sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
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_class(self._communication, *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
entailment
def receive_information_confirmation(self, message): """A InformationConfirmation is received. If :meth:`the api version is supported <AYABInterface.communication.Communication.api_version_is_supported>`, the communication object transitions into a :class:`InitializingMachine`, if unsupported, into a :class:`UnsupportedApiVersion` """ if message.api_version_is_supported(): self._next(InitializingMachine) else: self._next(UnsupportedApiVersion) self._communication.controller = message
A InformationConfirmation is received. If :meth:`the api version is supported <AYABInterface.communication.Communication.api_version_is_supported>`, the communication object transitions into a :class:`InitializingMachine`, if unsupported, into a :class:`UnsupportedApiVersion`
entailment
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 transitions into :class:`KnittingStarted` or else, into :class:`StartingFailed`. """ if message.is_success(): self._next(KnittingStarted) else: self._next(StartingFailed)
Receive a StartConfirmation message. :param message: a :class:`StartConfirmation <AYABInterface.communication.hardware_messages.StartConfirmation>` message If the message indicates success, the communication object transitions into :class:`KnittingStarted` or else, into :class:`StartingFailed`.
entailment
def enter(self): """Send a StartRequest.""" self._communication.send(StartRequest, self._communication.left_end_needle, self._communication.right_end_needle)
Send a StartRequest.
entailment
def enter(self): """Send a LineConfirmation to the controller. When this state is entered, a :class:`AYABInterface.communication.host_messages.LineConfirmation` is sent to the controller. Also, the :attr:`last line requested <AYABInterface.communication.Communication.last_requested_line_number>` is set. """ self._communication.last_requested_line_number = self._line_number self._communication.send(LineConfirmation, self._line_number)
Send a LineConfirmation to the controller. When this state is entered, a :class:`AYABInterface.communication.host_messages.LineConfirmation` is sent to the controller. Also, the :attr:`last line requested <AYABInterface.communication.Communication.last_requested_line_number>` is set.
entailment
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 needles_ = _row_color(row, color1) needles.append([NeedlePositions(needles_, (color1, color2), True)]) else: colors = [] for color in row: if color not in colors: colors.append(color) needles_ = [] for color in colors: needles_.append(NeedlePositions(_row_color(row, color), (color,), False)) needles.append(needles_) return needles
Convert rows to needle positions. :return: :rtype: list
entailment
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.machines.Machine.needle_positions>` """ # 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._machine.number_of_needles for row_index, row in enumerate(self._rows): if len(row) != expected_row_length: message = _ROW_LENGTH_ERROR_MESSAGE.format( row_index, len(row), expected_row_length) raise ValueError(message) for needle_index, needle_position in enumerate(row): if needle_position not in expected_positions: message = _NEEDLE_POSITION_ERROR_MESSAGE.format( row_index, needle_index, repr(needle_position), ", ".join(map(repr, expected_positions))) raise ValueError(message)
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.machines.Machine.needle_positions>`
entailment
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]
Return the row at the given index or the default value.
entailment
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: row_completed(index)
Mark the row at index as completed. .. seealso:: :meth:`completed_row_indices` This method notifies the obsevrers from :meth:`on_row_completed`.
entailment
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, left_end_needle=self.left_end_needle) return communication
Setup communication through a file. :rtype: AYABInterface.communication.Communication
entailment
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 = self._get_row_needles(0) # handle switches if len(colors) == 1: actions.extend([ SwitchOffMachine(), SwitchCarriageToModeNl()]) else: actions.extend([ SwitchCarriageToModeKc(), SwitchOnMachine()]) # move needles do(MoveNeedlesIntoPosition("B", first_needles)) do(MoveCarriageOverLeftHallSensor()) # use colors if len(colors) == 1: do(PutColorInNutA(colors[0])) if len(colors) == 2: do(PutColorInNutA(colors[0])) do(PutColorInNutB(colors[1])) # knit for index, row in enumerate(rows): do(movements[index & 1]) return actions
A list of actions to perform. :return: a list of :class:`AYABInterface.actions.Action`
entailment
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 """ 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_index + bit_index if index >= max_length: break needle_position = needle_positions[index] if bit.index(needle_position) == 1: byte |= 1 << bit_index result.append(byte) if byte_index >= max_length: break result.extend(b"\x00" * (25 - len(result))) return bytes(result)
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
entailment
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
The identifier of the machine.
entailment
def _id(self): """What this object is equal to.""" return (self.__class__, self.number_of_needles, self.needle_positions, self.left_end_needle)
What this object is equal to.
entailment
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(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_file_output) self._increase_current_chapter_number() self.chapters.append(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.
entailment
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 file to epub_name (Option[str]): The file name of your epub. This should not contain .epub at the end. If this argument is not provided, defaults to the title of the epub. """ 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(epub_name): try: assert isinstance(epub_name, basestring) or epub_name is None except AssertionError: raise TypeError('epub_name must be string or None') if epub_name is None: epub_name = self.title epub_name = ''.join([c for c in epub_name if c.isalpha() or c.isdigit() or c == ' ']).rstrip() epub_name_with_path = os.path.join(output_directory, epub_name) try: os.remove(os.path.join(epub_name_with_path, '.zip')) except OSError: pass shutil.make_archive(epub_name_with_path, 'zip', self.EPUB_DIR) return epub_name_with_path + '.zip' def turn_zip_into_epub(zip_archive): epub_full_name = zip_archive.strip('.zip') + '.epub' try: os.remove(epub_full_name) except OSError: pass os.rename(zip_archive, epub_full_name) return epub_full_name createTOCs_and_ContentOPF() epub_path = turn_zip_into_epub(create_zip_archive(epub_name)) return epub_path
Create an epub file from this object. Args: output_directory (str): Directory to output the epub file to epub_name (Option[str]): The file name of your epub. This should not contain .epub at the end. If this argument is not provided, defaults to the title of the epub.
entailment
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 extension of the image saved, which is determined dynamically. Args: image_url (str): The url of the image. image_directory (str): The directory to save the image in. image_name (str): The file name to save the image as. Raises: ImageErrorException: Raised if unable to save the image at image_url """ 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.copy(image_url, full_image_file_name) return image_type try: # urllib.urlretrieve(image_url, full_image_file_name) with open(full_image_file_name, 'wb') as f: user_agent = r'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0' request_headers = {'User-Agent': user_agent} requests_object = requests.get(image_url, headers=request_headers) try: content = requests_object.content # Check for empty response f.write(content) except AttributeError: raise ImageErrorException(image_url) except IOError: raise ImageErrorException(image_url) return image_type
Saves an online image from image_url to image_directory with the name image_name. Returns the extension of the image saved, which is determined dynamically. Args: image_url (str): The url of the image. image_directory (str): The directory to save the image in. image_name (str): The file name to save the image as. Raises: ImageErrorException: Raised if unable to save the image at image_url
entailment
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.element.Tag): The bs4 tag containing the image. ebook_folder (str): The directory where the ebook files are being saved. This must contain a subdirectory called "images". image_name (Option[str]): The short name to save the image as. Should not contain a directory or an extension. """ 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') assert os.path.exists(image_full_path) image_extension = save_image(image_url, image_full_path, image_name) image_tag['src'] = 'images' + '/' + image_name + '.' + image_extension except ImageErrorException: image_tag.decompose() except AssertionError: raise ValueError('%s doesn\'t exist or doesn\'t contain a subdirectory images' % ebook_folder) except TypeError: image_tag.decompose()
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.element.Tag): The bs4 tag containing the image. ebook_folder (str): The directory where the ebook files are being saved. This must contain a subdirectory called "images". image_name (Option[str]): The short name to save the image as. Should not contain a directory or an extension.
entailment
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'))
Writes the chapter object to an xhtml file. Args: file_name (str): The full name of the xhtml file to save to.
entailment
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. Args: url (string): The url to pull the content of the created Chapter from title (Option[string]): The title of the created Chapter. By default, this is None, in which case the title will try to be inferred from the webpage at the url. Returns: Chapter: A chapter object whose content is the webpage at the given url and whose title is that provided or inferred from the url Raises: ValueError: Raised if unable to connect to url supplied """ 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 requests.exceptions.SSLError: raise ValueError("Url %s doesn't have valid SSL certificate" % url) unicode_string = request_object.text return self.create_chapter_from_string(unicode_string, url, title)
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. Args: url (string): The url to pull the content of the created Chapter from title (Option[string]): The title of the created Chapter. By default, this is None, in which case the title will try to be inferred from the webpage at the url. Returns: Chapter: A chapter object whose content is the webpage at the given url and whose title is that provided or inferred from the url Raises: ValueError: Raised if unable to connect to url supplied
entailment
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 the clean_function method, and saves it as the content of the created chapter. Args: file_name (string): The file_name containing the html or xhtml content of the created Chapter url (Option[string]): A url to infer the title of the chapter from title (Option[string]): The title of the created Chapter. By default, this is None, in which case the title will try to be inferred from the webpage at the url. Returns: Chapter: A chapter object whose content is the given file and whose title is that provided or inferred from the url """ 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)
Creates a Chapter object from an html or xhtml file. Sanitizes the file's content using the clean_function method, and saves it as the content of the created chapter. Args: file_name (string): The file_name containing the html or xhtml content of the created Chapter url (Option[string]): A url to infer the title of the chapter from title (Option[string]): The title of the created Chapter. By default, this is None, in which case the title will try to be inferred from the webpage at the url. Returns: Chapter: A chapter object whose content is the given file and whose title is that provided or inferred from the url
entailment
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 xhtml content of the created Chapter url (Option[string]): A url to infer the title of the chapter from title (Option[string]): The title of the created Chapter. By default, this is None, in which case the title will try to be inferred from the webpage at the url. Returns: Chapter: A chapter object whose content is the given string and whose title is that provided or inferred from the url """ 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 title_node is not None: title = unicode(title_node.string) else: raise ValueError except (IndexError, ValueError): title = 'Ebook Chapter' return Chapter(clean_xhtml_string, title, url)
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 xhtml content of the created Chapter url (Option[string]): A url to infer the title of the chapter from title (Option[string]): The title of the created Chapter. By default, this is None, in which case the title will try to be inferred from the webpage at the url. Returns: Chapter: A chapter object whose content is the given string and whose title is that provided or inferred from the url
entailment
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 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(tag) return soup
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
entailment
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. Doctype is set to <!DOCTYPE html>. Args: input_string (basestring): A (possibly unicode) string representing HTML. tag_dictionary (Option[dict]): A dictionary with tags as keys and attributes as values. This operates as a whitelist--i.e. if a tag isn't contained, it will be removed. By default, this is set to use the supported tags and attributes for the Amazon Kindle, as found at https://kdp.amazon.com/help?topicId=A1JPUWCSD6F59O Returns: str: A (possibly unicode) string representing HTML. Raises: TypeError: Raised if input_string isn't a unicode string or string. """ try: assert isinstance(input_string, basestring) except AssertionError: raise TypeError root = BeautifulSoup(input_string, 'html.parser') article_tag = root.find_all('article') if article_tag: root = article_tag[0] stack = root.findAll(True, recursive=False) while stack: current_node = stack.pop() child_node_list = current_node.findAll(True, recursive=False) if current_node.name not in tag_dictionary.keys(): parent_node = current_node.parent current_node.extract() for n in child_node_list: parent_node.append(n) else: attribute_dict = current_node.attrs for attribute in attribute_dict.keys(): if attribute not in tag_dictionary[current_node.name]: attribute_dict.pop(attribute) stack.extend(child_node_list) #wrap partial tree if necessary if root.find_all('html') == []: root = create_html_from_fragment(root) # Remove img tags without src attribute image_node_list = root.find_all('img') for node in image_node_list: if not node.has_attr('src'): node.extract() unformatted_html_unicode_string = unicode(root.prettify(encoding='utf-8', formatter=EntitySubstitution.substitute_html), encoding='utf-8') # fix <br> tags since not handled well by default by bs4 unformatted_html_unicode_string = unformatted_html_unicode_string.replace('<br>', '<br/>') # remove &nbsp; and replace with space since not handled well by certain e-readers unformatted_html_unicode_string = unformatted_html_unicode_string.replace('&nbsp;', ' ') return unformatted_html_unicode_string
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. Doctype is set to <!DOCTYPE html>. Args: input_string (basestring): A (possibly unicode) string representing HTML. tag_dictionary (Option[dict]): A dictionary with tags as keys and attributes as values. This operates as a whitelist--i.e. if a tag isn't contained, it will be removed. By default, this is set to use the supported tags and attributes for the Amazon Kindle, as found at https://kdp.amazon.com/help?topicId=A1JPUWCSD6F59O Returns: str: A (possibly unicode) string representing HTML. Raises: TypeError: Raised if input_string isn't a unicode string or string.
entailment
def condense(input_string): """ Trims leadings and trailing whitespace between tags in an html document Args: input_string: A (possible unicode) string representing HTML. Returns: A (possibly unicode) string representing HTML. Raises: TypeError: Raised if input_string isn't a unicode string or string. """ 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
Trims leadings and trailing whitespace between tags in an html document Args: input_string: A (possible unicode) string representing HTML. Returns: A (possibly unicode) string representing HTML. Raises: TypeError: Raised if input_string isn't a unicode string or string.
entailment
def html_to_xhtml(html_unicode_string): """ Converts html to xhtml Args: html_unicode_string: A (possible unicode) string representing HTML. Returns: A (possibly unicode) string representing XHTML. Raises: TypeError: Raised if input_string isn't a unicode string or 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: assert root.html is not None except AssertionError: raise ValueError(''.join(['html_unicode_string cannot be a fragment.', 'string is the following: %s', unicode(root)])) # Add xmlns attribute to html node root.html['xmlns'] = 'http://www.w3.org/1999/xhtml' unicode_string = unicode(root.prettify(encoding='utf-8', formatter='html'), encoding='utf-8') # Close singleton tag_dictionary for tag in constants.SINGLETON_TAG_LIST: unicode_string = unicode_string.replace( '<' + tag + '/>', '<' + tag + ' />') return unicode_string
Converts html to xhtml Args: html_unicode_string: A (possible unicode) string representing HTML. Returns: A (possibly unicode) string representing XHTML. Raises: TypeError: Raised if input_string isn't a unicode string or string.
entailment
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 dict1[key] != dict2[key]: if self._options.get('allowmultioptions', True): if not isinstance(dict1[key], list): dict1[key] = [dict1[key]] if not isinstance(dict2[key], list): dict2[key] = [dict2[key]] dict1[key] = self._merge_lists(dict1[key], dict2[key]) else: if self._options.get('mergeduplicateoptions', False): dict1[key] = dict2[key] else: raise error.ApacheConfigError('Duplicate option "%s" prohibited' % '.'.join(path + [str(key)])) else: dict1[key] = dict2[key] return dict1
merges dict2 into dict1
entailment
def p_statement(self, p): """statement : OPTION_AND_VALUE """ p[0] = ['statement', p[1][0], p[1][1]] if self.options.get('lowercasenames'): p[0][1] = p[0][1].lower() if (not self.options.get('nostripvalues') and not hasattr(p[0][2], 'is_single_quoted') and not hasattr(p[0][2], 'is_double_quoted')): p[0][2] = p[0][2].rstrip()
statement : OPTION_AND_VALUE
entailment
def p_statements(self, p): """statements : statements statement | statement """ n = len(p) if n == 3: p[0] = p[1] + [p[2]] elif n == 2: p[0] = ['statements', p[1]]
statements : statements statement | statement
entailment
def p_contents(self, p): """contents : contents statements | contents comment | contents include | contents includeoptional | contents block | statements | comment | include | includeoptional | block """ n = len(p) if n == 3: p[0] = p[1] + [p[2]] else: p[0] = ['contents', p[1]]
contents : contents statements | contents comment | contents include | contents includeoptional | contents block | statements | comment | include | includeoptional | block
entailment
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: p[0] = ['block', p[1], [], p[1]] if self.options.get('lowercasenames'): for tag in (1, 3): p[0][tag] = p[0][tag].lower()
block : OPEN_TAG contents CLOSE_TAG | OPEN_TAG CLOSE_TAG | OPEN_CLOSE_TAG
entailment
def p_config(self, p): """config : config contents | contents """ n = len(p) if n == 3: p[0] = p[1] + [p[2]] elif n == 2: p[0] = ['config', p[1]]
config : config contents | contents
entailment
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')
r'\/\*
entailment
def t_ccomment_close(self, t): r'\*\/' t.lexer.ccomment_level -= 1 if t.lexer.ccomment_level == 0: t.value = t.lexer.lexdata[t.lexer.code_start:t.lexer.lexpos + 1 - 3] t.type = "CCOMMENT" t.lexer.lineno += t.value.count('\n') t.lexer.begin('INITIAL') return t
r'\*\/
entailment
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.value) t.lexer.begin('multiline') return lineno = len(re.findall(r'\r\n|\n|\r', t.value)) option, value = self._parse_option_value(t.value) process, option, value = self._pre_parse_value(option, value) if not process: return if value.startswith('<<'): t.lexer.heredoc_anchor = value[2:].strip() t.lexer.heredoc_option = option t.lexer.code_start = t.lexer.lexpos t.lexer.begin('heredoc') return t.value = option, value t.lexer.lineno += lineno return t
r'[^ \n\r\t=#]+[ \t=]+[^\r\n#]+
entailment
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.lexer.lexdata[t.lexer.code_start:t.lexer.lexpos + 1] t.lexer.lineno += len(re.findall(r'\r\n|\n|\r', value)) value = value.replace('\\\n', '').replace('\r', '').replace('\n', '') option, value = self._parse_option_value(value) process, option, value = self._pre_parse_value(option, value) if not process: return t.value = option, value return t
r'[^\r\n]+
entailment
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
r'\r\n|\n|\r
entailment
def t_heredoc_OPTION_AND_VALUE(self, t): r'[^\r\n]+' if t.value.lstrip() != t.lexer.heredoc_anchor: return t.type = "OPTION_AND_VALUE" t.lexer.begin('INITIAL') value = t.lexer.lexdata[t.lexer.code_start + 1:t.lexer.lexpos - len(t.lexer.heredoc_anchor)] t.lexer.lineno += len(re.findall(r'\r\n|\n|\r', t.value)) t.value = t.lexer.heredoc_option, value return t
r'[^\r\n]+
entailment
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
Replaces the current application default depot
entailment
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)
Gets the application wide depot instance. Might return ``None`` if :meth:`configure` has not been called yet.
entailment
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)
Retrieves a file by storage name and fileid in the form of a path Path is expected to be ``storage_name/fileid``.
entailment
def configure(cls, name, config, prefix='depot.'): """Configures an application depot. This configures the application wide depot from a settings dictionary. The settings dictionary is usually loaded from an application configuration file where all the depot options are specified with a given ``prefix``. The default ``prefix`` is *depot.*, the minimum required setting is ``depot.backend`` which specified the required backend for files storage. Additional options depend on the choosen backend. """ 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]
Configures an application depot. This configures the application wide depot from a settings dictionary. The settings dictionary is usually loaded from an application configuration file where all the depot options are specified with a given ``prefix``. The default ``prefix`` is *depot.*, the minimum required setting is ``depot.backend`` which specified the required backend for files storage. Additional options depend on the choosen backend.
entailment
def make_middleware(cls, app, **options): """Creates the application WSGI middleware in charge of serving local files. A Depot middleware is required if your application wants to serve files from storages that don't directly provide and HTTP interface like :class:`depot.io.local.LocalFileStorage` and :class:`depot.io.gridfs.GridFSStorage` """ from depot.middleware import DepotMiddleware mw = DepotMiddleware(app, **options) cls.set_middleware(mw) return mw
Creates the application WSGI middleware in charge of serving local files. A Depot middleware is required if your application wants to serve files from storages that don't directly provide and HTTP interface like :class:`depot.io.local.LocalFileStorage` and :class:`depot.io.gridfs.GridFSStorage`
entailment
def from_config(cls, config, prefix='depot.'): """Creates a new depot from a settings dictionary. Behaves like the :meth:`configure` method but instead of configuring the application depot it creates a new one each time. """ 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)) # Backend is already passed as a positional argument options.pop('backend', None) return cls._new(backend, **options)
Creates a new depot from a settings dictionary. Behaves like the :meth:`configure` method but instead of configuring the application depot it creates a new one each time.
entailment
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_depot = None cls._depots = {} cls._middleware = None cls._aliases = {}
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.
entailment
def setup_schema(command, conf, vars): """Place any commands to setup depotexample here""" # 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> print("Creating tables") model.metadata.create_all(bind=config['tg.app_globals'].sa_engine) # <websetup.websetup.schema.after.metadata.create_all> transaction.commit() print('Initializing Migrations') import alembic.config, alembic.command alembic_cfg = alembic.config.Config() alembic_cfg.set_main_option("script_location", "migration") alembic_cfg.set_main_option("sqlalchemy.url", config['sqlalchemy.url']) alembic.command.stamp(alembic_cfg, "head")
Place any commands to setup depotexample here
entailment
def permissions(self): """Return a set with all permissions granted to the user.""" perms = set() for g in self.groups: perms = perms | set(g.permissions) return perms
Return a set with all permissions granted to the user.
entailment
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()
Return the user object whose email address is ``email``.
entailment
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()
Return the user object whose user name is ``username``.
entailment
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 database. :type password: unicode object. :return: Whether the password is valid. :rtype: bool """ hash = sha256() hash.update((password + self.password[:64]).encode('utf-8')) return self.password[64:] == hash.hexdigest()
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 database. :type password: unicode object. :return: Whether the password is valid. :rtype: bool
entailment
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('SCRIPT_NAME', ''), code=request.params.get('code', resp.status_int), message=request.params.get('message', default_message)) return values
Render the error document
entailment
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 :param full_stack: Should the whole TG2 stack be set up? :type full_stack: str or bool :return: The depotexample application with all the relevant middleware loaded. This is the PasteDeploy factory for the depotexample application. ``app_conf`` contains all the application-specific settings (those defined under ``[app:main]``. """ app = make_base_app(global_conf, full_stack=True, **app_conf) # Wrap your base TurboGears 2 application with custom middleware here from depot.manager import DepotManager app = DepotManager.make_middleware(app) return app
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 :param full_stack: Should the whole TG2 stack be set up? :type full_stack: str or bool :return: The depotexample application with all the relevant middleware loaded. This is the PasteDeploy factory for the depotexample application. ``app_conf`` contains all the application-specific settings (those defined under ``[app:main]``.
entailment
def process_content(self, content, filename=None, content_type=None): """Standard implementation of :meth:`.DepotFileInfo.process_content` This is the standard depot implementation of files upload, it will store the file on the default depot and will provide the standard attributes. Subclasses will need to call this method to ensure the standard set of attributes is provided. """ file_path, file_id = self.store_content(content, filename, content_type) self['file_id'] = file_id self['path'] = file_path saved_file = self.file self['filename'] = saved_file.filename self['content_type'] = saved_file.content_type self['uploaded_at'] = saved_file.last_modified.strftime('%Y-%m-%d %H:%M:%S') self['_public_url'] = saved_file.public_url
Standard implementation of :meth:`.DepotFileInfo.process_content` This is the standard depot implementation of files upload, it will store the file on the default depot and will provide the standard attributes. Subclasses will need to call this method to ensure the standard set of attributes is provided.
entailment
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 = '[email protected]' u.password = 'managepass' model.DBSession.add(u) g = model.Group() g.group_name = 'managers' g.display_name = 'Managers Group' g.users.append(u) model.DBSession.add(g) p = model.Permission() p.permission_name = 'manage' p.description = 'This permission give an administrative right to the bearer' p.groups.append(g) model.DBSession.add(p) u1 = model.User() u1.user_name = 'editor' u1.display_name = 'Example editor' u1.email_address = '[email protected]' u1.password = 'editpass' model.DBSession.add(u1) model.DBSession.flush() transaction.commit() except IntegrityError: print('Warning, there was a problem adding your auth data, it may have already been added:') import traceback print(traceback.format_exc()) transaction.abort() print('Continuing with bootstrapping...')
Place any commands to setup depotexample here
entailment
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
Provides a real file object from file content Converts ``FileStorage``, ``FileIntent`` and ``bytes`` to an actual file.
entailment
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. """ return _FileInfo(fileobj, filename, content_type).get_info(existing)
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.
entailment
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)
Start the user login.
entailment
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 page if login failed. """ 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) redirect(came_from)
Redirect the user to the initially requested page on successful authentication or redirect her back to the login page if login failed.
entailment
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_rewrites(date_classes, alt_rules) else: date_classes = _apply_rewrites(date_classes, RULES) date_string = '' for date_class in date_classes: date_string += date_class.directive return date_string
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.
entailment
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
Return a list of date elements by applying rewrites to the initial date element list
entailment
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(1) most_common.sort() return most_common[0][0]
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.
entailment
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 KeyError('No least restrictive date element found')
Return the date_elem that has the most restrictive range from date_elems
entailment
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 enumerate(date_classes): for token in tokens: if date_class.is_match(token): match_count[i] += 1 percentages = tuple([float(m) / len(tokens) for m in match_count]) return percentages
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.
entailment
def _tag_most_likely(examples): """ Return a list of date elements by choosing the most likely element for a token within examples (context-free). """ 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 equal the mode of lengths within tokenized_examples token_lengths = [len(e) for e in tokenized_examples] token_lengths_mode = _mode(token_lengths) tokenized_examples = [example for example in tokenized_examples if len(example) == token_lengths_mode] # Now, we iterate through the tokens, assigning date elements based on their likelihood. In cases where # the assignments are unlikely for all date elements, assign filler. most_likely = [] for token_index in range(0, token_lengths_mode): tokens = [token[token_index] for token in tokenized_examples] probabilities = _percent_match(DATE_ELEMENTS, tokens) max_prob = max(probabilities) if max_prob < 0.5: most_likely.append(Filler(_mode(tokens))) else: if probabilities.count(max_prob) == 1: most_likely.append(DATE_ELEMENTS[probabilities.index(max_prob)]) else: choices = [] for index, prob in enumerate(probabilities): if prob == max_prob: choices.append(DATE_ELEMENTS[index]) most_likely.append(_most_restrictive(choices)) return most_likely
Return a list of date elements by choosing the most likely element for a token within examples (context-free).
entailment
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_by_character_class('2013-08-14') => ['2013', '-', '08', '-', '14'] """ character_classes = [string.digits, string.ascii_letters, string.punctuation, string.whitespace] result = [] rest = list(s) while rest: progress = False for character_class in character_classes: if rest[0] in character_class: progress = True token = '' for take_away in itertools.takewhile(lambda c: c in character_class, rest[:]): token += take_away rest.pop(0) result.append(token) break if not progress: # none of the character classes matched; unprintable character? result.append(rest[0]) rest = rest[1:] return result
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_by_character_class('2013-08-14') => ['2013', '-', '08', '-', '14']
entailment
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
If condition, return a new elem_list provided by executing action.
entailment
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': return elem.is_numerical() elif seq_expr == '\D': return not elem.is_numerical() else: # invalid wild-card specified raise LookupError('{0} is not a valid wild-card'.format(seq_expr)) else: # date element return elem == seq_expr
Return True if elem (an element of elem_list) matches seq_expr, an element in self.sequence
entailment
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 seq_pos = 0 raise LookupError('Failed to find sequence in elem_list')
Return the first position in elem_list where find_seq starts
entailment
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 elif 85 <= grade < 90: return 3.7 elif 82 <= grade < 85: return 3.3 elif 78 <= grade < 82: return 3.0 elif 75 <= grade < 78: return 2.7 elif 72 <= grade < 75: return 2.3 elif 68 <= grade < 72: return 2.0 elif 66 <= grade < 68: return 1.7 elif 64 <= grade < 66: return 1.3 elif 60 <= grade < 64: return 1.0 else: return 0.0 except ValueError: if grade_str == '优': return 3.9 elif grade_str == '良': return 3.0 elif grade_str == '中': return 2.0 elif grade_str == '及格': return 1.2 elif grade_str in ('不及格', '免修', '未考'): return 0.0 else: raise ValueError('{:s} 不是有效的成绩'.format(grade_str))
根据成绩判断绩点 :param grade_str: 一个字符串,因为可能是百分制成绩或等级制成绩 :return: 成绩绩点 :rtype: float
entailment
def cal_gpa(grades): """ 根据成绩数组计算课程平均绩点和 gpa, 算法不一定与学校一致, 结果仅供参考 :param grades: :meth:`models.StudentSession.get_my_achievements` 返回的成绩数组 :return: 包含了课程平均绩点和 gpa 的元组 """ # 课程总数 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['成绩']) credit = float(grade['学分']) points_sum += point credit_sum += credit gpa_points_sum += credit * point ave_point = points_sum / courses_sum gpa = gpa_points_sum / credit_sum return round(ave_point, 5), round(gpa, 5)
根据成绩数组计算课程平均绩点和 gpa, 算法不一定与学校一致, 结果仅供参考 :param grades: :meth:`models.StudentSession.get_my_achievements` 返回的成绩数组 :return: 包含了课程平均绩点和 gpa 的元组
entailment
def cal_term_code(year, is_first_term=True): """ 计算对应的学期代码 :param year: 学年开始年份,例如 "2012-2013学年第二学期" 就是 2012 :param is_first_term: 是否为第一学期 :type is_first_term: bool :return: 形如 "022" 的学期代码 """ if year <= 2001: msg = '出现了超出范围年份: {}'.format(year) raise ValueError(msg) term_code = (year - 2001) * 2 if is_first_term: term_code -= 1 return '%03d' % term_code
计算对应的学期代码 :param year: 学年开始年份,例如 "2012-2013学年第二学期" 就是 2012 :param is_first_term: 是否为第一学期 :type is_first_term: bool :return: 形如 "022" 的学期代码
entailment
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] == '一')
将学期字符串转换为对应的学期代码串 :param term_str: 形如 "2012-2013学年第二学期" 的学期字符串 :return: 形如 "022" 的学期代码
entailment
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: 其他传递到 ``requests.request`` 的参数 :return: 形如 ``[(访问耗时, 地址)]`` 的排名数据 """ ranks = [] class HostCheckerThread(Thread): def __init__(self, host): super(HostCheckerThread, self).__init__() self.host = host def run(self): INFINITY = 10000000 try: url = urllib.parse.urljoin(self.host, path) res = requests.request(method, url, timeout=timeout, **kwargs) res.raise_for_status() cost = res.elapsed.total_seconds() * 1000 except Exception as e: logger.warning('访问出错: %s', e) cost = INFINITY # http://stackoverflow.com/questions/6319207/are-lists-thread-safe ranks.append((cost, self.host)) threads = [HostCheckerThread(u) for u in hosts] for t in threads: t.start() for t in threads: t.join() ranks.sort() return ranks
测试各个地址的速度并返回排名, 当出现错误时消耗时间为 INFINITY = 10000000 :param method: 请求方法 :param path: 默认的访问路径 :param hosts: 进行的主机地址列表, 如 `['http://222.195.8.201/']` :param timeout: 超时时间, 可以是一个浮点数或 形如 ``(连接超时, 读取超时)`` 的元祖 :param kwargs: 其他传递到 ``requests.request`` 的参数 :return: 形如 ``[(访问耗时, 地址)]`` 的排名数据
entailment
def filter_curriculum(curriculum, week, weekday=None): """ 筛选出指定星期[和指定星期几]的课程 :param curriculum: 课程表数据 :param week: 需要筛选的周数, 是一个代表周数的正整数 :param weekday: 星期几, 是一个代表星期的整数, 1-7 对应周一到周日 :return: 如果 weekday 参数没给出, 返回的格式与原课表一致, 但只包括了在指定周数的课程, 否则返回指定周数和星期几的当天课程 """ if weekday: c = [deepcopy(curriculum[weekday - 1])] else: c = deepcopy(curriculum) for d in c: l = len(d) for t_idx in range(l): t = d[t_idx] if t is None: continue # 一般同一时间课程不会重复,重复时给出警告 t = list(filter(lambda k: week in k['上课周数'], t)) or None if t is not None and len(t) > 1: logger.warning('第 %d 周周 %d 第 %d 节课有冲突: %s', week, weekday or c.index(d) + 1, t_idx + 1, t) d[t_idx] = t return c[0] if weekday else c
筛选出指定星期[和指定星期几]的课程 :param curriculum: 课程表数据 :param week: 需要筛选的周数, 是一个代表周数的正整数 :param weekday: 星期几, 是一个代表星期的整数, 1-7 对应周一到周日 :return: 如果 weekday 参数没给出, 返回的格式与原课表一致, 但只包括了在指定周数的课程, 否则返回指定周数和星期几的当天课程
entailment
def curriculum2schedule(curriculum, first_day, compress=False, time_table=None): """ 将课程表转换为上课时间表, 如果 compress=False 结果是未排序的, 否则为压缩并排序后的上课时间表 :param curriculum: 课表 :param first_day: 第一周周一, 如 datetime.datetime(2016, 8, 29) :param compress: 压缩连续的课时为一个 :param time_table: 每天上课的时间表, 形如 ``((start timedelta, end timedelta), ...)`` 的 11 × 2 的矩阵 :return: [(datetime.datetime, str) ...] """ schedule = [] time_table = time_table or ( (timedelta(hours=8), timedelta(hours=8, minutes=50)), (timedelta(hours=9), timedelta(hours=9, minutes=50)), (timedelta(hours=10, minutes=10), timedelta(hours=11)), (timedelta(hours=11, minutes=10), timedelta(hours=12)), (timedelta(hours=14), timedelta(hours=14, minutes=50)), (timedelta(hours=15), timedelta(hours=15, minutes=50)), (timedelta(hours=16), timedelta(hours=16, minutes=50)), (timedelta(hours=17), timedelta(hours=17, minutes=50)), (timedelta(hours=19), timedelta(hours=19, minutes=50)), (timedelta(hours=19, minutes=50), timedelta(hours=20, minutes=40)), (timedelta(hours=20, minutes=40), timedelta(hours=21, minutes=30)) ) for i, d in enumerate(curriculum): for j, cs in enumerate(d): for c in cs or []: course = '{name}[{place}]'.format(name=c['课程名称'], place=c['课程地点']) for week in c['上课周数']: day = first_day + timedelta(weeks=week - 1, days=i) start, end = time_table[j] item = (week, day + start, day + end, course) schedule.append(item) schedule.sort() if compress: new_schedule = [schedule[0]] for i in range(1, len(schedule)): sch = schedule[i] # 同一天的连续课程 if new_schedule[-1][1].date() == sch[1].date() and new_schedule[-1][3] == sch[3]: # 更新结束时间 old_item = new_schedule.pop() # week, start, end, course new_item = (old_item[0], old_item[1], sch[2], old_item[3]) else: new_item = sch new_schedule.append(new_item) return new_schedule return schedule
将课程表转换为上课时间表, 如果 compress=False 结果是未排序的, 否则为压缩并排序后的上课时间表 :param curriculum: 课表 :param first_day: 第一周周一, 如 datetime.datetime(2016, 8, 29) :param compress: 压缩连续的课时为一个 :param time_table: 每天上课的时间表, 形如 ``((start timedelta, end timedelta), ...)`` 的 11 × 2 的矩阵 :return: [(datetime.datetime, str) ...]
entailment
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 (> 0) board_height : int the height of the board (> 0) num_mines : int the number of mines, cannot be larger than (board_width x board_height) port : int UDP port number, default is 5678 ip_add : string the ip address for receiving the command, default is localhost. """ 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) fun_wg = gui.ControlWidget() grid_wg = gui.GameWidget(ms_game, fun_wg) remote_thread = gui.RemoteControlThread() def update_grid_remote(move_msg): """Update grid from remote control.""" if grid_wg.ms_game.game_status == 2: grid_wg.ms_game.play_move_msg(str(move_msg)) grid_wg.update_grid() remote_thread.transfer.connect(update_grid_remote) def reset_button_state(): """Reset button state.""" grid_wg.reset_game() fun_wg.reset_button.clicked.connect(reset_button_state) ms_layout.addWidget(fun_wg, 0, 0) ms_layout.addWidget(grid_wg, 1, 0) remote_thread.control_start(grid_wg.ms_game) ms_window.show() ms_app.exec_()
Main function for Mine Sweeper Game. Parameters ---------- board_width : int the width of the board (> 0) board_height : int the height of the board (> 0) num_mines : int the number of mines, cannot be larger than (board_width x board_height) port : int UDP port number, default is 5678 ip_add : string the ip address for receiving the command, default is localhost.
entailment
def schedule2calendar(schedule, name='课表', using_todo=True): """ 将上课时间表转换为 icalendar :param schedule: 上课时间表 :param name: 日历名称 :param using_todo: 使用 ``icalendar.Todo`` 而不是 ``icalendar.Event`` 作为活动类 :return: icalendar.Calendar() """ # 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', 'Asia/Shanghai') cal.add('X-WR-CALNAME', name) cls = icalendar.Todo if using_todo else icalendar.Event for week, start, end, data in schedule: # "事件"组件更具通用性, Google 日历不支持"待办"组件 item = cls( SUMMARY='第{:02d}周-{}'.format(week, data), DTSTART=icalendar.vDatetime(start), DTEND=icalendar.vDatetime(end), DESCRIPTION='起始于 {}, 结束于 {}'.format(start.strftime('%H:%M'), end.strftime('%H:%M')) ) now = datetime.now() # 这个状态"事件"组件是没有的, 对于待办列表类应用有作用 # https://tools.ietf.org/html/rfc5545#section-3.2.12 if using_todo: if start < now < end: item.add('STATUS', 'IN-PROCESS') elif now > end: item.add('STATUS', 'COMPLETED') cal.add_component(item) return cal
将上课时间表转换为 icalendar :param schedule: 上课时间表 :param name: 日历名称 :param using_todo: 使用 ``icalendar.Todo`` 而不是 ``icalendar.Event`` 作为活动类 :return: icalendar.Calendar()
entailment
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: win, 2: playing moves : int how many moves carried out. """ 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 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.tcp_socket.bind((self.TCP_IP, self.TCP_PORT)) self.tcp_socket.listen(1)
Init a new game. Parameters ---------- board : MSBoard define a new board. game_status : int define the game status: 0: lose, 1: win, 2: playing moves : int how many moves carried out.
entailment
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 into a valid 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 """ 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("This is not a valid Y position of the move!") move_des = {} move_des["move_type"] = move_type move_des["move_x"] = move_x move_des["move_y"] = move_y self.num_moves += 1 return move_des
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 into a valid 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
entailment
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", "question" move_x : int X position of the move move_y : int Y position of the move """ # 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": self.board.click_field(move_x, move_y) elif move_type == "flag": self.board.flag_field(move_x, move_y) elif move_type == "unflag": self.board.unflag_field(move_x, move_y) elif move_type == "question": self.board.question_field(move_x, move_y) # check the status, see if end the game if self.board.check_board() == 0: self.game_status = 0 # game loses # self.print_board() self.end_game() elif self.board.check_board() == 1: self.game_status = 1 # game wins # self.print_board() self.end_game() elif self.board.check_board() == 2: self.game_status = 2
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
entailment
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
Parse a move from a string. Parameters ---------- move_msg : string a valid message should be in: "[move type]: [X], [Y]" Returns -------
entailment
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], [Y]" """ move_type, move_x, move_y = self.parse_move(move_msg) self.play_move(move_type, move_x, move_y)
Another play move function for move message. Parameters ---------- move_msg : string a valid message should be in: "[move type]: [X], [Y]"
entailment
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("> ")
Waiting for a TCP connection.
entailment
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)
Receive data from TCP port.
entailment
def parse_tr_strs(trs): """ 将没有值但有必须要的单元格的值设置为 None 将 <tr> 标签数组内的单元格文字解析出来并返回一个二维列表 :param trs: <tr> 标签或标签数组, 为 :class:`bs4.element.Tag` 对象 :return: 二维列表 """ 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%s', pformat(tr_strs)) return tr_strs
将没有值但有必须要的单元格的值设置为 None 将 <tr> 标签数组内的单元格文字解析出来并返回一个二维列表 :param trs: <tr> 标签或标签数组, 为 :class:`bs4.element.Tag` 对象 :return: 二维列表
entailment
def flatten_list(multiply_list): """ 碾平 list:: >>> a = [1, 2, [3, 4], [[5, 6], [7, 8]]] >>> flatten_list(a) [1, 2, 3, 4, 5, 6, 7, 8] :param multiply_list: 混淆的多层列表 :return: 单层的 list """ if isinstance(multiply_list, list): return [rv for l in multiply_list for rv in flatten_list(l)] else: return [multiply_list]
碾平 list:: >>> a = [1, 2, [3, 4], [[5, 6], [7, 8]]] >>> flatten_list(a) [1, 2, 3, 4, 5, 6, 7, 8] :param multiply_list: 混淆的多层列表 :return: 单层的 list
entailment
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 range(n): row = dict_list[i] for j in range(k): col = columns[j] if col in row: result[i][j] = row[col] else: result[i][j] = None return result
>>> dict_list_2_matrix([{'a': 1, 'b': 2}, {'a': 3, 'b': 4}], ('a', 'b')) [[1, 2], [3, 4]] :param dict_list: 字典列表 :param columns: 字典的键
entailment
def parse_course(course_str): """ 解析课程表里的课程 :param course_str: 形如 `单片机原理及应用[新安学堂434 (9-15周)]/数字图像处理及应用[新安学堂434 (1-7周)]/` 的课程表数据 """ # 解析课程单元格 # 所有情况 # 机械原理[一教416 (1-14周)]/ # 程序与算法综合设计[不占用教室 (18周)]/ # 财务管理[一教323 (11-17单周)]/ # 财务管理[一教323 (10-16双周)]/ # 形势与政策(4)[一教220 (2,4,6-7周)]/ p = re.compile(r'(.+?)\[(.+?)\s+\(([\d,-单双]+?)周\)\]/') courses = p.findall(course_str) results = [] for course in courses: d = {'课程名称': course[0], '课程地点': course[1]} # 解析上课周数 week_str = course[2] l = week_str.split(',') weeks = [] for v in l: m = re.match(r'(\d+)$', v) or re.match(r'(\d+)-(\d+)$', v) or re.match(r'(\d+)-(\d+)(单|双)$', v) g = m.groups() gl = len(g) if gl == 1: weeks.append(int(g[0])) elif gl == 2: weeks.extend([i for i in range(int(g[0]), int(g[1]) + 1)]) else: weeks.extend([i for i in range(int(g[0]), int(g[1]) + 1, 2)]) d['上课周数'] = weeks results.append(d) return results
解析课程表里的课程 :param course_str: 形如 `单片机原理及应用[新安学堂434 (9-15周)]/数字图像处理及应用[新安学堂434 (1-7周)]/` 的课程表数据
entailment
def get_class_students(self, xqdm, kcdm, jxbh): """ 教学班查询, 查询指定教学班的所有学生 @structure {'学期': str, '班级名称': str, '学生': [{'姓名': str, '学号': int}]} :param xqdm: 学期代码 :param kcdm: 课程代码 :param jxbh: 教学班号 """ return self.query(GetClassStudents(xqdm, kcdm, jxbh))
教学班查询, 查询指定教学班的所有学生 @structure {'学期': str, '班级名称': str, '学生': [{'姓名': str, '学号': int}]} :param xqdm: 学期代码 :param kcdm: 课程代码 :param jxbh: 教学班号
entailment
def get_class_info(self, xqdm, kcdm, jxbh): """ 获取教学班详情, 包括上课时间地点, 考查方式, 老师, 选中人数, 课程容量等等信息 @structure {'校区': str,'开课单位': str,'考核类型': str,'课程类型': str,'课程名称': str,'教学班号': str,'起止周': str, '时间地点': str,'学分': float,'性别限制': str,'优选范围': str,'禁选范围': str,'选中人数': int,'备注': str} :param xqdm: 学期代码 :param kcdm: 课程代码 :param jxbh: 教学班号 """ return self.query(GetClassInfo(xqdm, kcdm, jxbh))
获取教学班详情, 包括上课时间地点, 考查方式, 老师, 选中人数, 课程容量等等信息 @structure {'校区': str,'开课单位': str,'考核类型': str,'课程类型': str,'课程名称': str,'教学班号': str,'起止周': str, '时间地点': str,'学分': float,'性别限制': str,'优选范围': str,'禁选范围': str,'选中人数': int,'备注': str} :param xqdm: 学期代码 :param kcdm: 课程代码 :param jxbh: 教学班号
entailment
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))
课程查询 @structure [{'任课教师': str, '课程名称': str, '教学班号': str, '课程代码': str, '班级容量': int}] :param xqdm: 学期代码 :param kcdm: 课程代码 :param kcmc: 课程名称
entailment
def get_teaching_plan(self, xqdm, kclx='b', zydm=''): """ 专业教学计划查询, 可以查询全校公选课, 此时可以不填 `zydm` @structure [{'开课单位': str, '学时': int, '课程名称': str, '课程代码': str, '学分': float}] :param xqdm: 学期代码 :param kclx: 课程类型参数,只有两个值 b:专业必修课, x:全校公选课 :param zydm: 专业代码, 可以从 :meth:`models.StudentSession.get_code` 获得 """ return self.query(GetTeachingPlan(xqdm, kclx, zydm))
专业教学计划查询, 可以查询全校公选课, 此时可以不填 `zydm` @structure [{'开课单位': str, '学时': int, '课程名称': str, '课程代码': str, '学分': float}] :param xqdm: 学期代码 :param kclx: 课程类型参数,只有两个值 b:专业必修课, x:全校公选课 :param zydm: 专业代码, 可以从 :meth:`models.StudentSession.get_code` 获得
entailment
def change_password(self, new_password): """ 修改教务密码, **注意** 合肥校区使用信息中心账号登录, 与教务密码不一致, 即使修改了也没有作用, 因此合肥校区帐号调用此接口会直接报错 @structure bool :param new_password: 新密码 """ if self.session.campus == HF: raise ValueError('合肥校区使用信息中心账号登录, 修改教务密码没有作用') # 若新密码与原密码相同, 直接返回 True if new_password == self.session.password: raise ValueError('原密码与新密码相同') result = self.query(ChangePassword(self.session.password, new_password)) if result: self.session.password = new_password return result
修改教务密码, **注意** 合肥校区使用信息中心账号登录, 与教务密码不一致, 即使修改了也没有作用, 因此合肥校区帐号调用此接口会直接报错 @structure bool :param new_password: 新密码
entailment
def set_telephone(self, tel): """ 更新电话 @structure bool :param tel: 电话号码, 需要满足手机和普通电话的格式, 例如 `18112345678` 或者 '0791-1234567' """ return type(tel)(self.query(SetTelephone(tel))) == tel
更新电话 @structure bool :param tel: 电话号码, 需要满足手机和普通电话的格式, 例如 `18112345678` 或者 '0791-1234567'
entailment
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 为最好. 默认都是最好的选项 :param kcdm: 课程代码 :param jxbh: 教学班号 :param r101: 教学态度认真,课前准备充分 :param r102: 教授内容充实,要点重点突出 :param r103: 理论联系实际,反映最新成果 :param r104: 教学方法灵活,师生互动得当 :param r105: 运用现代技术,教学手段多样 :param r106: 注重因材施教,加强能力培养 :param r107: 严格要求管理,关心爱护学生 :param r108: 处处为人师表,注重教书育人 :param r109: 教学综合效果 :param r201: 课程内容 :param r202: 课程负担 :param advice: 其他建议,不能超过120字且不能使用分号,单引号,都好 :return: """ return self.query(EvaluateCourse( kcdm, jxbh, r101, r102, r103, r104, r105, r106, r107, r108, r109, r201, r202, advice ))
课程评价, 数值为 1-5, r1 类选项 1 为最好, 5 为最差, r2 类选项程度由深到浅, 3 为最好. 默认都是最好的选项 :param kcdm: 课程代码 :param jxbh: 教学班号 :param r101: 教学态度认真,课前准备充分 :param r102: 教授内容充实,要点重点突出 :param r103: 理论联系实际,反映最新成果 :param r104: 教学方法灵活,师生互动得当 :param r105: 运用现代技术,教学手段多样 :param r106: 注重因材施教,加强能力培养 :param r107: 严格要求管理,关心爱护学生 :param r108: 处处为人师表,注重教书育人 :param r109: 教学综合效果 :param r201: 课程内容 :param r202: 课程负担 :param advice: 其他建议,不能超过120字且不能使用分号,单引号,都好 :return:
entailment
def change_course(self, select_courses=None, delete_courses=None): """ 修改个人的课程 @structure [{'费用': float, '教学班号': str, '课程名称': str, '课程代码': str, '学分': float, '课程类型': str}] :param select_courses: 形如 ``[{'kcdm': '9900039X', 'jxbhs': {'0001', '0002'}}]`` 的课程代码与教学班号列表, jxbhs 可以为空代表选择所有可选班级 :param delete_courses: 需要删除的课程代码集合, 如 ``{'0200011B'}`` :return: 选课结果, 返回选中的课程教学班列表, 结构与 ``get_selected_courses`` 一致 """ # 框架重构后调整接口的调用 t = self.get_system_status() if t['当前轮数'] is None: raise ValueError('当前为 %s,选课系统尚未开启', t['当前学期']) if not (select_courses or delete_courses): raise ValueError('select_courses, delete_courses 参数不能都为空!') # 参数处理 select_courses = select_courses or [] delete_courses = {l.upper() for l in (delete_courses or [])} selected_courses = self.get_selected_courses() selected_kcdms = {course['课程代码'] for course in selected_courses} # 尝试删除没有被选中的课程会出错 unselected = delete_courses.difference(selected_kcdms) if unselected: msg = '无法删除没有被选的课程 {}'.format(unselected) logger.warning(msg) # 要提交的 kcdm 数据 kcdms_data = [] # 要提交的 jxbh 数据 jxbhs_data = [] # 必须添加已选课程, 同时去掉要删除的课程 for course in selected_courses: if course['课程代码'] not in delete_courses: kcdms_data.append(course['课程代码']) jxbhs_data.append(course['教学班号']) # 选课 for kv in select_courses: kcdm = kv['kcdm'].upper() jxbhs = set(kv['jxbhs']) if kv.get('jxbhs') else set() teaching_classes = self.get_course_classes(kcdm) if not teaching_classes: logger.warning('课程[%s]没有可选班级', kcdm) continue # 反正是统一提交, 不需要判断是否已满 optional_jxbhs = {c['教学班号'] for c in teaching_classes['可选班级']} if jxbhs: wrong_jxbhs = jxbhs.difference(optional_jxbhs) if wrong_jxbhs: msg = '课程[{}]{}没有教学班号{}'.format(kcdm, teaching_classes['课程名称'], wrong_jxbhs) logger.warning(msg) jxbhs = jxbhs.intersection(optional_jxbhs) else: jxbhs = optional_jxbhs for jxbh in jxbhs: kcdms_data.append(kcdm) jxbhs_data.append(jxbh) return self.query(ChangeCourse(self.session.account, select_courses, delete_courses))
修改个人的课程 @structure [{'费用': float, '教学班号': str, '课程名称': str, '课程代码': str, '学分': float, '课程类型': str}] :param select_courses: 形如 ``[{'kcdm': '9900039X', 'jxbhs': {'0001', '0002'}}]`` 的课程代码与教学班号列表, jxbhs 可以为空代表选择所有可选班级 :param delete_courses: 需要删除的课程代码集合, 如 ``{'0200011B'}`` :return: 选课结果, 返回选中的课程教学班列表, 结构与 ``get_selected_courses`` 一致
entailment
def check_courses(self, kcdms): """ 检查课程是否被选 @structure [bool] :param kcdms: 课程代码列表 :return: 与课程代码列表长度一致的布尔值列表, 已为True,未选为False """ selected_courses = self.get_selected_courses() selected_kcdms = {course['课程代码'] for course in selected_courses} result = [True if kcdm in selected_kcdms else False for kcdm in kcdms] return result
检查课程是否被选 @structure [bool] :param kcdms: 课程代码列表 :return: 与课程代码列表长度一致的布尔值列表, 已为True,未选为False
entailment
def get_selectable_courses(self, kcdms=None, pool_size=5, dump_result=True, filename='可选课程.json', encoding='utf-8'): """ 获取所有能够选上的课程的课程班级, 注意这个方法遍历所给出的课程和它们的可选班级, 当选中人数大于等于课程容量时表示不可选. 由于请求非常耗时且一般情况下用不到, 因此默认推荐在第一轮选课结束后到第三轮选课结束之前的时间段使用, 如果你仍然坚持使用, 你将会得到一个警告. @structure [{'可选班级': [{'起止周': str, '考核类型': str, '教学班附加信息': str, '课程容量': int, '选中人数': int, '教学班号': str, '禁选专业': str, '教师': [str], '校区': str, '优选范围': [str], '开课时间,开课地点': [str]}], '课程代码': str, '课程名称': str}] :param kcdms: 课程代码列表, 默认为所有可选课程的课程代码 :param dump_result: 是否保存结果到本地 :param filename: 保存的文件路径 :param encoding: 文件编码 """ now = time.time() t = self.get_system_status() if not (t['选课计划'][0][1] < now < t['选课计划'][2][1]): logger.warning('只推荐在第一轮选课结束到第三轮选课结束之间的时间段使用本接口!') def iter_kcdms(): for l in self.get_optional_courses(): yield l['课程代码'] kcdms = kcdms or iter_kcdms() def target(kcdm): course_classes = self.get_course_classes(kcdm) if not course_classes: return course_classes['可选班级'] = [c for c in course_classes['可选班级'] if c['课程容量'] > c['选中人数']] if len(course_classes['可选班级']) > 0: return course_classes # Python 2.7 不支持 with 语法 pool = Pool(pool_size) result = list(filter(None, pool.map(target, kcdms))) pool.close() pool.join() if dump_result: json_str = json.dumps(result, ensure_ascii=False, indent=4, sort_keys=True) with open(filename, 'wb') as fp: fp.write(json_str.encode(encoding)) logger.info('可选课程结果导出到了:%s', filename) return result
获取所有能够选上的课程的课程班级, 注意这个方法遍历所给出的课程和它们的可选班级, 当选中人数大于等于课程容量时表示不可选. 由于请求非常耗时且一般情况下用不到, 因此默认推荐在第一轮选课结束后到第三轮选课结束之前的时间段使用, 如果你仍然坚持使用, 你将会得到一个警告. @structure [{'可选班级': [{'起止周': str, '考核类型': str, '教学班附加信息': str, '课程容量': int, '选中人数': int, '教学班号': str, '禁选专业': str, '教师': [str], '校区': str, '优选范围': [str], '开课时间,开课地点': [str]}], '课程代码': str, '课程名称': str}] :param kcdms: 课程代码列表, 默认为所有可选课程的课程代码 :param dump_result: 是否保存结果到本地 :param filename: 保存的文件路径 :param encoding: 文件编码
entailment
def send(self, request, **kwargs): """ 所有接口用来发送请求的方法, 只是 :meth:`requests.sessions.Session.send` 的一个钩子方法, 用来处理请求前后的工作 """ response = super(BaseSession, self).send(request, **kwargs) if ENV['RAISE_FOR_STATUS']: response.raise_for_status() parsed = parse.urlparse(response.url) if parsed.netloc == parse.urlparse(self.host).netloc: response.encoding = ENV['SITE_ENCODING'] # 快速判断响应 IP 是否被封, 那个警告响应内容长度为 327 或 328, 保留一点余量确保准确 min_length, max_length, pattern = ENV['IP_BANNED_RESPONSE'] if min_length <= len(response.content) <= max_length and pattern.search(response.text): msg = '当前 IP 已被锁定, 如果可以请尝试切换教务系统地址, 否则请在更换网络环境或等待解封后重试!' raise IPBanned(msg) self.histories.append(response) logger.debug(report_response(response, redirection=kwargs.get('allow_redirects'))) return response
所有接口用来发送请求的方法, 只是 :meth:`requests.sessions.Session.send` 的一个钩子方法, 用来处理请求前后的工作
entailment
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 : numpy.ndarray the map that presents to gamer 0-8 is number of mines in srrounding. 9 is flagged field. 10 is questioned field. 11 is undiscovered field. 12 is a mine field. """ 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) idx_y = int(idx / self.board_width) self.mine_map[idx_y, idx_x] = 1 self.info_map = np.ones((self.board_height, self.board_width), dtype=np.uint8)*11
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 : numpy.ndarray the map that presents to gamer 0-8 is number of mines in srrounding. 9 is flagged field. 10 is questioned field. 11 is undiscovered field. 12 is a mine field.
entailment