Search is not available for this dataset
text stringlengths 75 104k |
|---|
def _next(self, state_class, *args):
"""Transition into the next state.
:param type state_class: a subclass of :class:`State`. It is intialized
with the communication object and :paramref:`args`
:param args: additional arguments
"""
self._communication.state = state_cl... |
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`, ... |
def receive_start_confirmation(self, message):
"""Receive a StartConfirmation message.
:param message: a :class:`StartConfirmation
<AYABInterface.communication.hardware_messages.StartConfirmation>`
message
If the message indicates success, the communication object transitio... |
def enter(self):
"""Send a StartRequest."""
self._communication.send(StartRequest,
self._communication.left_end_needle,
self._communication.right_end_needle) |
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.las... |
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:
... |
def check(self):
"""Check for validity.
:raises ValueError:
- if not all lines are as long as the :attr:`number of needles
<AYABInterface.machines.Machine.number_of_needles>`
- if the contents of the rows are not :attr:`needle positions
<AYABInterface.machin... |
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] |
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:
... |
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(
... |
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 = (
M... |
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
... |
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 |
def _id(self):
"""What this object is equal to."""
return (self.__class__, self.number_of_needles, self.needle_positions,
self.left_end_needle) |
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... |
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... |
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): Th... |
def _replace_image(image_url, image_tag, ebook_folder,
image_name=None):
"""
Replaces the src of an image to link to the local copy in the images folder of the ebook. Tightly coupled with bs4
package.
Args:
image_url (str): The url of the image.
image_tag (bs4.ele... |
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 ValueE... |
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... |
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): T... |
def create_chapter_from_string(self, html_string, url=None, title=None):
"""
Creates a Chapter object from a string. Sanitizes the
string using the clean_function method, and saves
it as the content of the created chapter.
Args:
html_string (string): The html or xhtm... |
def create_html_from_fragment(tag):
"""
Creates full html tree from a fragment. Assumes that tag should be wrapped in a body and is currently not
Args:
tag: a bs4.element.Tag
Returns:"
bs4.element.Tag: A bs4 tag representing a full html document
"""
try:
assert isinsta... |
def clean(input_string,
tag_dictionary=constants.SUPPORTED_TAGS):
"""
Sanitizes HTML. Tags not contained as keys in the tag_dictionary input are
removed, and child nodes are recursively moved to parent of removed node.
Attributes not contained as arguments in tag_dictionary are removed.
Do... |
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'... |
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.... |
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 ... |
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... |
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]] |
def p_contents(self, p):
"""contents : contents statements
| contents comment
| contents include
| contents includeoptional
| contents block
| statements
| comment
| includ... |
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:
... |
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]] |
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') |
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('INITIA... |
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
l... |
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.lex... |
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 |
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.le... |
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 |
def get(cls, name=None):
"""Gets the application wide depot instance.
Might return ``None`` if :meth:`configure` has not been
called yet.
"""
if name is None:
name = cls._default_depot
name = cls.resolve_alias(name) # resolve alias
return cls._depo... |
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) |
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... |
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.LocalFi... |
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... |
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_... |
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_a... |
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 |
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() |
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() |
def validate_password(self, password):
"""
Check the password against existing credentials.
:param password: the password that was provided by the user to
try and authenticate. This is the clear text version that we will
need to match against the hashed one in the databa... |
def document(self, *args, **kwargs):
"""Render the error document"""
resp = request.environ.get('pylons.original_response')
default_message = ("<p>We're sorry but we weren't able to process "
" this request.</p>")
values = dict(prefix=request.environ.get('SCRIP... |
def make_app(global_conf, full_stack=True, **app_conf):
"""
Set depotexample up with the settings found in the PasteDeploy configuration
file used.
:param global_conf: The global settings for depotexample (those
defined under the ``[DEFAULT]`` section).
:type global_conf: dict
:para... |
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.
... |
def bootstrap(command, conf, vars):
"""Place any commands to setup depotexample here"""
# <websetup.bootstrap.before.auth
from sqlalchemy.exc import IntegrityError
try:
u = model.User()
u.user_name = 'manager'
u.display_name = 'Example manager'
u.email_address = 'manager... |
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 = con... |
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.
... |
def login(self, came_from=lurl('/')):
"""Start the user login."""
login_counter = request.environ.get('repoze.who.logins', 0)
if login_counter > 0:
flash(_('Wrong credentials'), 'warning')
return dict(page='login', login_counter=str(login_counter),
came_fr... |
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',... |
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_... |
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 |
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... |
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_ELEMEN... |
def _percent_match(date_classes, tokens):
"""
For each date class, return the percentage of tokens that the class matched (floating point [0.0 - 1.0]). The
returned value is a tuple of length patterns. Tokens should be a list.
"""
match_count = [0] * len(date_classes)
for i, date_class in enume... |
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... |
def _tokenize_by_character_class(s):
"""
Return a list of strings by splitting s (tokenizing) by character class.
For example:
_tokenize_by_character_class('Sat Jan 11 19:54:52 MST 2014') => ['Sat', ' ', 'Jan', ' ', '11', ' ', '19', ':',
'54', ':', '52', ' ', 'MST', ' ', '2014']
_tokenize_b... |
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 |
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':
... |
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... |
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
... |
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_... |
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)
t... |
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] == '一') |
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... |
def filter_curriculum(curriculum, week, weekday=None):
"""
筛选出指定星期[和指定星期几]的课程
:param curriculum: 课程表数据
:param week: 需要筛选的周数, 是一个代表周数的正整数
:param weekday: 星期几, 是一个代表星期的整数, 1-7 对应周一到周日
:return: 如果 weekday 参数没给出, 返回的格式与原课表一致, 但只包括了在指定周数的课程, 否则返回指定周数和星期几的当天课程
"""
if weekday:
c = [dee... |
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 tim... |
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... |
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://i... |
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 ... |
def check_move(self, move_type, move_x, move_y):
"""Check if a move is valid.
If the move is not valid, then shut the game.
If the move is valid, then setup a dictionary for the game,
and update move counter.
TODO: maybe instead of shut the game, can end the game or turn it int... |
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
... |
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_... |
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... |
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("> ") |
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) |
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)
... |
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 ... |
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... |
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周)... |
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)) |
def get_class_info(self, xqdm, kcdm, jxbh):
"""
获取教学班详情, 包括上课时间地点, 考查方式, 老师, 选中人数, 课程容量等等信息
@structure {'校区': str,'开课单位': str,'考核类型': str,'课程类型': str,'课程名称': str,'教学班号': str,'起止周': str,
'时间地点': str,'学分': float,'性别限制': str,'优选范围': str,'禁选范围': str,'选中人数': int,'备注': str}
:param xq... |
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)) |
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.St... |
def change_password(self, new_password):
"""
修改教务密码, **注意** 合肥校区使用信息中心账号登录, 与教务密码不一致, 即使修改了也没有作用, 因此合肥校区帐号调用此接口会直接报错
@structure bool
:param new_password: 新密码
"""
if self.session.campus == HF:
raise ValueError('合肥校区使用信息中心账号登录, 修改教务密码没有作用')
# 若新密码与原密码... |
def set_telephone(self, tel):
"""
更新电话
@structure bool
:param tel: 电话号码, 需要满足手机和普通电话的格式, 例如 `18112345678` 或者 '0791-1234567'
"""
return type(tel)(self.query(SetTelephone(tel))) == tel |
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: 课程代码
:pa... |
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 可以为空代... |
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}
re... |
def get_selectable_courses(self, kcdms=None, pool_size=5, dump_result=True, filename='可选课程.json', encoding='utf-8'):
"""
获取所有能够选上的课程的课程班级, 注意这个方法遍历所给出的课程和它们的可选班级, 当选中人数大于等于课程容量时表示不可选.
由于请求非常耗时且一般情况下用不到, 因此默认推荐在第一轮选课结束后到第三轮选课结束之前的时间段使用, 如果你仍然坚持使用, 你将会得到一个警告.
@structure [{'可选班级': [{'起止周'... |
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.urlpars... |
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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.