output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Read the success byte and initialize the internal attributes. | Can you generate the documentation for the following Python 3 function
def _init(self):
self._api_version = self._file.read(1)[0]
self._firmware_version = FirmwareVersion(*self._file.read(2)) | You are a Python code analyst, evaluating scripts for potential improvements. |
def _init(self):
"""Read the line number."""
self._line_number = next_line(
self._communication.last_requested_line_number,
self._file.read(1)[0]) | How would you code a function in Python 3 to
read the line number. | As a Python code composer, you craft elegant and concise scripts. |
Read the success byte and initialize the internal state. | Can you tell what is the following Python 3 function doing
def _init(self):
self._ready = self._file.read(1)
self._hall_left = self._file.read(2)
self._hall_right = self._file.read(2)
self._carriage_type = self._file.read(1)[0]
self._carriage_position = self._file.read(1)[0] | You are a Python code architect, reviewing and designing scalable and efficient code |
Read the b\\ r \\ n at the end of the message. | Can you generate the documentation for the following Python 3 function
def _init(self):
read_values = []
read = self._file.read
last = read(1)
current = read(1)
while last != b'' and current != b'' and not \
(last == b'\r' and current == b'\n'):
read_v... | You are a Python code analyst, evaluating scripts for potential improvements. |
def send(self):
"""Send this message to the controller."""
self._file.write(self.as_bytes())
self._file.write(b'\r\n') | Create a Python 3 function to
send this message to the controller. | As a Python code analyst, you investigate and solve complex coding mysteries |
def init(self, left_end_needle, right_end_needle):
"""Initialize the StartRequest with start and stop needle.
:raises TypeError: if the arguments are not integers
:raises ValueError: if the values do not match the
:ref:`specification <m4-01>`
"""
if not isinstance(left... | How would you code a function in Python 3 to
initialize the StartRequest with start and stop needle. | You are a Python code architect, reviewing and designing scalable and efficient code |
def content_bytes(self):
"""Return the start and stop needle."""
get_message = \
self._communication.needle_positions.get_line_configuration_message
return get_message(self._line_number) | Can you implement a function in Python 3 that
returns the start and stop needle. | As a python code expert, you are capable of creating scripts from specifications. |
Sum up an iterable starting with a start value. | Given the following Python 3 function, write the documentation
def sum_all(iterable, start):
if hasattr(start, "__add__"):
for value in iterable:
start += value
else:
for value in iterable:
start |= value
return start | As a Python code composer, you craft elegant and concise scripts. |
Compute the next line based on the last line and a 8bit next line. | Given the following Python 3 function, write the documentation
def next_line(last_line, next_line_8bit):
# compute the line without the lowest byte
base_line = last_line - (last_line & 255)
# compute the three different lines
line = base_line + next_line_8bit
lower_line = line - 256
upper_line =... | You are a Python code architect, reviewing and designing scalable and efficient code |
def camel_case_to_under_score(camel_case_name):
"""Return the underscore name of a camel case name.
:param str camel_case_name: a name in camel case such as
``"ACamelCaseName"``
:return: the name using underscores, e.g. ``"a_camel_case_name"``
:rtype: str
"""
result = []
for letter in... | Implement a Python 3 function for
returning the underscore name of a camel case name. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Notify the observers about the received message. | Can you generate the documentation for the following Python 3 function
def _message_received(self, message):
with self.lock:
self._state.receive_message(message)
for callable in chain(self._on_message_received, self._on_message):
callable(message) | As a Python code composer, you craft elegant and concise scripts. |
def receive_message(self):
"""Receive a message from the file."""
with self.lock:
assert self.can_receive_messages()
message_type = self._read_message_type(self._file)
message = message_type(self._file, self)
self._message_received(message) | Can you write a function in Python 3 where it
receives a message from the file. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def can_receive_messages(self):
"""Whether tihs communication is ready to receive messages.]
:rtype: bool
.. code:: python
assert not communication.can_receive_messages()
communication.start()
assert communication.can_receive_messages()
communic... | Write a Python 3 function for
returning True if the tihs communication can receive messages. | As a Python code composer, you craft elegant and concise scripts. |
def stop(self):
"""Stop the communication with the shield."""
with self.lock:
self._message_received(ConnectionClosed(self._file, self)) | Implement a Python 3 function for
stopping the communication with the shield. | You are a Python code analyst, evaluating scripts for potential improvements. |
Send a host message. | Given the following Python 3 function, write the documentation
def send(self, host_message_class, *args):
message = host_message_class(self._file, self, *args)
with self.lock:
message.send()
for callable in self._on_message:
callable(message) | As a Python code analyst, you investigate and solve complex coding mysteries |
Set the state of the resource. | Can you tell what is the following Python 3 function doing
def state(self, new_state):
with self.lock:
self._state.exit()
self._state = new_state
self._state.enter() | As a Python code composer, you craft elegant and concise scripts. |
Start a thread for receiving messages. | How would you explain what the following Python 3 function does
def parallelize(self, seconds_to_wait=2):
with self.lock:
thread = Thread(target=self._parallel_receive_loop,
args=(seconds_to_wait,))
thread.deamon = True
thread.start()
s... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _parallel_receive_loop(self, seconds_to_wait):
"""Run the receiving in parallel."""
sleep(seconds_to_wait)
with self._lock:
self._number_of_threads_receiving_messages += 1
try:
with self._lock:
if self.state.is_waiting_for_start():
... | Can you implement a function in Python 3 that
runs the receiving in parallel. | You are a Python code architect, reviewing and designing scalable and efficient code |
def _next(self, state_class, *args):
"""Transition into the next state.
:param type state_class: a subclass of :class:`State`. It is intialized
with the communication object and :paramref:`args`
:param args: additional arguments
"""
self._communication.state = state_cl... | Write a Python 3 function that can
transition into the next state. | As a Python code analyst, you investigate and solve complex coding mysteries |
A InformationConfirmation is received. | Make a summary of the following Python 3 code
def receive_information_confirmation(self, message):
if message.api_version_is_supported():
self._next(InitializingMachine)
else:
self._next(UnsupportedApiVersion)
self._communication.controller = message | As a Python code composer, you craft elegant and concise scripts. |
def receive_start_confirmation(self, message):
"""Receive a StartConfirmation message.
:param message: a :class:`StartConfirmation
<AYABInterface.communication.hardware_messages.StartConfirmation>`
message
If the message indicates success, the communication object transitio... | Write a Python 3 script to
receive a StartConfirmation message. | As a Python code composer, you craft elegant and concise scripts. |
Send a LineConfirmation to the controller. | Can you tell what is the following Python 3 function doing
def enter(self):
self._communication.last_requested_line_number = self._line_number
self._communication.send(LineConfirmation, self._line_number) | As a Python code composer, you craft elegant and concise scripts. |
def colors_to_needle_positions(rows):
"""Convert rows to needle positions.
:return:
:rtype: list
"""
needles = []
for row in rows:
colors = set(row)
if len(colors) == 1:
needles.append([NeedlePositions(row, tuple(colors), False)])
elif len(colors) == 2:
... | Can you create a Python 3 function that
converts rows to needle positions. | You are a Python code architect, reviewing and designing scalable and efficient code |
def check(self):
"""Check for validity.
:raises ValueError:
- if not all lines are as long as the :attr:`number of needles
<AYABInterface.machines.Machine.number_of_needles>`
- if the contents of the rows are not :attr:`needle positions
<AYABInterface.machin... | Write a Python 3 script for
checking that the contents of the rows of the log file are valid. | You are a Python code generator, capable of creating scripts from specifications. |
def get_row(self, index, default=None):
"""Return the row at the given index or the default value."""
if not isinstance(index, int) or index < 0 or index >= len(self._rows):
return default
return self._rows[index] | Write a Python 3 script to
return the row at the given index or the default value. | As a Python code analyst, you investigate and solve complex coding mysteries |
def row_completed(self, index):
"""Mark the row at index as completed.
.. seealso:: :meth:`completed_row_indices`
This method notifies the obsevrers from :meth:`on_row_completed`.
"""
self._completed_rows.append(index)
for row_completed in self._on_row_completed:
... | Can you create a Python 3 function that
marks the row at index as completed. | You are a Python code generator, capable of creating scripts from specifications. |
A list of actions to perform. | Given the following Python 3 function, write the documentation
def actions(self):
actions = []
do = actions.append
# determine the number of colors
colors = self.colors
# rows and colors
movements = (
MoveCarriageToTheRight(KnitCarriage()),
MoveC... | You are a Python code architect, reviewing and designing scalable and efficient code |
def needle_positions_to_bytes(self, needle_positions):
"""Convert the needle positions to the wire format.
This conversion is used for :ref:`cnfline`.
:param needle_positions: an iterable over :attr:`needle_positions` of
length :attr:`number_of_needles`
:rtype: bytes
... | Write a Python 3 function for
converting the needle positions to the wire format. | As a python code expert, you are capable of creating scripts from specifications. |
The identifier of the machine. | Can you generate the documentation for the following Python 3 function
def name(self):
name = self.__class__.__name__
for i, character in enumerate(name):
if character.isdigit():
return name[:i] + "-" + name[i:]
return name | As a Python code composer, you craft elegant and concise scripts. |
What this object is equal to. | Can you generate a brief explanation for the following Python 3 code
def _id(self):
return (self.__class__, self.number_of_needles, self.needle_positions,
self.left_end_needle) | You are a Python code generator, capable of creating scripts from specifications. |
def add_chapter(self, c):
"""
Add a Chapter to your epub.
Args:
c (Chapter): A Chapter object representing your chapter.
Raises:
TypeError: Raised if a Chapter object isn't supplied to this
method.
"""
try:
assert type... | Write a Python 3 function that can
add a Chapter to the epub. | You are a Python code analyst, evaluating scripts for potential improvements. |
Creates an epub file from this object. | Can you generate the documentation for the following Python 3 function
def create_epub(self, output_directory, epub_name=None):
def createTOCs_and_ContentOPF():
for epub_file, name in ((self.toc_html, 'toc.html'), (self.toc_ncx, 'toc.ncx'), (self.opf, 'content.opf'),):
epub_file.add_... | As a Python code analyst, you investigate and solve complex coding mysteries |
Saves an online image from image_url to image_directory with the name image_name. | Explain what the following Python 3 code does
def save_image(image_url, image_directory, image_name):
image_type = get_image_type(image_url)
if image_type is None:
raise ImageErrorException(image_url)
full_image_file_name = os.path.join(image_directory, image_name + '.' + image_type)
# If the i... | As a python code expert, you are capable of creating scripts from specifications. |
def _replace_image(image_url, image_tag, ebook_folder,
image_name=None):
"""
Replaces the src of an image to link to the local copy in the images folder of the ebook. Tightly coupled with bs4
package.
Args:
image_url (str): The url of the image.
image_tag (bs4.ele... | Create a Python 3 function to
replace the src of an image in the ebook with the local copy in the images folder of the ebook. | As a python code expert, you are capable of creating scripts from specifications. |
Writes the chapter object to an xhtml file. | Given the following Python 3 function, write the documentation
def write(self, file_name):
try:
assert file_name[-6:] == '.xhtml'
except (AssertionError, IndexError):
raise ValueError('filename must end with .xhtml')
with open(file_name, 'wb') as f:
f.write(se... | As a Python code analyst, you investigate and solve complex coding mysteries |
def create_chapter_from_url(self, url, title=None):
"""
Creates a Chapter object from a url. Pulls the webpage from the
given url, sanitizes it using the clean_function method, and saves
it as the content of the created chapter. Basic webpage loaded
before any javascript executed... | How would you implement a function in Python 3 that
creates a Chapter object from a given url. | You are a Python code analyst, evaluating scripts for potential improvements. |
Creates a Chapter object from a file. | Make a summary of the following Python 3 code
def create_chapter_from_file(self, file_name, url=None, title=None):
with codecs.open(file_name, 'r', encoding='utf-8') as f:
content_string = f.read()
return self.create_chapter_from_string(content_string, url, title) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def create_chapter_from_string(self, html_string, url=None, title=None):
"""
Creates a Chapter object from a string. Sanitizes the
string using the clean_function method, and saves
it as the content of the created chapter.
Args:
html_string (string): The html or xhtm... | How would you code a function in Python 3 to
create a Chapter object from a string. | You are a Python code analyst, evaluating scripts for potential improvements. |
def create_html_from_fragment(tag):
"""
Creates full html tree from a fragment. Assumes that tag should be wrapped in a body and is currently not
Args:
tag: a bs4.element.Tag
Returns:"
bs4.element.Tag: A bs4 tag representing a full html document
"""
try:
assert isinsta... | Implement a function in Python 3 to
create full html tree from a fragment. Assumes that the tag is wrapped in a body. | As a Python code analyst, you investigate and solve complex coding mysteries |
def clean(input_string,
tag_dictionary=constants.SUPPORTED_TAGS):
"""
Sanitizes HTML. Tags not contained as keys in the tag_dictionary input are
removed, and child nodes are recursively moved to parent of removed node.
Attributes not contained as arguments in tag_dictionary are removed.
Do... | How would you code a function in Python 3 to
sanitize HTML. Tags not contained as keys in the tag_dictionary input are removed, and child nodes are recursively moved to parent of removed node. Attributes not contained as arguments in tag_dictionary are removed. Doctype is set to <!DOCTYPE html>. Args: input_string (bas... | As a python code expert, you are capable of creating scripts from specifications. |
Removes leading and trailing whitespace between tags in an html document. | Can you generate a brief explanation for the following Python 3 code
def condense(input_string):
try:
assert isinstance(input_string, basestring)
except AssertionError:
raise TypeError
removed_leading_whitespace = re.sub('>\s+', '>', input_string).strip()
removed_trailing_whitespace = re... | You are a Python code generator, capable of creating scripts from specifications. |
Converts a unicode string representing HTML to XHTML. | Make a summary of the following Python 3 code
def html_to_xhtml(html_unicode_string):
try:
assert isinstance(html_unicode_string, basestring)
except AssertionError:
raise TypeError
root = BeautifulSoup(html_unicode_string, 'html.parser')
# Confirm root node is html
try:
asser... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _merge_dicts(self, dict1, dict2, path=[]):
"merges dict2 into dict1"
for key in dict2:
if key in dict1:
if isinstance(dict1[key], dict) and isinstance(dict2[key], dict):
self._merge_dicts(dict1[key], dict2[key], path + [str(key)])
elif ... | Implement a function in Python 3 to
merge dict2 into dict1 | As a python code expert, you are capable of creating scripts from specifications. |
A helper function to add the statements to the list of statements. | Given the following Python 3 function, write the documentation
def p_statements(self, p):
n = len(p)
if n == 3:
p[0] = p[1] + [p[2]]
elif n == 2:
p[0] = ['statements', p[1]] | You are a Python code analyst, evaluating scripts for potential improvements. |
contents section of the log | Here you have a function in Python 3, explain what it does
def p_contents(self, p):
n = len(p)
if n == 3:
p[0] = p[1] + [p[2]]
else:
p[0] = ['contents', p[1]] | As a Python code analyst, you investigate and solve complex coding mysteries |
def p_block(self, p):
"""block : OPEN_TAG contents CLOSE_TAG
| OPEN_TAG CLOSE_TAG
| OPEN_CLOSE_TAG
"""
n = len(p)
if n == 4:
p[0] = ['block', p[1], p[2], p[3]]
elif n == 3:
p[0] = ['block', p[1], [], p[2]]
else:
... | Write a Python 3 script for
parsing the block tag | You are a Python code analyst, evaluating scripts for potential improvements. |
r \ * \ * | Make a summary of the following Python 3 code
def t_CCOMMENT(self, t):
r'\/\*'
t.lexer.code_start = t.lexer.lexpos
t.lexer.ccomment_level = 1 # Initial comment level
t.lexer.begin('ccomment') | You are a Python code architect, reviewing and designing scalable and efficient code |
t_OPTION_AND_VALUE returns a tuple of option and value | Can you generate the documentation for the following Python 3 function
def t_OPTION_AND_VALUE(self, t):
r'[^ \n\r\t=#]+[ \t=]+[^\r\n#]+' # TODO(etingof) escape hash
if t.value.endswith('\\'):
t.lexer.multiline_newline_seen = False
t.lexer.code_start = t.lexer.lexpos - len(t.valu... | You are a Python code architect, reviewing and designing scalable and efficient code |
t_multiline_OPTION_AND_VALUE t. lexer. begin | Given the following Python 3 function, write the documentation
def t_multiline_OPTION_AND_VALUE(self, t):
r'[^\r\n]+'
t.lexer.multiline_newline_seen = False
if t.value.endswith('\\'):
return
t.type = "OPTION_AND_VALUE"
t.lexer.begin('INITIAL')
value = t.lex... | You are a Python code architect, reviewing and designing scalable and efficient code |
def set_default(cls, name):
"""Replaces the current application default depot"""
if name not in cls._depots:
raise RuntimeError('%s depot has not been configured' % (name,))
cls._default_depot = name | Can you create a Python 3 function that
replaces the current application default depot | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get(cls, name=None):
"""Gets the application wide depot instance.
Might return ``None`` if :meth:`configure` has not been
called yet.
"""
if name is None:
name = cls._default_depot
name = cls.resolve_alias(name) # resolve alias
return cls._depo... | Write a Python 3 script to
get the application wide depot instance. | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_file(cls, path):
"""Retrieves a file by storage name and fileid in the form of a path
Path is expected to be ``storage_name/fileid``.
"""
depot_name, file_id = path.split('/', 1)
depot = cls.get(depot_name)
return depot.get(file_id) | Can you create a Python 3 function that
retrieves a file by storage name and fileid in the form of a path. | As a Python code composer, you craft elegant and concise scripts. |
Configures an application wide depot. | Can you generate a brief explanation for the following Python 3 code
def configure(cls, name, config, prefix='depot.'):
if name in cls._depots:
raise RuntimeError('Depot %s has already been configured' % (name,))
if cls._default_depot is None:
cls._default_depot = name
... | As a python code expert, you are capable of creating scripts from specifications. |
Creates the application WSGI middleware in charge of serving local files from a local file storage and a gridFS storage. | Given the following Python 3 function, write the documentation
def make_middleware(cls, app, **options):
from depot.middleware import DepotMiddleware
mw = DepotMiddleware(app, **options)
cls.set_middleware(mw)
return mw | As a Python code translator, you convert algorithms and pseudocode into Python. |
Creates a new depot from a settings dictionary. | Can you generate the documentation for the following Python 3 function
def from_config(cls, config, prefix='depot.'):
config = config or {}
# Get preferred storage backend
backend = config.get(prefix + 'backend', 'depot.io.local.LocalFileStorage')
# Get all options
prefixlen = ... | As a Python code composer, you craft elegant and concise scripts. |
def _clear(cls):
"""This is only for testing pourposes, resets the DepotManager status
This is to simplify writing test fixtures, resets the DepotManager global
status and removes the informations related to the current configured depots
and middleware.
"""
cls._default_... | Write a Python 3 function that can
reset the status of the current set of DepotManager items. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Place any commands to setup depotexample here | Make a summary of the following Python 3 code
def setup_schema(command, conf, vars):
# Load the models
# <websetup.websetup.schema.before.model.import>
from depotexample import model
# <websetup.websetup.schema.after.model.import>
# <websetup.websetup.schema.before.metadata.create_all>
pr... | As a python code expert, you are capable of creating scripts from specifications. |
Return a set with all permissions granted to the user. | Given the following Python 3 function, write the documentation
def permissions(self):
perms = set()
for g in self.groups:
perms = perms | set(g.permissions)
return perms | As a python code expert, you are capable of creating scripts from specifications. |
Return the user object whose email address is email. | Explain what the following Python 3 code does
def by_email_address(cls, email):
return DBSession.query(cls).filter_by(email_address=email).first() | You are a Python code analyst, evaluating scripts for potential improvements. |
Return the user object whose user name is username. | Explain what the following Python 3 code does
def by_user_name(cls, username):
return DBSession.query(cls).filter_by(user_name=username).first() | As a Python code translator, you convert algorithms and pseudocode into Python. |
def validate_password(self, password):
"""
Check the password against existing credentials.
:param password: the password that was provided by the user to
try and authenticate. This is the clear text version that we will
need to match against the hashed one in the databa... | Implement a function in Python 3 to
check the password against existing credentials. | As a Python code composer, you craft elegant and concise scripts. |
def document(self, *args, **kwargs):
"""Render the error document"""
resp = request.environ.get('pylons.original_response')
default_message = ("<p>We're sorry but we weren't able to process "
" this request.</p>")
values = dict(prefix=request.environ.get('SCRIP... | Create a Python 3 function to
render the error document | As a Python code analyst, you investigate and solve complex coding mysteries |
def make_app(global_conf, full_stack=True, **app_conf):
"""
Set depotexample up with the settings found in the PasteDeploy configuration
file used.
:param global_conf: The global settings for depotexample (those
defined under the ``[DEFAULT]`` section).
:type global_conf: dict
:para... | How would you implement a function in Python 3 that
creates a new TurboGears 2 application with all the relevant middleware and settings. | As a Python code analyst, you investigate and solve complex coding mysteries |
def bootstrap(command, conf, vars):
"""Place any commands to setup depotexample here"""
# <websetup.bootstrap.before.auth
from sqlalchemy.exc import IntegrityError
try:
u = model.User()
u.user_name = 'manager'
u.display_name = 'Example manager'
u.email_address = 'manager... | How would you code a function in Python 3 to
place any commands to setup depotexample here | You are a Python code generator, capable of creating scripts from specifications. |
Provides a real file object from a cgi. FieldStorage FileIntent and bytes. | Here you have a function in Python 3, explain what it does
def file_from_content(content):
f = content
if isinstance(content, cgi.FieldStorage):
f = content.file
elif isinstance(content, FileIntent):
f = content._fileobj
elif isinstance(content, byte_string):
f = SpooledTemporary... | You are a Python code analyst, evaluating scripts for potential improvements. |
def fileinfo(fileobj, filename=None, content_type=None, existing=None):
"""Tries to extract from the given input the actual file object, filename and content_type
This is used by the create and replace methods to correctly deduce their parameters
from the available information when possible.
... | Can you write a function in Python 3 where it
tries to extract from the given input the actual file object filename and content_type and existing. Returns None if no information was found. | You are a Python code architect, reviewing and designing scalable and efficient code |
def login(self, came_from=lurl('/')):
"""Start the user login."""
login_counter = request.environ.get('repoze.who.logins', 0)
if login_counter > 0:
flash(_('Wrong credentials'), 'warning')
return dict(page='login', login_counter=str(login_counter),
came_fr... | How would you code a function in Python 3 to
start the user login. | As a python code expert, you are capable of creating scripts from specifications. |
Redirect the user to the initially requested page on successful
authentication or redirect her back to the login page on successful
authentication or redirect her back to the login page on successful
authentication. | How would you explain what the following Python 3 function does
def post_login(self, came_from=lurl('/')):
if not request.identity:
login_counter = request.environ.get('repoze.who.logins', 0) + 1
redirect('/login',
params=dict(came_from=came_from, __logins=login_counter))... | As a python code expert, you are capable of creating scripts from specifications. |
def infer(examples, alt_rules=None):
"""
Returns a datetime.strptime-compliant format string for parsing the *most likely* date format
used in examples. examples is a list containing example date strings.
"""
date_classes = _tag_most_likely(examples)
if alt_rules:
date_classes = _apply_... | Write a Python 3 function that can
infer the most likely date format from the examples. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _apply_rewrites(date_classes, rules):
"""
Return a list of date elements by applying rewrites to the initial date element list
"""
for rule in rules:
date_classes = rule.execute(date_classes)
return date_classes | Create a Python 3 function for
applying rewrites to the initial date element list. | As a python code expert, you are capable of creating scripts from specifications. |
def _mode(elems):
"""
Find the mode (most common element) in list elems. If there are ties, this function returns the least value.
If elems is an empty list, returns None.
"""
if len(elems) == 0:
return None
c = collections.Counter()
c.update(elems)
most_common = c.most_common... | Can you create a Python 3 function that
finds the mode of the given list of elements. | As a python code expert, you are capable of creating scripts from specifications. |
Return the date_elem that has the most restrictive range from date_elems
| How would you explain what the following Python 3 function does
def _most_restrictive(date_elems):
most_index = len(DATE_ELEMENTS)
for date_elem in date_elems:
if date_elem in DATE_ELEMENTS and DATE_ELEMENTS.index(date_elem) < most_index:
most_index = DATE_ELEMENTS.index(date_elem)
if mo... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _percent_match(date_classes, tokens):
"""
For each date class, return the percentage of tokens that the class matched (floating point [0.0 - 1.0]). The
returned value is a tuple of length patterns. Tokens should be a list.
"""
match_count = [0] * len(date_classes)
for i, date_class in enume... | Implement a Python 3 function for
returning the percentage of tokens that the class matched. | As a Python code composer, you craft elegant and concise scripts. |
Return a list of date elements by choosing the most likely element for a token within examples. | Given the following Python 3 function, write the documentation
def _tag_most_likely(examples):
tokenized_examples = [_tokenize_by_character_class(example) for example in examples]
# We currently need the tokenized_examples to all have the same length, so drop instances that have a length
# that does not eq... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _tokenize_by_character_class(s):
"""
Return a list of strings by splitting s (tokenizing) by character class.
For example:
_tokenize_by_character_class('Sat Jan 11 19:54:52 MST 2014') => ['Sat', ' ', 'Jan', ' ', '11', ' ', '19', ':',
'54', ':', '52', ' ', 'MST', ' ', '2014']
_tokenize_b... | Create a Python 3 function for
returning a list of strings by splitting s by character class. | You are a Python code architect, reviewing and designing scalable and efficient code |
def execute(self, elem_list):
"""
If condition, return a new elem_list provided by executing action.
"""
if self.condition.is_true(elem_list):
return self.action.act(elem_list)
else:
return elem_list | Write a Python 3 function that can
execute the condition and return a new list of elements. | As a python code expert, you are capable of creating scripts from specifications. |
def match(elem, seq_expr):
"""
Return True if elem (an element of elem_list) matches seq_expr, an element in self.sequence
"""
if type(seq_expr) is str: # wild-card
if seq_expr == '.': # match any element
return True
elif seq_expr == '\d':
... | Implement a Python 3 function for
returning True if elem matches seq_expr | As a Python code analyst, you investigate and solve complex coding mysteries |
Find the first element in elem_list where find_seq starts | Make a summary of the following Python 3 code
def find(find_seq, elem_list):
seq_pos = 0
for index, elem in enumerate(elem_list):
if Sequence.match(elem, find_seq[seq_pos]):
seq_pos += 1
if seq_pos == len(find_seq): # found matching sequence
... | You are a Python code generator, capable of creating scripts from specifications. |
def get_point(grade_str):
"""
根据成绩判断绩点
:param grade_str: 一个字符串,因为可能是百分制成绩或等级制成绩
:return: 成绩绩点
:rtype: float
"""
try:
grade = float(grade_str)
assert 0 <= grade <= 100
if 95 <= grade <= 100:
return 4.3
elif 90 <= grade < 95:
return 4.0
... | Can you implement a function in Python 3 that
returns the point in the nation of the current state of the current node. | You are a Python code generator, capable of creating scripts from specifications. |
cal_gpa - 参考 return ave_point gpa | Given the following Python 3 function, write the documentation
def cal_gpa(grades):
# 课程总数
courses_sum = len(grades)
# 课程绩点和
points_sum = 0
# 学分和
credit_sum = 0
# 课程学分 x 课程绩点之和
gpa_points_sum = 0
for grade in grades:
point = get_point(grade.get('补考成绩') or grade['成绩'])
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def term_str2code(term_str):
"""
将学期字符串转换为对应的学期代码串
:param term_str: 形如 "2012-2013学年第二学期" 的学期字符串
:return: 形如 "022" 的学期代码
"""
result = ENV['TERM_PATTERN'].match(term_str).groups()
year = int(result[0])
return cal_term_code(year, result[1] == '一') | Implement a function in Python 3 to
convert a term_str to a term_code | As a Python code analyst, you investigate and solve complex coding mysteries |
def sort_hosts(hosts, method='GET', path='/', timeout=(5, 10), **kwargs):
"""
测试各个地址的速度并返回排名, 当出现错误时消耗时间为 INFINITY = 10000000
:param method: 请求方法
:param path: 默认的访问路径
:param hosts: 进行的主机地址列表, 如 `['http://222.195.8.201/']`
:param timeout: 超时时间, 可以是一个浮点数或 形如 ``(连接超时, 读取超时)`` 的元祖
:param kwargs... | Write a Python 3 function that can
sort hosts by url | As a Python code translator, you convert algorithms and pseudocode into Python. |
def filter_curriculum(curriculum, week, weekday=None):
"""
筛选出指定星期[和指定星期几]的课程
:param curriculum: 课程表数据
:param week: 需要筛选的周数, 是一个代表周数的正整数
:param weekday: 星期几, 是一个代表星期的整数, 1-7 对应周一到周日
:return: 如果 weekday 参数没给出, 返回的格式与原课表一致, 但只包括了在指定周数的课程, 否则返回指定周数和星期几的当天课程
"""
if weekday:
c = [dee... | How would you code a function in Python 3 to
filter the curriculum by week. | You are a Python code generator, capable of creating scripts from specifications. |
Convert a schedule to an icalendar. Calendar object. | Here you have a function in Python 3, explain what it does
def schedule2calendar(schedule, name='课表', using_todo=True):
# https://zh.wikipedia.org/wiki/ICalendar
# http://icalendar.readthedocs.io/en/latest
# https://tools.ietf.org/html/rfc5545
cal = icalendar.Calendar()
cal.add('X-WR-TIMEZONE', 'Asi... | You are a Python code architect, reviewing and designing scalable and efficient code |
Init a new game. | Can you generate a brief explanation for the following Python 3 code
def init_new_game(self, with_tcp=True):
self.board = self.create_board(self.board_width, self.board_height,
self.num_mines)
self.game_status = 2
self.num_moves = 0
self.move_histor... | As a python code expert, you are capable of creating scripts from specifications. |
def check_move(self, move_type, move_x, move_y):
"""Check if a move is valid.
If the move is not valid, then shut the game.
If the move is valid, then setup a dictionary for the game,
and update move counter.
TODO: maybe instead of shut the game, can end the game or turn it int... | Implement a function in Python 3 to
check if a move is valid and return a dictionary of move parameters. | As a python code expert, you are capable of creating scripts from specifications. |
Updat board by a given move.
Parameters
----------
move_type : string
one of four move types:
"click", "flag", "unflag", "question"
move_x : int
X position of the move
move_y : int
Y position of the move | Make a summary of the following Python 3 code
def play_move(self, move_type, move_x, move_y):
# record the move
if self.game_status == 2:
self.move_history.append(self.check_move(move_type, move_x,
move_y))
else:
self.e... | You are a Python code architect, reviewing and designing scalable and efficient code |
Parse a move from a string. | Explain what the following Python 3 code does
def parse_move(self, move_msg):
# TODO: some condition check
type_idx = move_msg.index(":")
move_type = move_msg[:type_idx]
pos_idx = move_msg.index(",")
move_x = int(move_msg[type_idx+1:pos_idx])
move_y = int(move_msg[pos_idx... | As a python code expert, you are capable of creating scripts from specifications. |
Waiting for a TCP connection. | Can you tell what is the following Python 3 function doing
def tcp_accept(self):
self.conn, self.addr = self.tcp_socket.accept()
print("[MESSAGE] The connection is established at: ", self.addr)
self.tcp_send("> ") | You are a Python code generator, capable of creating scripts from specifications. |
Receive data from TCP port. | Here you have a function in Python 3, explain what it does
def tcp_receive(self):
data = self.conn.recv(self.BUFFER_SIZE)
if type(data) != str:
# Python 3 specific
data = data.decode("utf-8")
return str(data) | You are a Python code analyst, evaluating scripts for potential improvements. |
parse_tr_strs - 将没有必须要的单元格的值但有必须要的单元格的值设置为 None | How would you explain what the following Python 3 function does
def parse_tr_strs(trs):
tr_strs = []
for tr in trs:
strs = []
for td in tr.find_all('td'):
text = td.get_text(strip=True)
strs.append(text or None)
tr_strs.append(strs)
logger.debug('从行中解析出以下数据\n%... | As a python code expert, you are capable of creating scripts from specifications. |
flatten_list - flattens a list of n - tuple | Make a summary of the following Python 3 code
def flatten_list(multiply_list):
if isinstance(multiply_list, list):
return [rv for l in multiply_list for rv in flatten_list(l)]
else:
return [multiply_list] | You are a Python code architect, reviewing and designing scalable and efficient code |
def dict_list_2_matrix(dict_list, columns):
"""
>>> dict_list_2_matrix([{'a': 1, 'b': 2}, {'a': 3, 'b': 4}], ('a', 'b'))
[[1, 2], [3, 4]]
:param dict_list: 字典列表
:param columns: 字典的键
"""
k = len(columns)
n = len(dict_list)
result = [[None] * k for i in range(n)]
for i in... | Write a Python 3 script for
converting a dictionary list to a matrix | As a Python code analyst, you investigate and solve complex coding mysteries |
Parse a course string into a list of dicts. | Can you tell what is the following Python 3 function doing
def parse_course(course_str):
# 解析课程单元格
# 所有情况
# 机械原理[一教416 (1-14周)]/
# 程序与算法综合设计[不占用教室 (18周)]/
# 财务管理[一教323 (11-17单周)]/
# 财务管理[一教323 (10-16双周)]/
# 形势与政策(4)[一教220 (2,4,6-7周)]/
p = re.compile(r'(.+?)\[(.+?)\s+\(([\d,-单双]+?)周\)\]/'... | As a python code expert, you are capable of creating scripts from specifications. |
教学班查询, 查询指定教学班的所有学生
@structure {'学期': str, '班级名称': str, '学生': [{'姓名': str, '学号': int}]}
:param xqdm: 学期代码
:param kcdm: 课程代码
:param jxbh: 教学班号 | Can you generate the documentation for the following Python 3 function
def get_class_students(self, xqdm, kcdm, jxbh):
return self.query(GetClassStudents(xqdm, kcdm, jxbh)) | As a Python code translator, you convert algorithms and pseudocode into Python. |
获取教学班详情, 包括上课时间地点, 考查方式, 老师, 选中人数, 课程容量等等信息
@structure {'校区': str,'开课单位': str,'考核类型': str,'课程类型': str,'课程名称': str,'教学班号': str,'起止周': str,
'时间地点': str,'学分': float,'性别限制': str,'优选范围': str,'禁选范围': str,'选中人数': int,'备注': str}
:param xqdm: 学期代码
:param kcdm: 课程代码
:param jxbh: 教学班号 | Here you have a function in Python 3, explain what it does
def get_class_info(self, xqdm, kcdm, jxbh):
return self.query(GetClassInfo(xqdm, kcdm, jxbh)) | As a Python code analyst, you investigate and solve complex coding mysteries |
def search_course(self, xqdm, kcdm=None, kcmc=None):
"""
课程查询
@structure [{'任课教师': str, '课程名称': str, '教学班号': str, '课程代码': str, '班级容量': int}]
:param xqdm: 学期代码
:param kcdm: 课程代码
:param kcmc: 课程名称
"""
return self.query(SearchCourse(xqdm, kcdm, kcmc)) | Implement a function in Python 3 to
search course by name. | You are a Python code generator, capable of creating scripts from specifications. |
专业教学计划查询, 可以查询全校公选课, 此时可以不填 `zydm`
@structure [{'开课单位': str, '学时': int, '课程名称': str, '课程代码': str, '学分': float}]
:param xqdm: 学期代码
:param kclx: 课程类型参数,只有两个值 b:专业必修课, x:全校公选课
:param zydm: 专业代码, 可以从 :meth:`models.StudentSession.get_code` 获得 | How would you explain what the following Python 3 function does
def get_teaching_plan(self, xqdm, kclx='b', zydm=''):
return self.query(GetTeachingPlan(xqdm, kclx, zydm)) | You are a Python code analyst, evaluating scripts for potential improvements. |
def change_password(self, new_password):
"""
修改教务密码, **注意** 合肥校区使用信息中心账号登录, 与教务密码不一致, 即使修改了也没有作用, 因此合肥校区帐号调用此接口会直接报错
@structure bool
:param new_password: 新密码
"""
if self.session.campus == HF:
raise ValueError('合肥校区使用信息中心账号登录, 修改教务密码没有作用')
# 若新密码与原密码... | Write a Python 3 function that can
change the password of the user. | As a Python code translator, you convert algorithms and pseudocode into Python. |
课程评价, 数值为 1-5, r1 类选项 1 为最好, 5 为最差, r2 类选项程度由深到浅, 3 为最好.
默认都是最好的选项
:param kcdm: 课程代码
:param jxbh: 教学班号
:param r101: 教学态度认真,课前准备充分
:param r102: 教授内容充实,要点重点突出
:param r103: 理论联系实际,反映最新成果
:param r104: 教学方法灵活,师生互动得当
:param r105: 运用现代技术,教学手段多样
:param r... | Can you tell what is the following Python 3 function doing
def evaluate_course(self, kcdm, jxbh,
r101=1, r102=1, r103=1, r104=1, r105=1, r106=1, r107=1, r108=1, r109=1,
r201=3, r202=3, advice=''):
"""
课程评价, 数值为 1-5, r1 类选项 1 为最好, 5 为最差, r2 类选项程度由深到浅, 3 为最好... | You are a Python code analyst, evaluating scripts for potential improvements. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.