text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gdal_nodata_mask(pcl, pcsl, tirs_arr): """ Given a boolean potential cloud layer, a potential cloud shadow layer and a thermal band Calculate the GDAL-style ...
tirs_mask = np.isnan(tirs_arr) | (tirs_arr == 0) return ((~(pcl | pcsl | tirs_mask)) * 255).astype('uint8')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _transstat(status, grouppath, dictpath, line): """Executes processing steps when reading a line"""
if status == 0: raise MTLParseError( "Status should not be '%s' after reading line:\n%s" % (STATUSCODE[status], line)) elif status == 1: currentdict = dictpath[-1] currentgroup = _getgroupname(line) grouppath.append(currentgroup) currentdict[curre...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _postprocess(valuestr): """ Takes value as str, returns str, int, float, date, datetime, or time """
# USGS has started quoting time sometimes. Grr, strip quotes in this case intpattern = re.compile(r'^\-?\d+$') floatpattern = re.compile(r'^\-?\d+\.\d+(E[+-]?\d\d+)?$') datedtpattern = '%Y-%m-%d' datedttimepattern = '%Y-%m-%dT%H:%M:%SZ' timedtpattern = '%H:%M:%S.%f' timepattern = re.compil...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tox_get_python_executable(envconfig): """Return a python executable for the given python base name. The first plugin/hook which returns an executable path wi...
try: # pylint: disable=no-member pyenv = (getattr(py.path.local.sysfind('pyenv'), 'strpath', 'pyenv') or 'pyenv') cmd = [pyenv, 'which', envconfig.basepython] pipe = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def quote(myitem, elt=True): '''URL encode string''' if elt and '<' in myitem and len(myitem) > 24 and myitem.find(']]>') == -1: return '<![CDATA[%s]]>' % (myitem) else: myitem = myitem.replace('&', '&amp;').\ replace('<', '&lt;').replace(']]>', ']]&gt;') if not elt: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _doPrep(field_dict): """ _doPrep is makes changes in-place. Do some prep work converting python types into formats that Salesforce will accept. This includes...
fieldsToNull = [] for key, value in field_dict.items(): if value is None: fieldsToNull.append(key) field_dict[key] = [] if hasattr(value, '__iter__'): if len(value) == 0: fieldsToNull.append(key) elif isinstance(value, dict): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _prepareSObjects(sObjects): '''Prepare a SObject''' sObjectsCopy = copy.deepcopy(sObjects) if isinstance(sObjectsCopy, dict): # If root element is a dict, then this is a single object not an array _doPrep(sObjectsCopy) else: # else this is an array, and each elelment should b...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def queryTypesDescriptions(self, types): """ Given a list of types, construct a dictionary such that each key is a type, and each value is the corresponding sObj...
types = list(types) if types: types_descs = self.describeSObjects(types) else: types_descs = [] return dict(map(lambda t, d: (t, d), types, types_descs))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_token(self): """Create a session protection token for this client. This method generates a session protection token for the cilent, which consists in ...
user_agent = request.headers.get('User-Agent') if user_agent is None: # pragma: no cover user_agent = 'no user agent' user_agent = user_agent.encode('utf-8') base = self._get_remote_addr() + b'|' + user_agent h = sha256() h.update(base) return h.hexd...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear_session(self, response): """Clear the session. This method is invoked when the session is found to be invalid. Subclasses can override this method to i...
session.clear() # if flask-login is installed, we try to clear the # "remember me" cookie, just in case it is set if 'flask_login' in sys.modules: remember_cookie = current_app.config.get('REMEMBER_COOKIE', 'remember_toke...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def haikunate(self, delimiter='-', token_length=4, token_hex=False, token_chars='0123456789'): """ Generate heroku-like random names to use in your python applic...
if token_hex: token_chars = '0123456789abcdef' adjective = self._random_element(self._adjectives) noun = self._random_element(self._nouns) token = ''.join(self._random_element(token_chars) for _ in range(token_length)) sections = [adjective, noun, token] re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_parser_class(): """ Returns the parser according to the system platform """
global distro if distro == 'Linux': Parser = parser.LinuxParser if not os.path.exists(Parser.get_command()[0]): Parser = parser.UnixIPParser elif distro in ['Darwin', 'MacOSX']: Parser = parser.MacOSXParser elif distro == 'Windows': # For some strange reason,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def default_interface(ifconfig=None, route_output=None): """ Return just the default interface device dictionary. :param ifconfig: For mocking actual command out...
global Parser return Parser(ifconfig=ifconfig)._default_interface(route_output=route_output)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse(self, ifconfig=None): # noqa: max-complexity=12 """ Parse ifconfig output into self._interfaces. Optional Arguments: ifconfig The data (stdout) from th...
if not ifconfig: ifconfig, __, __ = exec_cmd(self.get_command()) self.ifconfig_data = ifconfig cur = None patterns = self.get_patterns() for line in self.ifconfig_data.splitlines(): for pattern in patterns: m = re.match(pattern, line) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, line_number): """Return the needle positions or None. :param int line_number: the number of the line :rtype: list :return: the needle positions for...
if line_number not in self._get_cache: self._get_cache[line_number] = self._get(line_number) return self._get_cache[line_number]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_bytes(self, line_number): """Get the bytes representing needle positions or None. :param int line_number: the line number to take the bytes from :rtype: ...
if line_number not in self._needle_position_bytes_cache: line = self._get(line_number) if line is None: line_bytes = None else: line_bytes = self._machine.needle_positions_to_bytes(line) self._needle_position_bytes_cache[line_numbe...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_line_configuration_message(self, line_number): """Return the cnfLine content without id for the line. :param int line_number: the number of the line :rty...
if line_number not in self._line_configuration_message_cache: line_bytes = self.get_bytes(line_number) if line_bytes is not None: line_bytes = bytes([line_number & 255]) + line_bytes line_bytes += bytes([self.is_last(line_number)]) line_by...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_message_type(file): """Read the message type from a file."""
message_byte = file.read(1) if message_byte == b'': return ConnectionClosed message_number = message_byte[0] return _message_types.get(message_number, UnknownMessage)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _init(self): """Read the line number."""
self._line_number = next_line( self._communication.last_requested_line_number, self._file.read(1)[0])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send(self): """Send this message to the controller."""
self._file.write(self.as_bytes()) self._file.write(b'\r\n')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init(self, left_end_needle, right_end_needle): """Initialize the StartRequest with start and stop needle. :raises TypeError: if the arguments are not integer...
if not isinstance(left_end_needle, int): raise TypeError(_left_end_needle_error_message(left_end_needle)) if left_end_needle < 0 or left_end_needle > 198: raise ValueError(_left_end_needle_error_message(left_end_needle)) if not isinstance(right_end_needle, int): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sum_all(iterable, start): """Sum up an iterable starting with a start value. In contrast to :func:`sum`, this also works on other types like :class:`lists <l...
if hasattr(start, "__add__"): for value in iterable: start += value else: for value in iterable: start |= value return start
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def next_line(last_line, next_line_8bit): """Compute the next line based on the last line and a 8bit next line. The behaviour of the function is specified in :re...
# 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 = line + 256 # compute the next line if last_line - lower_line <= line - last_line: retur...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ``"A...
result = [] for letter in camel_case_name: if letter.lower() != letter: result.append("_" + letter.lower()) else: result.append(letter.lower()) if result[0].startswith("_"): result[0] = result[0][1:] return "".join(result)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _message_received(self, message): """Notify the observers about the received message."""
with self.lock: self._state.receive_message(message) for callable in chain(self._on_message_received, self._on_message): callable(message)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def can_receive_messages(self): """Whether tihs communication is ready to receive messages.] :rtype: bool .. code:: python assert not communication.can_receive_m...
with self.lock: return not self._state.is_waiting_for_start() and \ not self._state.is_connection_closed()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stop(self): """Stop the communication with the shield."""
with self.lock: self._message_received(ConnectionClosed(self._file, self))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send(self, host_message_class, *args): """Send a host message. :param type host_message_class: a subclass of :class:`AYABImterface.communication.host_message...
message = host_message_class(self._file, self, *args) with self.lock: message.send() for callable in self._on_message: callable(message)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parallelize(self, seconds_to_wait=2): """Start a parallel thread for receiving messages. If :meth:`start` was no called before, start will be called in the t...
with self.lock: thread = Thread(target=self._parallel_receive_loop, args=(seconds_to_wait,)) thread.deamon = True thread.start() self._thread = thread
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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(): self.start() while True: with self.lock: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 communic...
self._communication.state = state_class(self._communication, *args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def receive_information_confirmation(self, message): """A InformationConfirmation is received. If :meth:`the api version is supported <AYABInterface.communicatio...
if message.api_version_is_supported(): self._next(InitializingMachine) else: self._next(UnsupportedApiVersion) self._communication.controller = message
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def receive_start_confirmation(self, message): """Receive a StartConfirmation message. :param message: a :class:`StartConfirmation <AYABInterface.communication.h...
if message.is_success(): self._next(KnittingStarted) else: self._next(StartingFailed)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enter(self): """Send a StartRequest."""
self._communication.send(StartRequest, self._communication.left_end_needle, self._communication.right_end_needle)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enter(self): """Send a LineConfirmation to the controller. When this state is entered, a :class:`AYABInterface.communication.host_messages.LineConfirmation` ...
self._communication.last_requested_line_number = self._line_number self._communication.send(LineConfirmation, self._line_number)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: color1, color2 = colors if color1 != row[0]: color1, color2 = color2, color1 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
# TODO: This violates the law of demeter. # The architecture should be changed that this check is either # performed by the machine or by the unity of machine and # carriage. expected_positions = self._machine.needle_positions expected_row_length = self...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def row_completed(self, index): """Mark the row at index as completed. .. seealso:: :meth:`completed_row_indices` This method notifies the obsevrers from :meth:`...
self._completed_rows.append(index) for row_completed in self._on_row_completed: row_completed(index)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def communicate_through(self, file): """Setup communication through a file. :rtype: AYABInterface.communication.Communication """
if self._communication is not None: raise ValueError("Already communicating.") self._communication = communication = Communication( file, self._get_needle_positions, self._machine, [self._on_message_received], right_end_needle=self.right_end_needle, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def actions(self): """A list of actions to perform. :return: a list of :class:`AYABInterface.actions.Action` """
actions = [] do = actions.append # determine the number of colors colors = self.colors # rows and colors movements = ( MoveCarriageToTheRight(KnitCarriage()), MoveCarriageToTheLeft(KnitCarriage())) rows = self._rows first_needles...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def needle_positions_to_bytes(self, needle_positions): """Convert the needle positions to the wire format. This conversion is used for :ref:`cnfline`. :param nee...
bit = self.needle_positions assert len(bit) == 2 max_length = len(needle_positions) assert max_length == self.number_of_needles result = [] for byte_index in range(0, max_length, 8): byte = 0 for bit_index in range(8): index = byte...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def name(self): """The identifier of the machine."""
name = self.__class__.__name__ for i, character in enumerate(name): if character.isdigit(): return name[:i] + "-" + name[i:] return name
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _id(self): """What this object is equal to."""
return (self.__class__, self.number_of_needles, self.needle_positions, self.left_end_needle)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
try: assert type(c) == chapter.Chapter except AssertionError: raise TypeError('chapter must be of type Chapter') chapter_file_output = os.path.join(self.OEBPS_DIR, self.current_chapter_path) c._replace_images_in_chapter(self.OEBPS_DIR) c.write(chapter_fil...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_epub(self, output_directory, epub_name=None): """ Create an epub file from this object. Args: output_directory (str): Directory to output the epub fi...
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_chapters(self.chapters) epub_file.write(os.path.join(self.OEBPS_DIR, name)) def create_zip_archive(epu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_image(image_url, image_directory, image_name): """ Saves an online image from image_url to image_directory with the name image_name. Returns the extensi...
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 image is present on the local filesystem just copy it if os.path.exists(image_url): shutil...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 e...
try: assert isinstance(image_tag, bs4.element.Tag) except AssertionError: raise TypeError("image_tag cannot be of type " + str(type(image_tag))) if image_name is None: image_name = str(uuid.uuid4()) try: image_full_path = os.path.join(ebook_folder, 'images') asse...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(self, file_name): """ Writes the chapter object to an xhtml file. Args: file_name (str): The full name of the xhtml file to save to. """
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(self.content.encode('utf-8'))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_f...
try: request_object = requests.get(url, headers=self.request_headers, allow_redirects=False) except (requests.exceptions.MissingSchema, requests.exceptions.ConnectionError): raise ValueError("%s is an invalid url or no network connection" % url) except re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_chapter_from_file(self, file_name, url=None, title=None): """ Creates a Chapter object from an html or xhtml file. Sanitizes the file's content using ...
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_functio...
clean_html_string = self.clean_function(html_string) clean_xhtml_string = clean.html_to_xhtml(clean_html_string) if title: pass else: try: root = BeautifulSoup(html_string, 'html.parser') title_node = root.title if ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 bs...
try: assert isinstance(tag, bs4.element.Tag) except AssertionError: raise TypeError try: assert tag.find_all('body') == [] except AssertionError: raise ValueError soup = BeautifulSoup('<html><head></head><body></body></html>', 'html.parser') soup.body.append(ta...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def condense(input_string): """ Trims leadings and trailing whitespace between tags in an html document Args: input_string: A (possible unicode) string represent...
try: assert isinstance(input_string, basestring) except AssertionError: raise TypeError removed_leading_whitespace = re.sub('>\s+', '>', input_string).strip() removed_trailing_whitespace = re.sub('\s+<', '<', removed_leading_whitespace).strip() return removed_trailing_whitespace
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def html_to_xhtml(html_unicode_string): """ Converts html to xhtml Args: html_unicode_string: A (possible unicode) string representing HTML. Returns: A (possibly...
try: assert isinstance(html_unicode_string, basestring) except AssertionError: raise TypeError root = BeautifulSoup(html_unicode_string, 'html.parser') # Confirm root node is html try: assert root.html is not None except AssertionError: raise ValueError(''.join([...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def t_multiline_NEWLINE(self, t): r'\r\n|\n|\r' if t.lexer.multiline_newline_seen: return self.t_multiline_OPTION_AND_VALUE(t) t.lexer.multiline_newline_seen = True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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._depots.get(name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def configure(cls, name, config, prefix='depot.'): """Configures an application depot. This configures the application wide depot from a settings dictionary. The...
if name in cls._depots: raise RuntimeError('Depot %s has already been configured' % (name,)) if cls._default_depot is None: cls._default_depot = name cls._depots[name] = cls.from_config(config, prefix) return cls._depots[name]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_middleware(cls, app, **options): """Creates the application WSGI middleware in charge of serving local files. A Depot middleware is required if your app...
from depot.middleware import DepotMiddleware mw = DepotMiddleware(app, **options) cls.set_middleware(mw) return mw
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_config(cls, config, prefix='depot.'): """Creates a new depot from a settings dictionary. Behaves like the :meth:`configure` method but instead of config...
config = config or {} # Get preferred storage backend backend = config.get(prefix + 'backend', 'depot.io.local.LocalFileStorage') # Get all options prefixlen = len(prefix) options = dict((k[prefixlen:], config[k]) for k in config.keys() if k.startswith(prefix)) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _clear(cls): """This is only for testing pourposes, resets the DepotManager status This is to simplify writing test fixtures, resets the DepotManager global ...
cls._default_depot = None cls._depots = {} cls._middleware = None cls._aliases = {}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def by_email_address(cls, email): """Return the user object whose email address is ``email``."""
return DBSession.query(cls).filter_by(email_address=email).first()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def by_user_name(cls, username): """Return the user object whose user name is ``username``."""
return DBSession.query(cls).filter_by(user_name=username).first()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_password(self, password): """ Check the password against existing credentials. :param password: the password that was provided by the user to try an...
hash = sha256() hash.update((password + self.password[:64]).encode('utf-8')) return self.password[64:] == hash.hexdigest()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def file_from_content(content): """Provides a real file object from file content Converts ``FileStorage``, ``FileIntent`` and ``bytes`` to an actual file. """
f = content if isinstance(content, cgi.FieldStorage): f = content.file elif isinstance(content, FileIntent): f = content._fileobj elif isinstance(content, byte_string): f = SpooledTemporaryFile(INMEMORY_FILESIZE) f.write(content) f.seek(0) return f
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fileinfo(fileobj, filename=None, content_type=None, existing=None): """Tries to extract from the given input the actual file object, filename and content_typ...
return _FileInfo(fileobj, filename, content_type).get_info(existing)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_from=came_from)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def post_login(self, came_from=lurl('/')): """ Redirect the user to the initially requested page on successful authentication or redirect her back to the login p...
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)) userid = request.identity['repoze.who.userid'] flash(_('Welcome back, %s!') % userid) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _most_restrictive(date_elems): """ Return the date_elem that has the most restrictive range from 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 most_index < len(DATE_ELEMENTS): return DATE_ELEMENTS[most_index] else: raise Ke...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find(find_seq, elem_list): """ Return the first position in elem_list where find_seq starts """
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 return index - seq_pos + 1 else: # exited sequence ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ms_game_main(board_width, board_height, num_mines, port, ip_add): """Main function for Mine Sweeper Game. Parameters board_width : int the width of the board...
ms_game = MSGame(board_width, board_height, num_mines, port=port, ip_add=ip_add) ms_app = QApplication([]) ms_window = QWidget() ms_window.setAutoFillBackground(True) ms_window.setWindowTitle("Mine Sweeper") ms_layout = QGridLayout() ms_window.setLayout(ms_layout) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_new_game(self, with_tcp=True): """Init a new game. Parameters board : MSBoard define a new board. game_status : int define the game status: 0: lose, 1: ...
self.board = self.create_board(self.board_width, self.board_height, self.num_mines) self.game_status = 2 self.num_moves = 0 self.move_history = [] if with_tcp is True: # init TCP communication. self.tcp_socket = soc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 di...
if move_type not in self.move_types: raise ValueError("This is not a valid move!") if move_x < 0 or move_x >= self.board_width: raise ValueError("This is not a valid X position of the move!") if move_y < 0 or move_y >= self.board_height: raise ValueError("Thi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def play_move(self, move_type, move_x, move_y): """Updat board by a given move. Parameters move_type : string one of four move types: "click", "flag", "unflag", ...
# record the move if self.game_status == 2: self.move_history.append(self.check_move(move_type, move_x, move_y)) else: self.end_game() # play the move, update the board if move_type == "click": ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_move(self, move_msg): """Parse a move from a string. Parameters move_msg : string a valid message should be in: "[move type]: [X], [Y]" Returns -------...
# 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+1:]) return move_type, move_x, move_y
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def play_move_msg(self, move_msg): """Another play move function for move message. Parameters move_msg : string a valid message should be in: "[move type]: [X], ...
move_type, move_x, move_y = self.parse_move(move_msg) self.play_move(move_type, move_x, move_y)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tcp_accept(self): """Waiting for a TCP connection."""
self.conn, self.addr = self.tcp_socket.accept() print("[MESSAGE] The connection is established at: ", self.addr) self.tcp_send("> ")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tcp_receive(self): """Receive data from TCP port."""
data = self.conn.recv(self.BUFFER_SIZE) if type(data) != str: # Python 3 specific data = data.decode("utf-8") return str(data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_board(self): """Init a valid board by given settings. Parameters mine_map : numpy.ndarray the map that defines the mine 0 is empty, 1 is mine info_map :...
self.mine_map = np.zeros((self.board_height, self.board_width), dtype=np.uint8) idx_list = np.random.permutation(self.board_width*self.board_height) idx_list = idx_list[:self.num_mines] for idx in idx_list: idx_x = int(idx % self.board_width...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def click_field(self, move_x, move_y): """Click one grid by given position."""
field_status = self.info_map[move_y, move_x] # can only click blank region if field_status == 11: if self.mine_map[move_y, move_x] == 1: self.info_map[move_y, move_x] = 12 else: # discover the region. self.discover_region(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def discover_region(self, move_x, move_y): """Discover region from given location."""
field_list = deque([(move_y, move_x)]) while len(field_list) != 0: field = field_list.popleft() (tl_idx, br_idx, region_sum) = self.get_region(field[1], field[0]) if region_sum == 0: self.info_map[field[0], field[1]] = region_sum # g...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_region(self, move_x, move_y): """Get region around a location."""
top_left = (max(move_y-1, 0), max(move_x-1, 0)) bottom_right = (min(move_y+1, self.board_height-1), min(move_x+1, self.board_width-1)) region_sum = self.mine_map[top_left[0]:bottom_right[0]+1, top_left[1]:bottom_right[1]+1].sum() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flag_field(self, move_x, move_y): """Flag a grid by given position."""
field_status = self.info_map[move_y, move_x] # a questioned or undiscovered field if field_status != 9 and (field_status == 10 or field_status == 11): self.info_map[move_y, move_x] = 9
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unflag_field(self, move_x, move_y): """Unflag or unquestion a grid by given position."""
field_status = self.info_map[move_y, move_x] if field_status == 9 or field_status == 10: self.info_map[move_y, move_x] = 11
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def question_field(self, move_x, move_y): """Question a grid by given position."""
field_status = self.info_map[move_y, move_x] # a questioned or undiscovered field if field_status != 10 and (field_status == 9 or field_status == 11): self.info_map[move_y, move_x] = 10
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_board(self): """Check the board status and give feedback."""
num_mines = np.sum(self.info_map == 12) num_undiscovered = np.sum(self.info_map == 11) num_questioned = np.sum(self.info_map == 10) if num_mines > 0: return 0 elif np.array_equal(self.info_map == 9, self.mine_map): return 1 elif num_undiscovered ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def board_msg(self): """Structure a board as in print_board."""
board_str = "s\t\t" for i in xrange(self.board_width): board_str += str(i)+"\t" board_str = board_str.expandtabs(4)+"\n\n" for i in xrange(self.board_height): temp_line = str(i)+"\t\t" for j in xrange(self.board_width): if self.info_m...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_ui(self): """Setup control widget UI."""
self.control_layout = QHBoxLayout() self.setLayout(self.control_layout) self.reset_button = QPushButton() self.reset_button.setFixedSize(40, 40) self.reset_button.setIcon(QtGui.QIcon(WIN_PATH)) self.game_timer = QLCDNumber() self.game_timer.setStyleSheet("QLCDNum...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_ui(self): """Init game interface."""
board_width = self.ms_game.board_width board_height = self.ms_game.board_height self.create_grid(board_width, board_height) self.time = 0 self.timer = QtCore.QTimer() self.timer.timeout.connect(self.timing_game) self.timer.start(1000)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_grid(self, grid_width, grid_height): """Create a grid layout with stacked widgets. Parameters grid_width : int the width of the grid grid_height : int...
self.grid_layout = QGridLayout() self.setLayout(self.grid_layout) self.grid_layout.setSpacing(1) self.grid_wgs = {} for i in xrange(grid_height): for j in xrange(grid_width): self.grid_wgs[(i, j)] = FieldWidget() self.grid_layout.addWi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def timing_game(self): """Timing game."""
self.ctrl_wg.game_timer.display(self.time) self.time += 1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset_game(self): """Reset game board."""
self.ms_game.reset_game() self.update_grid() self.time = 0 self.timer.start(1000)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_grid(self): """Update grid according to info map."""
info_map = self.ms_game.get_info_map() for i in xrange(self.ms_game.board_height): for j in xrange(self.ms_game.board_width): self.grid_wgs[(i, j)].info_label(info_map[i, j]) self.ctrl_wg.move_counter.display(self.ms_game.num_moves) if self.ms_game.game_stat...