output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def get_objects_or_children_by_type(self, *types):
""" Get objects if children already been read or get children.
Use this method for fast access to objects in case of static configurations.
:param types: requested object types.
:return: all children of the specified types.
"""... | Can you create a Python 3 function that
gets objects if children already been read or get children of the requested types. | You are a Python code generator, capable of creating scripts from specifications. |
Get object if child already been read or get child. | Make a summary of the following Python 3 code
def get_object_or_child_by_type(self, *types):
objects = self.get_objects_or_children_by_type(*types)
return objects[0] if any(objects) else None | As a python code expert, you are capable of creating scripts from specifications. |
Get all objects of the requested type and all child types. | Make a summary of the following Python 3 code
def get_objects_with_object(self, obj_type, *child_types):
return [o for o in self.get_objects_by_type(obj_type) if
o.get_objects_by_type(*child_types)] | You are a Python code generator, capable of creating scripts from specifications. |
Returns a list of objects of the requested type but not including the requested child types. | Can you tell what is the following Python 3 function doing
def get_objects_without_object(self, obj_type, *child_types):
return [o for o in self.get_objects_by_type(obj_type) if
not o.get_objects_by_type(*child_types)] | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_objects_with_attribute(self, obj_type, attribute, value):
"""
:param obj_type: requested object type.
:param attribute: requested attribute.
:param value: requested attribute value.
:return: all children of the requested type that have the requested attribute == requested... | Implement a function in Python 3 to
return a list of objects of the requested type with the requested attribute and value. | You are a Python code analyst, evaluating scripts for potential improvements. |
returns the ancestor of the object of the requested type. | Can you tell what is the following Python 3 function doing
def get_ancestor_object_by_type(self, obj_type):
if self.type.lower() == obj_type.lower():
return self
else:
if not self.parent:
return None
return self.parent.get_ancestor_object_by_type(obj_... | As a python code expert, you are capable of creating scripts from specifications. |
Delete object from parent object. | Can you generate a brief explanation for the following Python 3 code
def del_object_from_parent(self):
if self.parent:
self.parent.objects.pop(self.ref) | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns a list of all objects of the requested class. | Can you generate a brief explanation for the following Python 3 code
def get_objects_of_class(cls):
return list(o for o in gc.get_objects() if isinstance(o, cls)) | You are a Python code generator, capable of creating scripts from specifications. |
def _handle_sighup(myrpcserver, signum, unused):
"""Closes (terminates) all of its clients. Though keeps server running."""
print("SIGHUP: stopping all clients",sys.stderr)
if myrpcserver._closed:
return
for c in set(myrpcserver.clients):
try:
c.shutdown(socket.SHUT_RDWR)
... | Can you implement a function in Python 3 that
closes (terminates) all of its clients. Though keeps server running. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def split_strings(string, separators):
"""
Split a string with arbitrary number of separators.
Return a list with the splitted values
Arguments:
string (str): ex. "a:1|2,b:2"
separators (list): ex. [',',':','|']
Returns:
results (list) : ex. ['a','1','2','b','2']
... | Implement a Python 3 function for
splitting a string into two lists of strings. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _idToStr(self, x):
"""
Convert VCD id in int to string
"""
if x < 0:
sign = -1
elif x == 0:
return self._idChars[0]
else:
sign = 1
x *= sign
digits = []
while x:
digits.append(self._idChars[x % se... | Implement a Python 3 function for
converting VCD id in int to string | As a Python code composer, you craft elegant and concise scripts. |
Add a variable to the current scope | Can you tell what is the following Python 3 function doing
def addVar(self, sig: object, name: str, sigType: VCD_SIG_TYPE, width: int,
valueFormatter: Callable[["Value"], str]):
"""
Add variable to scope
:ivar sig: user specified object to keep track of VcdVarInfo in change()
... | As a python code expert, you are capable of creating scripts from specifications. |
def varScope(self, name):
"""
Create sub variable scope with defined name
"""
ch = VcdVarWritingScope(name, self._writer, parent=self)
assert name not in self.children, name
self.children[name] = ch
return ch | Create a Python 3 function to
create a sub variable scope with defined name. | You are a Python code generator, capable of creating scripts from specifications. |
Wrapper for being able to launch all the threads. | Given the following Python 3 function, write the documentation
def multi_run_wrapper(params):
'''
Wrapper for being able to launch all the threads.
:param params: We receive the parameters as a tuple.
'''
zeronet, index, total, output_folder, overwrite = params
print "[" + str(index) + "... | You are a Python code generator, capable of creating scripts from specifications. |
Extract the domain from the URL. | Explain what the following Python 3 code does
def getDomainFromUrl(self, url):
try:
domain = re.findall( self.domainRegexp, url )[0]
except Exception, e:
errMsg = "ERROR. Something happened when trying to find the domain from <" + url + ">. Are you sure that the following regular... | As a Python code composer, you craft elegant and concise scripts. |
def _grabContentFromUrl(self, url):
"""
Function that abstracts capturing a URL. This method will be rewritten in child classes.
:param url: The URL to be processed.
:return: The response in a Json format.
"""
# Defining an empty object for th... | Write a Python 3 function that can
function that abstracts capturing a URL. This method will be rewritten in child classes. | You are a Python code generator, capable of creating scripts from specifications. |
This method wraps the extraction of the content and returns the response in a Json format. | Here you have a function in Python 3, explain what it does
def getResponse(self, url):
# Defining an empty object for the response
response = {}
try:
# This receives only the parameters needed by this Tor Wrapper:
# {
# "host" : "127.0.0.1"
# ... | You are a Python code generator, capable of creating scripts from specifications. |
def append_qs(url, query_string):
"""Append query_string values to an existing URL and return it as a string.
query_string can be:
* an encoded string: 'test3=val1&test3=val2'
* a dict of strings: {'test3': 'val'}
* a dict of lists of strings: {'test3': ['val1', 'val2']}
* a lis... | Write a Python 3 function for
appending query_string values to an existing URL and return it as a string. | You are a Python code architect, reviewing and designing scalable and efficient code |
URL encode unicode data. | How would you explain what the following Python 3 function does
def urlencode_unicode(data, doseq=0):
data_iter = None
if isdict(data):
data_iter = list(data.items())
elif islist(data):
data_iter = data
if data_iter:
for i, (key, value) in enumerate(data_iter):
if is... | As a python code expert, you are capable of creating scripts from specifications. |
This function will recursively loop through the values of a dict or list and return a list of all the keys and values in the order. create method. | How would you explain what the following Python 3 function does
def to_nested_php_args(data, prefix_key=None):
is_root = prefix_key is None
prefix_key = prefix_key if prefix_key else ''
if islist(data):
data_iter = data if is_root else enumerate(data)
new_data = [] if is_root else {}
el... | As a Python code analyst, you investigate and solve complex coding mysteries |
Parse Content - Disposition header to pull out the filename bit. | Can you tell what is the following Python 3 function doing
def get_filename(disposition):
if disposition:
params = [param.strip() for param in disposition.split(';')[1:]]
for param in params:
if '=' in param:
name, value = param.split('=', 1)
if name == 'f... | You are a Python code generator, capable of creating scripts from specifications. |
Returns a Tcl list of argument pairs. | Can you generate the documentation for the following Python 3 function
def get_args_pairs(arguments):
return ' '.join(' '.join(['-' + k, tcl_str(str(v))]) for k, v in arguments.items()) | You are a Python code architect, reviewing and designing scalable and efficient code |
Convert Tcl list to Python list using Tcl interpreter. | Here you have a function in Python 3, explain what it does
def tcl_list_2_py_list(tcl_list, within_tcl_str=False):
if not within_tcl_str:
tcl_list = tcl_str(tcl_list)
return tcl_interp_g.eval('join ' + tcl_list + ' LiStSeP').split('LiStSeP') if tcl_list else [] | You are a Python code architect, reviewing and designing scalable and efficient code |
def py_list_to_tcl_list(py_list):
""" Convert Python list to Tcl list using Tcl interpreter.
:param py_list: Python list.
:type py_list: list
:return: string representing the Tcl string equivalent to the Python list.
"""
py_list_str = [str(s) for s in py_list]
return tcl_str(tcl_interp_g.e... | Implement a function in Python 3 to
convert a Python list to Tcl list using Tcl interpreter. | You are a Python code analyst, evaluating scripts for potential improvements. |
@summary: Evaluate Tcl command.
@param command: command to evaluate.
@return: command output. | Can you generate a brief explanation for the following Python 3 code
def eval(self, command):
# Some operations (like take ownership) may take long time.
con_command_out = self._con.send_cmd(command, timeout=256)
if 'ERROR_SEND_CMD_EXIT_DUE_TO_TIMEOUT' in con_command_out:
raise Excep... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Execute Tcl command and return the command raw output. | Can you tell what is the following Python 3 function doing
def eval(self, command):
if self.logger.handlers:
self.logger.debug(command.decode('utf-8'))
if self.tcl_script:
self.tcl_script.info(command)
self.rc = self.tcl_interp.eval(command)
if self.logger.handle... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _grabContentFromUrl(self, url):
"""
Function that abstracts capturing a URL. This method rewrites the one from Wrapper.
:param url: The URL to be processed.
:return: The response in a Json format.
"""
# Defining an empty object for the res... | Write a Python 3 script for
functioning that abstracts capturing a URL. This method rewrites the one from Wrapper. :param url: The URL to be processed. :return: The response in a Json format. | You are a Python code generator, capable of creating scripts from specifications. |
append change from VCD file signal data series | Explain what the following Python 3 code does
def value_change(self, vcdId, value):
'''append change from VCD file signal data series'''
self.idcode2series[vcdId].append((self.now, value)) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Edit a record in Archivist s Toolkit using the provided new_record. | Can you generate a brief explanation for the following Python 3 code
def edit_record(self, new_record):
try:
record_id = new_record["id"]
except KeyError:
raise ValueError("No record ID provided!")
record_type = self.resource_type(record_id)
if record_type is Non... | As a python code expert, you are capable of creating scripts from specifications. |
Returns an array of all levels of description defined in this Archivist s Toolkit instance. | How would you explain what the following Python 3 function does
def get_levels_of_description(self):
if not hasattr(self, "levels_of_description"):
cursor = self.db.cursor()
levels = set()
cursor.execute("SELECT distinct(resourceLevel) FROM Resources")
for row in ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def collection_list(self, resource_id, resource_type="collection"):
"""
Fetches a list of all resource and component IDs within the specified resource.
:param long resource_id: The ID of the resource to fetch children from.
:param string resource_type: Specifies whether the resource to ... | Write a Python 3 script for
fetching a list of all resource and component IDs within the specified resource. | As a Python code analyst, you investigate and solve complex coding mysteries |
This function returns detailed metadata about the specified resource and its children. | Given the following Python 3 function, write the documentation
def get_resource_component_and_children(
self, resource_id, resource_type="collection", level=1, sort_data={}, **kwargs
):
"""
Fetch detailed metadata for the specified resource_id and all of its children.
:param long re... | As a Python code analyst, you investigate and solve complex coding mysteries |
def find_resource_id_for_component(self, component_id):
"""
Given the ID of a component, returns the parent resource ID.
If the immediate parent of the component is itself a component, this method will progress up the tree until a resource is found.
:param long component_id: The ID of ... | Write a Python 3 script to
find the parent resource ID for a given component. | As a python code expert, you are capable of creating scripts from specifications. |
def find_parent_id_for_component(self, component_id):
"""
Given the ID of a component, returns the parent component's ID.
:param string component_id: The ID of the component.
:return: A tuple containing:
* The type of the parent record; valid values are ArchivesSpaceClient.R... | How would you code a function in Python 3 to
give the ID of a component returns the parent component s ID. | As a Python code translator, you convert algorithms and pseudocode into Python. |
This method returns a list of all resource IDs for every resource in the database. | Can you generate a brief explanation for the following Python 3 code
def find_collection_ids(
self, search_pattern="", identifier="", page=None, page_size=30
):
"""
Fetches a list of all resource IDs for every resource in the database.
:param string search_pattern: A search pattern ... | You are a Python code architect, reviewing and designing scalable and efficient code |
def evaluate(self, flux, xo, yo, a, b, c):
"""
Evaluate the Gaussian model
Parameters
----------
flux : tf.Variable
xo, yo : tf.Variable, tf.Variable
Center coordiantes of the Gaussian.
a, b, c : tf.Variable, tf.Variable
Parameters that co... | Can you create a Python 3 function that
evaluates the Gaussian model for a specific entry. | You are a Python code architect, reviewing and designing scalable and efficient code |
def parse_log_line(line):
"""Parses a log line and returns it with more information
:param line: str - A line from a bcbio-nextgen log
:returns dict: A dictionary containing the line, if its a new step if its a Traceback or if the
analysis is finished
"""
matches = re.search(r'^\... | Write a Python 3 script to
parse a line from a bcbio - nextgen log file and returns it with more information | As a Python code composer, you craft elegant and concise scripts. |
def message(self):
"""Dictionary representation of the Event appropriate for JSON-encoding."""
return {
'timestamp': time.mktime(self.timestamp.timetuple())*1e3 + self.timestamp.microsecond/1e3,
'group': self.group_pk,
'participant': None if not self.participant else ... | How would you implement a function in Python 3 that
returns a dictionary representation of the Event appropriate for JSON - encoding. | You are a Python code generator, capable of creating scripts from specifications. |
Save an Event automatically sets the timestamp if not already set. | Make a summary of the following Python 3 code
def save(self, *args, **kwargs):
if self.timestamp is None:
self.timestamp = timezone.now()
super().save(*args, **kwargs) | As a Python code analyst, you investigate and solve complex coding mysteries |
Called by the WebSocket consumer when all players have connected. | Explain what the following Python 3 code does
def _on_connect(self, participant):
lock = get_redis_lock()
if not lock:
lock = fake_lock()
with lock:
self.refresh_from_db()
if self.ran_ready_function:
return
for player in self.get_p... | As a python code expert, you are capable of creating scripts from specifications. |
Trigger the : meth : when_player_disconnects callback. | Make a summary of the following Python 3 code
def _on_disconnect(self, participant):
player = None
for p in self.get_players():
if p.participant == participant:
player = p
break
self.when_player_disconnects(player) | You are a Python code architect, reviewing and designing scalable and efficient code |
def send(self, channel, payload):
"""Send a message with the given payload on the given channel.
Messages are broadcast to all players in the group.
"""
with track('send_channel=' + channel):
with track('create event'):
Event.objects.create(
... | Write a Python 3 script to
send a message with the given payload on the given channel. | As a python code expert, you are capable of creating scripts from specifications. |
Save the object to the database. | How would you explain what the following Python 3 function does
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
if self.pk is not None:
update_fields = kwargs.get('update_fields')
json_fields = {}
for field in self._meta.get_fields():
if... | You are a Python code generator, capable of creating scripts from specifications. |
def when_all_players_ready(self):
"""Initializes decisions based on ``player.initial_decision()``.
If :attr:`num_subperiods` is set, starts a timed task to run the
sub-periods.
"""
self.group_decisions = {}
self.subperiod_group_decisions = {}
for player in self.ge... | Can you implement a function in Python 3 that
calls by the AAF manager when all players are ready to run the main task. | You are a Python code generator, capable of creating scripts from specifications. |
def _subperiod_tick(self, current_interval, intervals):
"""Tick each sub-period, copying group_decisions to subperiod_group_decisions."""
self.refresh_from_db()
for key, value in self.group_decisions.items():
self.subperiod_group_decisions[key] = value
self.send('group_decis... | Can you write a function in Python 3 where it
ticks each sub - period copying group_decisions to subperiod_group_decisions. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _on_decisions_event(self, event=None, **kwargs):
"""Called when an Event is received on the decisions channel. Saves
the value in group_decisions. If num_subperiods is None, immediately
broadcasts the event back out on the group_decisions channel.
"""
if not self.ran_ready_fu... | How would you implement a function in Python 3 that
calls when an event is received on the decisions channel. Saves the value in group_decisions and sends the event back out on the group_decisions channel. | You are a Python code architect, reviewing and designing scalable and efficient code |
def clean(matrix):
"""Return a copy of given matrix where keys associated
to space values are discarded"""
return defaultdict(lambda: ' ', {
k: v for k, v in matrix.items() if v != ' '
}) | Write a Python 3 function for
returning a copy of given matrix where keys associated to space values are discarded | You are a Python code analyst, evaluating scripts for potential improvements. |
Yield lines generated from given matrix | Make a summary of the following Python 3 code
def build(matrix):
max_x = max(matrix, key=lambda t: t[0])[0]
min_x = min(matrix, key=lambda t: t[0])[0]
max_y = max(matrix, key=lambda t: t[1])[1]
min_y = min(matrix, key=lambda t: t[1])[1]
yield from (
# '{}:'.format(j).ljust(4) + ''.join(matri... | You are a Python code architect, reviewing and designing scalable and efficient code |
def next_unwrittable_on_row(view, coords):
"""Return position of the next (in row) letter that is unwrittable"""
x, y = coords
maxx = max(view.keys(), key=itemgetter(0))[0]
for offset in range(x + 1, maxx):
letter = view[offset, y]
if letter not in REWRITABLE_LETTERS:
return ... | Write a Python 3 function that can
return the position of the next unwrittable letter on a row. | As a python code expert, you are capable of creating scripts from specifications. |
Return the position of the next unwrittable letter in the column coords. | Here you have a function in Python 3, explain what it does
def next_unwrittable_on_col(view, coords):
x, y = coords
maxy = max(view.keys(), key=itemgetter(1))[1]
for offset in range(y + 1, maxy):
letter = view[x, offset]
if letter not in REWRITABLE_LETTERS:
return offset
retu... | You are a Python code architect, reviewing and designing scalable and efficient code |
Return the position of the previous unwrittable letter on a given row. | Can you tell what is the following Python 3 function doing
def previous_unwrittable_on_row(view, coords):
x, y = coords
minx = -1
for offset in range(x - 1, minx, -1):
letter = view[offset, y]
if letter not in REWRITABLE_LETTERS:
return offset
return None | As a Python code composer, you craft elegant and concise scripts. |
def previous_unwrittable_on_col(view, coords):
"""Return position of the previous (in column) letter that is unwrittable"""
x, y = coords
miny = -1
for offset in range(y - 1, miny, -1):
letter = view[x, offset]
if letter not in REWRITABLE_LETTERS:
return offset
return Non... | Can you create a Python 3 function that
returns the position of the previous unwrittable letter that is unwrittable on the column coords. | You are a Python code architect, reviewing and designing scalable and efficient code |
Build the base URL string based on host and port. | Here you have a function in Python 3, explain what it does
def _build_base_url(self, host, port):
parsed = urlparse(host)
if not parsed.scheme:
parsed = parsed._replace(scheme="http")
parsed = parsed._replace(path="")
netloc, parts = host, host.partition(":")
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def _format_notes(self, record):
"""
Extracts notes from a record and reformats them in a simplified format.
"""
notes = []
for note in record["notes"]:
if note.get("type"):
n = {}
n["type"] = note["type"]
try:
... | Write a Python 3 script to
extract notes from a record and reformats them in a simplified format. | As a Python code composer, you craft elegant and concise scripts. |
def _process_notes(record, new_record):
"""
Populate the notes property using the provided new_record.
If the new_record field was populated, assume that we want to replace
the notes. If there are valid changes to be made, they will be added to
the new_notes list. An empty list ... | Write a Python 3 function that can
process the notes field in the record and update the internal notes property with the new_record. | You are a Python code analyst, evaluating scripts for potential improvements. |
def _escape_solr_query(query, field="title"):
"""
Escapes special characters in Solr queries.
Note that this omits * - this is intentionally permitted in user queries.
The list of special characters is located at http://lucene.apache.org/core/4_0_0/queryparser/org/apache/lucene/querypars... | Create a Python 3 function for
escaping special characters in Solr queries. | As a python code expert, you are capable of creating scripts from specifications. |
def resource_type(self, resource_id):
"""
Given an ID, determines whether a given resource is a resource or a resource_component.
:param resource_id string: The URI of the resource whose type to determine.
:raises ArchivesSpaceError: if the resource_id does not appear to be either type.... | How would you implement a function in Python 3 that
determines whether a given resource is a resource or a resource_component. | You are a Python code architect, reviewing and designing scalable and efficient code |
Updates a record in ArchivesSpace using the provided new_record. | Make a summary of the following Python 3 code
def edit_record(self, new_record):
try:
record_id = new_record["id"]
except KeyError:
raise ValueError("No record ID provided!")
record = self.get_record(record_id)
# TODO: add more fields?
field_map = {"titl... | As a Python code composer, you craft elegant and concise scripts. |
Returns an array of all levels of description defined in this ArcivesSpace instance. | Can you tell what is the following Python 3 function doing
def get_levels_of_description(self):
if not hasattr(self, "levels_of_description"):
# TODO: * fetch human-formatted strings
# * is hardcoding this ID okay?
self.levels_of_description = self._get("/config/enumera... | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_resource_component_children(self, resource_component_id):
"""
Given a resource component, fetches detailed metadata for it and all of its children.
This is implemented using ArchivesSpaceClient.get_resource_component_children and uses its default options when fetching children.
... | Implement a function in Python 3 to
get detailed metadata for a resource component and all of its children. | As a Python code translator, you convert algorithms and pseudocode into Python. |
This function returns detailed metadata about the specified resource and all of its children. | Can you tell what is the following Python 3 function doing
def get_resource_component_and_children(
self,
resource_id,
resource_type="collection",
level=1,
sort_data={},
recurse_max_level=False,
sort_by=None,
**kwargs
):
"""
Fetch detai... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Given the URL to a component returns the parent component s URL. | How would you explain what the following Python 3 function does
def find_parent_id_for_component(self, component_id):
response = self.get_record(component_id)
if "parent" in response:
return (ArchivesSpaceClient.RESOURCE_COMPONENT, response["parent"]["ref"])
# if this is the top arch... | As a Python code composer, you craft elegant and concise scripts. |
Fetches a list of resource URLs for every resource in the database. | How would you explain what the following Python 3 function does
def find_collection_ids(self, search_pattern="", identifier="", fetched=0, page=1):
params = {"page": page, "q": "primary_type:resource"}
if search_pattern != "":
search_pattern = self._escape_solr_query(search_pattern, field="... | You are a Python code generator, capable of creating scripts from specifications. |
Fetches a list of all resource IDs for every resource in the database. | Explain what the following Python 3 code does
def find_collections(
self,
search_pattern="",
identifier="",
fetched=0,
page=1,
page_size=30,
sort_by=None,
):
"""
Fetches a list of all resource IDs for every resource in the database.
:p... | You are a Python code architect, reviewing and designing scalable and efficient code |
def find_by_id(self, object_type, field, value):
"""
Find resource by a specific ID.
Results are a dict in the format:
{
'id': <resource URI fragment>,
'identifier': <resource identifier>,
'title': <title of the resource>,
'levelOfDescript... | How would you code a function in Python 3 to
find resource by a specific ID. | You are a Python code architect, reviewing and designing scalable and efficient code |
Adds a digital object to the archival object. | Make a summary of the following Python 3 code
def add_digital_object(
self,
parent_archival_object,
identifier,
title=None,
uri=None,
location_of_originals=None,
object_type="text",
xlink_show="embed",
xlink_actuate="onLoad",
restricted=Fal... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def add_child(
self,
parent,
title="",
level="",
start_date="",
end_date="",
date_expression="",
notes=[],
):
"""
Adds a new resource component parented within `parent`.
:param str parent: The ID to a resource or a resource com... | Write a Python 3 script for
adding a new child record to the current record. | You are a Python code generator, capable of creating scripts from specifications. |
Wrap a function as an attribute. | Can you generate the documentation for the following Python 3 function
def attribute(func):
attr = abc.abstractmethod(func)
attr.__iattribute__ = True
attr = _property(attr)
return attr | You are a Python code generator, capable of creating scripts from specifications. |
Wrap a function as a property. | Can you tell what is the following Python 3 function doing
def property(func):
attr = abc.abstractmethod(func)
attr.__iproperty__ = True
attr = Property(attr)
return attr | You are a Python code analyst, evaluating scripts for potential improvements. |
Wrap a function as a class attribute. | Can you tell what is the following Python 3 function doing
def classattribute(func):
attr = abc.abstractmethod(func)
attr.__iclassattribute__ = True
attr = _property(attr)
return attr | You are a Python code analyst, evaluating scripts for potential improvements. |
Wrap a function as a method. | Explain what the following Python 3 code does
def method(func):
attr = abc.abstractmethod(func)
attr.__imethod__ = True
return attr | As a Python code analyst, you investigate and solve complex coding mysteries |
def classmethod(func):
"""Wrap a function as a classmethod.
This applies the classmethod decorator.
"""
attr = abc.abstractmethod(func)
attr.__iclassmethod__ = True
attr = _classmethod(attr)
return attr | Can you create a Python 3 function that
wraps a function as a classmethod. | You are a Python code architect, reviewing and designing scalable and efficient code |
Parse a YAML configuration file | Can you generate the documentation for the following Python 3 function
def parse_config(config_file):
try:
with open(config_file, 'r') as f:
return yaml.load(f)
except IOError:
print "Configuration file {} not found or not readable.".format(config_file)
raise | As a python code expert, you are capable of creating scripts from specifications. |
Convert to a tuple of interfaces and raise if not interfaces. | Can you generate the documentation for the following Python 3 function
def _ensure_ifaces_tuple(ifaces):
try:
ifaces = tuple(ifaces)
except TypeError:
ifaces = (ifaces,)
for iface in ifaces:
if not _issubclass(iface, ibc.Iface):
raise TypeError('Can only compare aga... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Checks if a value is a valid definition of a value. | Can you tell what is the following Python 3 function doing
def _check_for_definition(iface, cls, tag, defines):
attributes = (
attr
for attr in iface.__abstractmethods__
if hasattr(getattr(iface, attr), tag)
)
for attribute in attributes:
for node in cls.__mro__:
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def issubclass(cls, ifaces):
"""Check if the given class is an implementation of the given iface."""
ifaces = _ensure_ifaces_tuple(ifaces)
for iface in ifaces:
return all((
_check_for_definition(
iface,
cls,
'__iclassattribute__',
... | Implement a Python 3 function for
checking if the given class is an implementation of the given iface. | As a Python code composer, you craft elegant and concise scripts. |
Check if a given instance is an implementation of the interface. | How would you explain what the following Python 3 function does
def isinstance(instance, ifaces):
ifaces = _ensure_ifaces_tuple(ifaces)
for iface in ifaces:
attributes = (
attr
for attr in iface.__abstractmethods__
if hasattr(getattr(iface, attr), '__iattribute__')
... | As a Python code composer, you craft elegant and concise scripts. |
def fit(self, pixel_flux, data_placeholder, var_list, session, feed_dict={}):
"""
Parameters
----------
pixel_flux : ndarray
The TPF-like pixel flux time series. The first dimension
must represent time, and the remaining two dimensions
must represent t... | Implement a function in Python 3 to
fit the optimizer on the TPF - like pixel flux time series. | As a python code expert, you are capable of creating scripts from specifications. |
Returns the splitted entry from the variant information | Can you tell what is the following Python 3 function doing
def get_entry(self, variant_line=None, variant_dict=None, raw_entry=None,
vcf_header=None, csq_format=None, dict_key=None, individual_id=None):
"""Return the splitted entry from variant information
Args:
var... | As a python code expert, you are capable of creating scripts from specifications. |
def get_raw_entry(self, variant_line=None, variant_dict=None,
vcf_header=None, individual_id=None, dict_key=None):
"""Return the raw entry from the vcf field
If no entry was found return None
Args:
variant_line (str): A vcf formated variant ... | Write a Python 3 script to
return the raw entry from the vcf field if no entry was found return None | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get the value of the attribute in the correct format | Make a summary of the following Python 3 code
def get_value(self, variant_line=None, variant_dict=None, entry=None,
raw_entry=None, vcf_header=None, csq_format=None, dict_key=None,
individual_id=None):
"""
Return the value as specified by plugin
Get value will return o... | You are a Python code analyst, evaluating scripts for potential improvements. |
def create_layout(graph, graphviz_prog=DEFAULT_GRAPHVIZ_PROG):
"""Return {node: position} for given graph"""
graphviz_layout = graphutils.graphviz_layout(graph, prog=graphviz_prog)
# print('GRAPHIZ LAYOUT:', graphviz_layout)
layout = {k: (int(x // 10), int(y // 10))
for k, (x, y) in graphv... | Can you create a Python 3 function that
creates a layout for a given graph | You are a Python code analyst, evaluating scripts for potential improvements. |
def pretty_view(graph, oriented=False, construction=False,
graphviz_prog=DEFAULT_GRAPHVIZ_PROG):
"""Yield strings, printable view of given graph"""
layout = create_layout(graph, graphviz_prog=graphviz_prog)
matrix_view = defaultdict(lambda: ' ')
# Add the edge to the view
# print('... | Can you create a Python 3 function that
yields a string representation of a graph in a pretty way. | You are a Python code analyst, evaluating scripts for potential improvements. |
def _get_call_class(method):
"""Find the call class for method if it exists else create one."""
call_base, call_name = method.split('.', 1)
# import the call class's module
mod = __import__('ubersmith.calls.{0}'.format(call_base), fromlist=[''])
# grab all the public members of the module
gen = ... | Can you write a function in Python 3 where it
finds the call class for a given method if it exists else create one. | You are a Python code architect, reviewing and designing scalable and efficient code |
Validate process clean and return the result of the call. | Can you generate the documentation for the following Python 3 function
def render(self):
if not self.validate():
raise ValidationError
self.process_request()
self.clean()
return self.response | You are a Python code analyst, evaluating scripts for potential improvements. |
def validate(self):
"""Validate request data before sending it out. Return True/False."""
# check if required_fields aren't present
for field in set(self.required_fields) - set(self.request_data):
if not isinstance(field, string_types):
# field was a collection, itera... | Implement a Python 3 function for
validating request data before sending it out. Return True or False. | As a Python code composer, you craft elegant and concise scripts. |
def process_request(self):
"""Processing the call and set response_data."""
self.response = self.request_handler.process_request(
self.method, self.request_data) | How would you implement a function in Python 3 that
processes the call and set response_data. | As a Python code composer, you craft elegant and concise scripts. |
def total_ordering(cls): # pragma: no cover
"""Class decorator that fills in missing ordering methods"""
convert = {
'__lt__': [('__gt__', lambda self, other: not (self < other or self == other)),
('__le__', lambda self, other: self < other or self == other),
('__g... | Write a Python 3 function that can
class decorator that creates a new class that extends the base class with the total ordering methods. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def init_logger_file(log_file, log_level='INFO'):
""" Append a FileHandler to the root logger.
:param str log_file: Path to the log file
:param str log_level: Logging level
"""
log_level = LOG_LEVELS[log_level] if log_level in LOG_LEVELS.keys() else logging.INFO
ROOT_LOG.setLevel(log_level)
... | Can you write a function in Python 3 where it
initializes the logger with a file. | You are a Python code architect, reviewing and designing scalable and efficient code |
def load_signing_key(signing_key, crypto_backend=default_backend()):
""" Optional: crypto backend object from the "cryptography" python library
"""
if not isinstance(crypto_backend, (Backend, MultiBackend)):
raise ValueError('backend must be a valid Backend object')
if isinstance(signing_key, E... | How would you code a function in Python 3 to
load a private key from the cryptography library. | You are a Python code analyst, evaluating scripts for potential improvements. |
Load a verification key from the cryptography library. | Can you generate a brief explanation for the following Python 3 code
def load_verifying_key(verifying_key, crypto_backend=default_backend()):
if not isinstance(crypto_backend, (Backend, MultiBackend)):
raise ValueError('backend must be a valid Backend object')
if isinstance(verifying_key, EllipticCurve... | As a python code expert, you are capable of creating scripts from specifications. |
Extracts notes from a record and reformats them in a simplified format. | How would you explain what the following Python 3 function does
def _format_notes(self, record):
notes = []
if "notes" in record:
for note in record["notes"]:
self._append_note_dict_to_list(notes, "general", note)
if "language_and_script_notes" in record:
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Escapes special characters in Solr queries. | Explain what the following Python 3 code does
def _escape_lucene_query(query, field=None):
replacement = r"\\\1"
return re.sub(r'([\'" +\-!\(\)\{\}\[\]^"~?:\\/]|&&|\|\|)', replacement, query) | As a python code expert, you are capable of creating scripts from specifications. |
def edit_record(self, new_record):
"""
Update a record in AtoM using the provided new_record.
The format of new_record is identical to the format returned by get_resource_component_and_children and related methods; consult the documentation for that method in ArchivistsToolkitClient to see the ... | Can you write a function in Python 3 where it
updates a record in AtoM using the provided new_record. | As a python code expert, you are capable of creating scripts from specifications. |
Returns an array of all levels of description defined in this AtoM instance. | Can you generate the documentation for the following Python 3 function
def get_levels_of_description(self):
if not hasattr(self, "levels_of_description"):
self.levels_of_description = [
item["name"]
for item in self._get(urljoin(self.base_url, "taxonomies/34")).json()... | As a Python code composer, you craft elegant and concise scripts. |
Fetches a list of slugs representing descriptions within the specified parent description. | Can you tell what is the following Python 3 function doing
def collection_list(self, resource_id, resource_type="collection"):
def fetch_children(children):
results = []
for child in children:
results.append(child["slug"])
if "children" in child:
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
This function returns detailed metadata about the specified resource and all of its children. | Can you tell what is the following Python 3 function doing
def get_resource_component_and_children(
self,
resource_id,
resource_type="collection",
level=1,
sort_data={},
recurse_max_level=False,
sort_by=None,
**kwargs
):
"""
Fetch detai... | You are a Python code architect, reviewing and designing scalable and efficient code |
def find_parent_id_for_component(self, slug):
"""
Given the slug of a description, returns the parent description's slug.
:param string slug: The slug of a description.
:return: The URL of the parent record.
:rtype: string
"""
response = self.get_record(slug)
... | Write a Python 3 function for
giving the slug of a description returns the parent description s slug. | You are a Python code generator, capable of creating scripts from specifications. |
Fetches a list of resource URLs for every top - level description in the database. | Given the following Python 3 function, write the documentation
def find_collection_ids(self, search_pattern="", identifier="", fetched=0, page=1):
response = self._collections_search_request(search_pattern, identifier, page)
hits = response.json()
results = [r["slug"] for r in hits["results"]]
... | As a python code expert, you are capable of creating scripts from specifications. |
This method is used to make a request to retrieve a list of resource URLs for every top - level description in the database. | Here you have a function in Python 3, explain what it does
def _collections_search_request(
self, search_pattern="", identifier="", page=1, page_size=50, sort_by=None
):
"""
Fetches a list of resource URLs for every top-level description in the database.
:param string search_pattern... | 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.