code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class TrueCrypt(DumperTemplate): <NEW_LINE> <INDENT> procnames = ["TrueCrypt.exe"] <NEW_LINE> def run(self): <NEW_LINE> <INDENT> self.memdump() <NEW_LINE> self.commands('truecryptmaster', 'truecryptpassphrase', 'truecryptsummary')
Dumper for the common application TrueCrypt.
6259906c283ffb24f3cf50e0
class Property(object): <NEW_LINE> <INDENT> def __init__(self, concept_ref='', is_parent=False): <NEW_LINE> <INDENT> self.concept_ref = concept_ref <NEW_LINE> self.is_parent = is_parent <NEW_LINE> <DEDENT> def toXMLElement(self): <NEW_LINE> <INDENT> property_element = xml.etree.ElementTree.Element('property') <NEW_LINE> property_element.set('concept', self.concept_ref) <NEW_LINE> if self.is_parent: <NEW_LINE> <INDENT> property_element.set('isParent', 'true') <NEW_LINE> <DEDENT> return property_element
Representation of a simple DSPL concept property. For now, this representation is limited to properties with just a concept reference and (optional) isParent attribute.
6259906ce76e3b2f99fda239
class TokenDetail(NamedTuple): <NEW_LINE> <INDENT> surface: str <NEW_LINE> normalized: str <NEW_LINE> feature: TokenFeature <NEW_LINE> named_entity: str <NEW_LINE> chunk: CaboCha.Chunk <NEW_LINE> @classmethod <NEW_LINE> def from_cabocha_token(cls, token: CaboCha.Token): <NEW_LINE> <INDENT> feature = token.feature <NEW_LINE> token_feature = TokenFeature.from_result(*feature.split(',')) <NEW_LINE> if token_feature.base_form == '*': <NEW_LINE> <INDENT> token_feature._replace(base_form=token.surface) <NEW_LINE> <DEDENT> return cls(token.surface, token.normalized_surface, token_feature, token.ne, token.chunk)
形態素情報の詳細 Attributes: surface (str): 表層形 normalized: 正規化後の形 feature (TokenFeature): 表層形を除いた形態素情報 named_entity (str): 固有表現 chunk (CaboCha.Chunk): 複合語内の単語
6259906c9c8ee82313040da4
class Hebbian(LearningFn): <NEW_LINE> <INDENT> def __call__(self,input_activity, unit_activity, weights, single_connection_learning_rate): <NEW_LINE> <INDENT> weights += single_connection_learning_rate * unit_activity * input_activity
Basic Hebbian rule; Dayan and Abbott, 2001, equation 8.3. Increases each weight in proportion to the product of this neuron's activity and the input activity. Requires some form of output_fn normalization for stability.
6259906cfff4ab517ebcf053
class Group(Node): <NEW_LINE> <INDENT> __documentation_section__ = 'Session Objects' <NEW_LINE> __slots__ = () <NEW_LINE> _valid_add_actions = ( servertools.AddAction.ADD_TO_HEAD, servertools.AddAction.ADD_TO_TAIL, servertools.AddAction.ADD_AFTER, servertools.AddAction.ADD_BEFORE, ) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return 'group-{}'.format(self.session_id) <NEW_LINE> <DEDENT> def _to_request(self, action, id_mapping): <NEW_LINE> <INDENT> source_id = id_mapping[action.source] <NEW_LINE> target_id = id_mapping[action.target] <NEW_LINE> add_action = action.action <NEW_LINE> request = requesttools.GroupNewRequest( add_action=add_action, node_id=source_id, target_node_id=target_id, ) <NEW_LINE> return request
A non-realtime group.
6259906c7b180e01f3e49c80
class PhabricatorOAuth2(BaseOAuth2): <NEW_LINE> <INDENT> name = 'phabricator' <NEW_LINE> API_URL = 'https://secure.phabricator.com' <NEW_LINE> AUTHORIZATION_URL = 'https://secure.phabricator.com/oauthserver/auth/' <NEW_LINE> ACCESS_TOKEN_URL = 'https://secure.phabricator.com/oauthserver/token/' <NEW_LINE> ACCESS_TOKEN_METHOD = 'POST' <NEW_LINE> REDIRECT_STATE = False <NEW_LINE> def api_url(self, path): <NEW_LINE> <INDENT> api_url = self.setting('API_URL') or self.API_URL <NEW_LINE> return '{0}{1}'.format(api_url.rstrip('/'), path) <NEW_LINE> <DEDENT> def authorization_url(self): <NEW_LINE> <INDENT> return self.api_url('/oauthserver/auth/') <NEW_LINE> <DEDENT> def access_token_url(self): <NEW_LINE> <INDENT> return self.api_url('/oauthserver/token/') <NEW_LINE> <DEDENT> def get_user_details(self, response): <NEW_LINE> <INDENT> fullname, first_name, last_name = self.get_user_names( response.get('realName') ) <NEW_LINE> return { 'id': response.get('phid'), 'username': response.get('userName'), 'email': response.get('primaryEmail', ''), 'fullname': fullname, 'first_name': first_name, 'last_name': last_name, } <NEW_LINE> <DEDENT> def user_data(self, access_token, *args, **kwargs): <NEW_LINE> <INDENT> return self.get_json(self.api_url('/api/user.whoami'), params={ 'access_token': access_token, })
Phabricator OAuth authentication backend
6259906c63b5f9789fe8699b
class BodyPart(object): <NEW_LINE> <INDENT> def __init__(self, content, encoding): <NEW_LINE> <INDENT> self.encoding = encoding <NEW_LINE> headers = {} <NEW_LINE> if b'\r\n\r\n' in content: <NEW_LINE> <INDENT> first, self.content = _split_on_find(content, b'\r\n\r\n') <NEW_LINE> if first != b'': <NEW_LINE> <INDENT> headers = _header_parser(first.lstrip(), encoding) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise ImproperBodyPartContentException( 'content does not contain CR-LF-CR-LF' ) <NEW_LINE> <DEDENT> self.headers = CaseInsensitiveDict(headers) <NEW_LINE> <DEDENT> @property <NEW_LINE> def text(self): <NEW_LINE> <INDENT> return self.content.decode(self.encoding)
The ``BodyPart`` object is a ``Response``-like interface to an individual subpart of a multipart response. It is expected that these will generally be created by objects of the ``MultipartDecoder`` class. Like ``Response``, there is a ``CaseInsensitiveDict`` object named headers, ``content`` to access bytes, ``text`` to access unicode, and ``encoding`` to access the unicode codec.
6259906c8e71fb1e983bd300
class TestStringEmpty(unittest.TestCase): <NEW_LINE> <INDENT> def test_is_empty_for_a_valid_string(self): <NEW_LINE> <INDENT> self.assertFalse(utils.is_empty_string('asdfgf')) <NEW_LINE> <DEDENT> def test_is_empty_for_a_blank_string(self): <NEW_LINE> <INDENT> self.assertTrue(utils.is_empty_string('')) <NEW_LINE> <DEDENT> def test_is_empty_for_none(self): <NEW_LINE> <INDENT> self.assertTrue(utils.is_empty_string(None)) <NEW_LINE> <DEDENT> def test_is_empty_for_a_number(self): <NEW_LINE> <INDENT> self.assertFalse(utils.is_empty_string(0))
Unit tests for string functions of utils.py.
6259906c2c8b7c6e89bd501e
class PrivateLinkServiceConnectionState(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'status': {'key': 'status', 'type': 'str'}, 'description': {'key': 'description', 'type': 'str'}, 'actions_required': {'key': 'actionsRequired', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, status: Optional[Union[str, "PrivateEndpointServiceConnectionStatus"]] = None, description: Optional[str] = None, actions_required: Optional[str] = None, **kwargs ): <NEW_LINE> <INDENT> super(PrivateLinkServiceConnectionState, self).__init__(**kwargs) <NEW_LINE> self.status = status <NEW_LINE> self.description = description <NEW_LINE> self.actions_required = actions_required
A collection of information about the state of the connection between service consumer and provider. :ivar status: Indicates whether the connection has been Approved/Rejected/Removed by the owner of the service. Possible values include: "Pending", "Approved", "Rejected". :vartype status: str or ~azure.mgmt.compute.v2020_09_30.models.PrivateEndpointServiceConnectionStatus :ivar description: The reason for approval/rejection of the connection. :vartype description: str :ivar actions_required: A message indicating if changes on the service provider require any updates on the consumer. :vartype actions_required: str
6259906c8a43f66fc4bf39cc
class BaseOption(object): <NEW_LINE> <INDENT> def __init__(self, name, default_value, desc, _help='', tabid=''): <NEW_LINE> <INDENT> self._value = None <NEW_LINE> self.set_value(default_value) <NEW_LINE> self._default_value = self._value <NEW_LINE> self._name = name <NEW_LINE> self._desc = desc <NEW_LINE> self._help = _help <NEW_LINE> self._tabid = tabid <NEW_LINE> <DEDENT> def get_name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> def get_desc(self): <NEW_LINE> <INDENT> return self._desc <NEW_LINE> <DEDENT> def get_default_value(self): <NEW_LINE> <INDENT> return self._default_value <NEW_LINE> <DEDENT> def get_value(self): <NEW_LINE> <INDENT> return self._value <NEW_LINE> <DEDENT> def _get_str(self, value): <NEW_LINE> <INDENT> return str(value) <NEW_LINE> <DEDENT> def get_default_value_str(self): <NEW_LINE> <INDENT> return self._get_str(self.get_default_value()) <NEW_LINE> <DEDENT> def get_value_str(self): <NEW_LINE> <INDENT> return self._get_str(self.get_value()) <NEW_LINE> <DEDENT> def get_value_for_profile(self): <NEW_LINE> <INDENT> return self._get_str(self.get_value()) <NEW_LINE> <DEDENT> def get_type(self): <NEW_LINE> <INDENT> return self._type <NEW_LINE> <DEDENT> def get_help(self): <NEW_LINE> <INDENT> return self._help <NEW_LINE> <DEDENT> def get_tabid(self): <NEW_LINE> <INDENT> return self._tabid <NEW_LINE> <DEDENT> def set_name(self, v): <NEW_LINE> <INDENT> self._name = v <NEW_LINE> <DEDENT> def set_desc(self, v): <NEW_LINE> <INDENT> self._desc = v <NEW_LINE> <DEDENT> def set_default_value(self, v): <NEW_LINE> <INDENT> self._default_value = v <NEW_LINE> <DEDENT> def set_value(self, value): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def validate(self, value): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def set_type(self, v): <NEW_LINE> <INDENT> self._type = v <NEW_LINE> <DEDENT> def set_help(self, v): <NEW_LINE> <INDENT> self._help = v <NEW_LINE> <DEDENT> def set_tabid(self, v): <NEW_LINE> <INDENT> self._tabid = v <NEW_LINE> <DEDENT> def _sanitize(self, value): <NEW_LINE> <INDENT> value = cgi.escape(value) <NEW_LINE> value = value.replace('"', '&quot;') <NEW_LINE> return value <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> fmt = '<option name:%s|type:%s|value:%s>' <NEW_LINE> return fmt % (self._name, self._type, self._value) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, BaseOption): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> name = self._name == other._name <NEW_LINE> _type = self._type == other._type <NEW_LINE> value = self._value == other._value <NEW_LINE> return name and _type and value <NEW_LINE> <DEDENT> def copy(self): <NEW_LINE> <INDENT> return copy.deepcopy(self)
This class represents an option. :author: Andres Riancho ([email protected])
6259906cac7a0e7691f73d20
class XeroUnsupportedMediaType(XeroException): <NEW_LINE> <INDENT> def __init__(self, response): <NEW_LINE> <INDENT> super(XeroUnsupportedMediaType, self).__init__(response, response.text)
HTTP 415: UnsupportedMediaType.
6259906c0c0af96317c5797b
class CompilationError(RuntimeError): <NEW_LINE> <INDENT> def __init__(self, error): <NEW_LINE> <INDENT> super(CompilationError, self).__init__() <NEW_LINE> self.line = error.get("line") <NEW_LINE> self.column = error.get("column") <NEW_LINE> self.message = error.get("message") <NEW_LINE> self.text = error.get("text") <NEW_LINE> self.annotated = error.get("annotated") <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.text
A ``RuntimeError`` subclass for reporting JS compilation errors.
6259906c99fddb7c1ca639ed
class ReplyEmitter(QObject): <NEW_LINE> <INDENT> NRSREPLY = pyqtSignal(object ,object) <NEW_LINE> CancelTEST = pyqtSignal(object ,object) <NEW_LINE> def __init__(self, session, preppedReq , meta = {}): <NEW_LINE> <INDENT> super(QObject, self, ).__init__() <NEW_LINE> self.preppedReq = preppedReq <NEW_LINE> self.session = session <NEW_LINE> metaThread = copy(meta) <NEW_LINE> del meta <NEW_LINE> self.metaThread = metaThread
- this is needed in QRunnable, because QRunnable is NOT able to emit signals. But this is.
6259906ca17c0f6771d5d7c5
class Adapter(object): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.context = None <NEW_LINE> <DEDENT> def set_context(self, context): <NEW_LINE> <INDENT> self.context = context
An abstract superclass for all adapters
6259906c21bff66bcd72449f
class Parser: <NEW_LINE> <INDENT> def __init__(self, path_or_file: Union[str, io.TextIOBase]): <NEW_LINE> <INDENT> self.path: str = None <NEW_LINE> self.data: str = None <NEW_LINE> if isinstance(path_or_file, str): <NEW_LINE> <INDENT> self.path = path_or_file <NEW_LINE> with open(self.path, encoding="utf-8") as fp: <NEW_LINE> <INDENT> self.data: str = fp.read() <NEW_LINE> <DEDENT> <DEDENT> elif isinstance(path_or_file, io.TextIOBase): <NEW_LINE> <INDENT> self.data: str = path_or_file.read() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError("Expected str or TextIO") <NEW_LINE> <DEDENT> self.strings: List[str] = self._extract_strings() <NEW_LINE> <DEDENT> def _extract_strings(self) -> List[str]: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def get_extracted_strings(self): <NEW_LINE> <INDENT> return self.strings <NEW_LINE> <DEDENT> def replace_strings(self, strings: List[str]): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def save(self, path: str=None): <NEW_LINE> <INDENT> output_path = path if path is not None else self.path <NEW_LINE> with open(output_path, "w", encoding="utf-8") as fp: <NEW_LINE> <INDENT> fp.write(self.data) <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return f"<{self.__class__.__name__} path={self.path!r}>"
A base class for extracting and replacing text snippet in files
6259906c091ae3566870646d
class Solution(object): <NEW_LINE> <INDENT> def exist(self, board, word): <NEW_LINE> <INDENT> row, column, n = len(board), len(board[0]), len(word) <NEW_LINE> def dfs(x, y, k): <NEW_LINE> <INDENT> if k == n: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if x < 0 or x >= row or y < 0 or y >= column: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if board[x][y] != word[k]: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> board[x][y] = word[k] * 2 <NEW_LINE> for a, b in [(0, 1), (0, -1), (1, 0), (-1, 0)]: <NEW_LINE> <INDENT> if dfs(x + a, y + b, k + 1): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> board[x][y] = word[k] <NEW_LINE> return False <NEW_LINE> <DEDENT> for i in range(row): <NEW_LINE> <INDENT> for j in range(column): <NEW_LINE> <INDENT> if dfs(i, j, 0): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return False
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。 路径可以从矩阵中的任意一格开始,每一步可以在矩阵中向左、右、上、下移动一格。 如果一条路径经过了矩阵的某一格,那么该路径不能再次进入该格子。 例如,在下面的3×4的矩阵中包含一条字符串“bfce”的路径(路径中的字母用加粗标出)。 [["a","b","c","e"], ["s","f","c","s"], ["a","d","e","e"]] 但矩阵中不包含字符串“abfb”的路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入这个格子。 输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED" 输出:true 输入:board = [["a","b"],["c","d"]], word = "abcd" 输出:false 1 <= board.length <= 200 1 <= board[i].length <= 200 链接:https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof
6259906c6e29344779b01e8e
class Exchange(Base): <NEW_LINE> <INDENT> __tablename__ = "santa_exchanges" <NEW_LINE> name = Column(String(EXCHANGE_NAME_SIZE), primary_key=True) <NEW_LINE> guild_id = Column(BigInteger, nullable=False) <NEW_LINE> owner_id = Column(BigInteger, nullable=False) <NEW_LINE> is_open = Column(Boolean, nullable=False) <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return "<SantaExchange(name='%s', guild_id='%s', owner_id='%s', is_open='%s')>" % ( self.name, self.guild_id, self.owner_id, str(self.is_open))
This is an SQLAlchemy class representing the table containing the exchange data.
6259906c8e7ae83300eea8c9
class DepartmentMajor(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=255) <NEW_LINE> department = models.ForeignKey( "CollegeDepartment", on_delete=models.CASCADE) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return str(self.department) + " " + str(self.name)
Model keeps data about exact departments majors
6259906c1f037a2d8b9e5487
class Level: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(Level, self).__init__() <NEW_LINE> self.structure = [] <NEW_LINE> self.map = map <NEW_LINE> <DEDENT> def generate(self): <NEW_LINE> <INDENT> with open(self.map, "r") as maps: <NEW_LINE> <INDENT> level_structure = [] <NEW_LINE> for line in maps: <NEW_LINE> <INDENT> level_line = [] <NEW_LINE> for sprite in line: <NEW_LINE> <INDENT> if sprite != '\n': <NEW_LINE> <INDENT> level_line.append(sprite) <NEW_LINE> <DEDENT> <DEDENT> level_structure.append(level_line) <NEW_LINE> <DEDENT> self.structure = level_structure <NEW_LINE> <DEDENT> <DEDENT> def display(self, windows): <NEW_LINE> <INDENT> wall = pygame.transform.scale(pygame.image.load( wall_img), (sprite_size, sprite_size)) <NEW_LINE> floor = pygame.transform.scale(pygame.image.load( floor_img), (sprite_size, sprite_size)) <NEW_LINE> line_num = 0 <NEW_LINE> for line in self.structure: <NEW_LINE> <INDENT> case_num = 0 <NEW_LINE> for sprite in line: <NEW_LINE> <INDENT> y = line_num * sprite_size <NEW_LINE> x = case_num * sprite_size <NEW_LINE> if sprite == "X": <NEW_LINE> <INDENT> windows.blit(wall, (x, y)) <NEW_LINE> <DEDENT> if sprite == "0": <NEW_LINE> <INDENT> windows.blit(floor, (x, y)) <NEW_LINE> <DEDENT> case_num += 1 <NEW_LINE> <DEDENT> line_num += 1
Construction of the Maze from a txt file, take 1 arguments the windows where the maze gonna be displayed
6259906c26068e7796d4e173
class LintMessage: <NEW_LINE> <INDENT> def __init__(self, path, line, category, msg_id, symbol, obj, msg, cell=None, data=None): <NEW_LINE> <INDENT> self.path, self.line, self.category = path, int(line), category <NEW_LINE> self.msg_id, self.symbol, self.obj, self.msg = msg_id, symbol, obj, msg <NEW_LINE> self.cell, self.data = cell, data <NEW_LINE> self.enhance_msg() <NEW_LINE> <DEDENT> def enhance_msg(self): <NEW_LINE> <INDENT> map = { "W0702": "Too broad exception clause. You should try catching " "specific exceptions", } <NEW_LINE> self.msg = map.get(self.msg_id, self.msg) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_stdout(cls, stdout, source=None): <NEW_LINE> <INDENT> pattern = r'(\S+):(\d*): (\w*) \((\w*), ([\w-]*), (.*)\) (.*)' <NEW_LINE> objects = [cls(*l) for l in re.findall(pattern, stdout)] <NEW_LINE> for obj in objects: <NEW_LINE> <INDENT> obj.line -= 1 <NEW_LINE> if source: <NEW_LINE> <INDENT> obj.data = source[obj.line] <NEW_LINE> <DEDENT> <DEDENT> return objects <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> if self.cell is not None: <NEW_LINE> <INDENT> return f'cell: {self.cell+1}, line: {self.line+1} - {self.msg}' <NEW_LINE> <DEDENT> return f'line: {self.line+1} - {self.msg}' <NEW_LINE> <DEDENT> def full_str(self, indent=0): <NEW_LINE> <INDENT> p = f'{" "*indent}{self.msg_id}, {self.symbol}, ' + self.__str__() <NEW_LINE> p += '\n' + " "*indent + 'on line: ' + self.data.strip() + '\n' <NEW_LINE> return p
A simple data container for each linting message
6259906c4428ac0f6e659d6c
class NodeDuplicates(ValidationFailure): <NEW_LINE> <INDENT> pass
Duplicate nodes in a D3 JSON file.
6259906c32920d7e50bc7880
class TokenHandler(webapp2.RequestHandler): <NEW_LINE> <INDENT> def get(self): <NEW_LINE> <INDENT> self.response.headers['Content-Type'] = 'text/plain' <NEW_LINE> if not users.is_current_user_admin(): <NEW_LINE> <INDENT> self.response.set_status(401) <NEW_LINE> self.response.out.write('unauthorized') <NEW_LINE> return <NEW_LINE> <DEDENT> user = users.get_current_user() <NEW_LINE> desc = user.email() <NEW_LINE> token = auth.create_auth_token(desc) <NEW_LINE> lines = [ 'save the following to .fileset.json:', '', '{"token": "%s"}' % token, '', ] <NEW_LINE> payload = '\n'.join(lines) <NEW_LINE> self.response.out.write(payload)
Handler that generates an auth token for a user.
6259906c76e4537e8c3f0dbd
class RedisCache(Cache): <NEW_LINE> <INDENT> def __init__(self, host='localhost', port=6379, timeout=None): <NEW_LINE> <INDENT> super(RedisCache, self).__init__() <NEW_LINE> self._redis = StrictRedis(host, port, socket_timeout=timeout, socket_connect_timeout=timeout) <NEW_LINE> <DEDENT> @redis_error_wrapper <NEW_LINE> def get(self, key): <NEW_LINE> <INDENT> return self._redis.get(key) <NEW_LINE> <DEDENT> @redis_error_wrapper <NEW_LINE> def set(self, key, value, expire_seconds=None, only_if_new=False, only_if_old=False): <NEW_LINE> <INDENT> expire_milliseconds = None <NEW_LINE> if expire_seconds is not None: <NEW_LINE> <INDENT> expire_milliseconds = int(expire_seconds * 1000) <NEW_LINE> <DEDENT> return self._redis.set(key, value, None, expire_milliseconds, only_if_new, only_if_old) <NEW_LINE> <DEDENT> @redis_error_wrapper <NEW_LINE> def delete(self, keys): <NEW_LINE> <INDENT> if len(keys) > 0: <NEW_LINE> <INDENT> return self._redis.delete(*keys) <NEW_LINE> <DEDENT> return 0 <NEW_LINE> <DEDENT> @redis_error_wrapper <NEW_LINE> def get_keys(self, pattern='*'): <NEW_LINE> <INDENT> return self._redis.keys(pattern) <NEW_LINE> <DEDENT> @redis_error_wrapper <NEW_LINE> def increase(self, key, amount=1): <NEW_LINE> <INDENT> return self._redis.incr(key, amount) <NEW_LINE> <DEDENT> @redis_error_wrapper <NEW_LINE> def multi_get(self, keys): <NEW_LINE> <INDENT> if len(keys) > 0: <NEW_LINE> <INDENT> return self._redis.mget(keys) <NEW_LINE> <DEDENT> return [] <NEW_LINE> <DEDENT> @redis_error_wrapper <NEW_LINE> def clear(self, pattern='*'): <NEW_LINE> <INDENT> return super(RedisCache, self).clear(pattern)
Implement redis cache
6259906c460517430c432c73
class GlobalTestOpenAcademySession(TransactionCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(GlobalTestOpenAcademySession, self).setUp() <NEW_LINE> self.session = self.env['openacademy.session'] <NEW_LINE> self.partner_absa = self.env.ref('base.res_partner_address_15') <NEW_LINE> self.course = self.env.ref('openacademy.course0') <NEW_LINE> <DEDENT> def test_10_instructor_is_attendee(self): <NEW_LINE> <INDENT> with self.assertRaisesRegexp( ValidationError, "A session's instructor can't be an attendee" ): <NEW_LINE> <INDENT> self.session.create({ 'name': 'Session test 1', 'seats': 1, 'instructor_id': self.partner_absa.id, 'attendee_ids': [(6, 0, [self.partner_absa.id])], 'course_id': self.course.id, })
This create global test to sessions
6259906cd486a94d0ba2d7f9
class ListItemCollection(ClientObjectCollection): <NEW_LINE> <INDENT> pass
List Item collection
6259906c99cbb53fe6832722
class route_card(object): <NEW_LINE> <INDENT> def __init__(self,city1, city2, points, owner=0, completed=False): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> assert city1 in valid_cities, "city 1 is invalid: " + city1 <NEW_LINE> assert city2 in valid_cities, "city 2 is invalid: " + city2 <NEW_LINE> self.city1 = city1 <NEW_LINE> self.city2 = city2 <NEW_LINE> self.points = points <NEW_LINE> self.owner = owner <NEW_LINE> self.completed = completed <NEW_LINE> <DEDENT> except AssertionError as e: <NEW_LINE> <INDENT> print(e) <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "%s, %s, %d" % (self.city1, self.city2, self.points) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "%s, %s, %d" % (self.city1, self.city2, self.points)
class to store all route cards. in the face-up pile, face-down in the deck, or in the discard pile
6259906c3539df3088ecdad9
class SetupError(Exception): <NEW_LINE> <INDENT> pass
Indicates user needs to take action before setup can complete
6259906c4c3428357761baed
class RocketShell(Shell): <NEW_LINE> <INDENT> def __init__(self, start_point, angle, speed, direction, *groups): <NEW_LINE> <INDENT> super(RocketShell, self).__init__(*groups) <NEW_LINE> if direction == 'right': <NEW_LINE> <INDENT> self.image = pygame.image.load('graphics/shellRight.gif') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.image = pygame.image.load('graphics/shellLeft.gif') <NEW_LINE> <DEDENT> self.boom_images = [] <NEW_LINE> for nbr in xrange(1,8,1): <NEW_LINE> <INDENT> self.boom_images.append(pygame.image.load('graphics/explosedSprite.png').subsurface((20*(nbr-1),0,20,20))) <NEW_LINE> <DEDENT> self.explosed = False <NEW_LINE> self.screen = pygame.display.get_surface() <NEW_LINE> self.rect = pygame.rect.Rect(start_point, self.image.get_size()) <NEW_LINE> self.start_point = start_point <NEW_LINE> self.speed_constant = speed <NEW_LINE> self.start_angle = angle <NEW_LINE> self.time_of_birth = 0.0 <NEW_LINE> self.damage_rate = -17 <NEW_LINE> self.direction = direction <NEW_LINE> <DEDENT> def update(self, dt, game): <NEW_LINE> <INDENT> self.time_of_birth += dt <NEW_LINE> x_acc = 1.8 <NEW_LINE> if not self.explosed: <NEW_LINE> <INDENT> if self.direction == 'right': <NEW_LINE> <INDENT> self.rect.x += self.speed_constant* cos(radians(self.start_angle)) + 0.5*x_acc*(self.time_of_birth**2) <NEW_LINE> self.rect.y += sin(radians(-self.start_angle))*self.speed_constant + 0.5*10*(self.time_of_birth**2) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.rect.x -= self.speed_constant* cos(radians(self.start_angle)) * 0.5*x_acc*(self.time_of_birth**2) <NEW_LINE> self.rect.y += sin(radians(-self.start_angle))*self.speed_constant + 0.5*10*(self.time_of_birth**2) <NEW_LINE> <DEDENT> for cell in game.tilemap.layers['triggers'].collide(self.rect, 'blockers'): <NEW_LINE> <INDENT> self.time_of_birth = 0 <NEW_LINE> self.explosed = True <NEW_LINE> <DEDENT> if self.time_of_birth > 0.9: <NEW_LINE> <INDENT> for sp in game.tilemap.layers: <NEW_LINE> <INDENT> if type(sp) == tmx.SpriteLayer and sp.name == "players": <NEW_LINE> <INDENT> for player in sp: <NEW_LINE> <INDENT> if self.rect.top > player.rect.top and self.rect.bottom < player.rect.bottom and self.rect.left > player.rect.left and self.rect.right < player.rect.right: <NEW_LINE> <INDENT> player.updateHealthBy(self.damage_rate) <NEW_LINE> self.time_of_birth = 0 <NEW_LINE> self.explosed = True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.image = self.boom_images[int(self.time_of_birth/0.033)] <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> self.kill()
Класс снаряда типа ракета
6259906ce5267d203ee6cfdb
@util.export <NEW_LINE> class Plugin(plugin.PluginBase): <NEW_LINE> <INDENT> def __init__(self, context): <NEW_LINE> <INDENT> super(Plugin, self).__init__(context=context) <NEW_LINE> <DEDENT> @plugin.event( stage=plugin.Stages.STAGE_INIT, ) <NEW_LINE> def _init(self): <NEW_LINE> <INDENT> self.environment.setdefault( osetupcons.RemoveEnv.REMOVE_DATABASE, None ) <NEW_LINE> self._bkpfile = None <NEW_LINE> <DEDENT> @plugin.event( stage=plugin.Stages.STAGE_CUSTOMIZATION, after=( osetupcons.Stages.REMOVE_CUSTOMIZATION_COMMON, ), ) <NEW_LINE> def _customization(self): <NEW_LINE> <INDENT> if self.environment[ osetupcons.RemoveEnv.REMOVE_ALL ]: <NEW_LINE> <INDENT> self.environment[ osetupcons.RemoveEnv.REMOVE_DATABASE ] = True <NEW_LINE> <DEDENT> if self.environment[ osetupcons.RemoveEnv.REMOVE_DATABASE ] is None: <NEW_LINE> <INDENT> self.environment[ osetupcons.RemoveEnv.REMOVE_DATABASE ] = dialog.queryBoolean( dialog=self.dialog, name='OVESETUP_REMOVE_DATABASE', note=_( 'Do you want to remove Engine DB content? All data will ' 'be lost (@VALUES@) [@DEFAULT@]: ' ), prompt=True, true=_('Yes'), false=_('No'), default=False, ) <NEW_LINE> <DEDENT> <DEDENT> @plugin.event( stage=plugin.Stages.STAGE_MISC, condition=lambda self: ( self.environment[osetupcons.DBEnv.PASSWORD] is not None and self.environment[osetupcons.RemoveEnv.REMOVE_DATABASE] ), after=( osetupcons.Stages.DB_CREDENTIALS_AVAILABLE_LATE, ), ) <NEW_LINE> def _misc(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> dbovirtutils = database.OvirtUtils(plugin=self) <NEW_LINE> dbovirtutils.tryDatabaseConnect() <NEW_LINE> self._bkpfile = dbovirtutils.backup() <NEW_LINE> self.logger.info( _('Clearing database {database}').format( database=self.environment[osetupcons.DBEnv.DATABASE], ) ) <NEW_LINE> dbovirtutils.clearOvirtEngineDatabase() <NEW_LINE> <DEDENT> except RuntimeError as e: <NEW_LINE> <INDENT> self.logger.debug('exception', exc_info=True) <NEW_LINE> self.logger.warning( _( 'Cannot clear database: {error}' ).format( error=e, ) ) <NEW_LINE> <DEDENT> <DEDENT> @plugin.event( stage=plugin.Stages.STAGE_CLOSEUP, condition=lambda self: self._bkpfile is not None, before=( osetupcons.Stages.DIALOG_TITLES_E_SUMMARY, ), after=( osetupcons.Stages.DIALOG_TITLES_S_SUMMARY, ), ) <NEW_LINE> def _closeup(self): <NEW_LINE> <INDENT> self.dialog.note( text=_( 'A backup of the database is available at {path}' ).format( path=self._bkpfile ), )
Clear plugin.
6259906c2c8b7c6e89bd5021
class LabelMixin(object): <NEW_LINE> <INDENT> @declared_attr <NEW_LINE> def labels(self): <NEW_LINE> <INDENT> self.Label = type( '{0:s}Label'.format(self.__name__), (Label, BaseModel,), dict( __tablename__='{0:s}_label'.format(self.__tablename__), parent_id=Column( Integer, ForeignKey('{0:s}.id'.format(self.__tablename__))), parent=relationship(self) ) ) <NEW_LINE> return relationship(self.Label)
A MixIn for generating the necessary tables in the database and to make it accessible from the parent model object (the model object that uses this MixIn, i.e. the object that the label is added to).
6259906c66673b3332c31c38
class NamedTupleCursor(_cursor): <NEW_LINE> <INDENT> Record = None <NEW_LINE> MAX_CACHE = 1024 <NEW_LINE> def execute(self, query, vars=None): <NEW_LINE> <INDENT> self.Record = None <NEW_LINE> return super(NamedTupleCursor, self).execute(query, vars) <NEW_LINE> <DEDENT> def executemany(self, query, vars): <NEW_LINE> <INDENT> self.Record = None <NEW_LINE> return super(NamedTupleCursor, self).executemany(query, vars) <NEW_LINE> <DEDENT> def callproc(self, procname, vars=None): <NEW_LINE> <INDENT> self.Record = None <NEW_LINE> return super(NamedTupleCursor, self).callproc(procname, vars) <NEW_LINE> <DEDENT> def fetchone(self): <NEW_LINE> <INDENT> t = super(NamedTupleCursor, self).fetchone() <NEW_LINE> if t is not None: <NEW_LINE> <INDENT> nt = self.Record <NEW_LINE> if nt is None: <NEW_LINE> <INDENT> nt = self.Record = self._make_nt() <NEW_LINE> <DEDENT> return nt._make(t) <NEW_LINE> <DEDENT> <DEDENT> def fetchmany(self, size=None): <NEW_LINE> <INDENT> ts = super(NamedTupleCursor, self).fetchmany(size) <NEW_LINE> nt = self.Record <NEW_LINE> if nt is None: <NEW_LINE> <INDENT> nt = self.Record = self._make_nt() <NEW_LINE> <DEDENT> return list(map(nt._make, ts)) <NEW_LINE> <DEDENT> def fetchall(self): <NEW_LINE> <INDENT> ts = super(NamedTupleCursor, self).fetchall() <NEW_LINE> nt = self.Record <NEW_LINE> if nt is None: <NEW_LINE> <INDENT> nt = self.Record = self._make_nt() <NEW_LINE> <DEDENT> return list(map(nt._make, ts)) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> it = super(NamedTupleCursor, self).__iter__() <NEW_LINE> t = next(it) <NEW_LINE> nt = self.Record <NEW_LINE> if nt is None: <NEW_LINE> <INDENT> nt = self.Record = self._make_nt() <NEW_LINE> <DEDENT> yield nt._make(t) <NEW_LINE> while True: <NEW_LINE> <INDENT> yield nt._make(next(it)) <NEW_LINE> <DEDENT> <DEDENT> except StopIteration: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> _re_clean = _re.compile( '[' + _re.escape(' !"#$%&\'()*+,-./:;<=>?@[\\]^`{|}~') + ']') <NEW_LINE> def _make_nt(self): <NEW_LINE> <INDENT> key = tuple(d[0] for d in self.description) if self.description else () <NEW_LINE> return self._cached_make_nt(key) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _do_make_nt(cls, key): <NEW_LINE> <INDENT> fields = [] <NEW_LINE> for s in key: <NEW_LINE> <INDENT> s = cls._re_clean.sub('_', s) <NEW_LINE> if s[0] == '_' or '0' <= s[0] <= '9': <NEW_LINE> <INDENT> s = 'f' + s <NEW_LINE> <DEDENT> fields.append(s) <NEW_LINE> <DEDENT> nt = namedtuple("Record", fields) <NEW_LINE> return nt
A cursor that generates results as `~collections.namedtuple`. `!fetch*()` methods will return named tuples instead of regular tuples, so their elements can be accessed both as regular numeric items as well as attributes. >>> nt_cur = conn.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor) >>> rec = nt_cur.fetchone() >>> rec Record(id=1, num=100, data="abc'def") >>> rec[1] 100 >>> rec.data "abc'def"
6259906c63d6d428bbee3ea7
class SuperUserClass(object): <NEW_LINE> <INDENT> def __init__(self, user_id, user_name, password, is_active): <NEW_LINE> <INDENT> self.user_id = user_id <NEW_LINE> self.user_name = user_name <NEW_LINE> self.password = password <NEW_LINE> self.is_active = is_active
管理用户
6259906c21bff66bcd7244a1
class GradesTest(): <NEW_LINE> <INDENT> grades_df = pd.DataFrame( data={'exam1': [43, 81, 78, 75, 89, 70, 91, 65, 98, 87], 'exam2': [24, 63, 56, 56, 67, 51, 79, 46, 72, 60]}, index=['Andre', 'Barry', 'Chris', 'Dan', 'Emilio', 'Fred', 'Greta', 'Humbert', 'Ivan', 'James'] ) <NEW_LINE> def convert_to_letter(self,score): <NEW_LINE> <INDENT> if (score >= 90): <NEW_LINE> <INDENT> return 'A' <NEW_LINE> <DEDENT> elif (score >= 80): <NEW_LINE> <INDENT> return 'B' <NEW_LINE> <DEDENT> elif (score >= 70): <NEW_LINE> <INDENT> return 'C' <NEW_LINE> <DEDENT> elif (score >= 60): <NEW_LINE> <INDENT> return 'D' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 'F' <NEW_LINE> <DEDENT> <DEDENT> def convert_grades(self,grades): <NEW_LINE> <INDENT> return grades.applymap(self.convert_to_letter)
对成绩进行等级的转换
6259906c4f6381625f19a0c5
class PrintGraph(object): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def print_graph(out, graph): <NEW_LINE> <INDENT> justification = defaultdict(lambda: '<') <NEW_LINE> justification['SIZE'] = '>' <NEW_LINE> name_funcs = [ _print.NodeGetters.DMNAME, _print.NodeGetters.DEVNAME, _print.NodeGetters.IDENTIFIER ] <NEW_LINE> line_info = _print.LineInfo( graph, ['NAME', 'DEVTYPE', 'DIFFSTATUS', 'BY-PATH', 'SIZE'], justification, { 'NAME' : name_funcs, 'DEVTYPE': [_print.NodeGetters.DEVTYPE], 'DIFFSTATUS': [_print.NodeGetters.DIFFSTATUS], 'SIZE': [_print.NodeGetters.SIZE], 'BY-PATH': [_print.NodeGetters.BY_PATH] } ) <NEW_LINE> lines = _print.LineArrangements.node_strings_from_graph( _print.LineArrangementsConfig( line_info.info, lambda k, v: str(v), 'NAME' ), graph ) <NEW_LINE> lines = list(_print.XformLines.xform(line_info.keys, lines)) <NEW_LINE> lines = _print.Print.lines( line_info.keys, lines, 2, line_info.alignment ) <NEW_LINE> for line in lines: <NEW_LINE> <INDENT> print(line, end="\n", file=out)
Print a textual representation of the graph.
6259906c76e4537e8c3f0dbe
class NoCaracter(Exception): <NEW_LINE> <INDENT> pass
Excepcion para ningun caracter.
6259906c4a966d76dd5f0725
class ConditionNotMetError(RemoteError): <NEW_LINE> <INDENT> pass
Thrown when a condition is not met.
6259906d1f037a2d8b9e5488
class TemplateTagTestCase(TestCase): <NEW_LINE> <INDENT> tag_library = '', <NEW_LINE> def render_tag(self, tag_name = '', context = {}): <NEW_LINE> <INDENT> template = '{% load ' + self.tag_library + '%}{% ' + tag_name + '%}' <NEW_LINE> t = Template(template) <NEW_LINE> c = Context(context) <NEW_LINE> return t.render(c) <NEW_LINE> <DEDENT> def render_template(self, template_name='', context={}): <NEW_LINE> <INDENT> t = loader.get_template(template_name); <NEW_LINE> c = Context(context) <NEW_LINE> return t.render(c)
Slouží pro testování template tagů. Test se používá porovnáním výstupu z tagu a výstupu z šablony. Pro získání těchto výstupů jsou připraveny metody render_tag a render_template. Při používání metody render_tag je potřeba nastavit vlastnost tag_library ve které musí být název knihovny tagů.
6259906d16aa5153ce401d15
class Prop: <NEW_LINE> <INDENT> def __init__(self, node, offset, name, bytes): <NEW_LINE> <INDENT> self._node = node <NEW_LINE> self._offset = offset <NEW_LINE> self.name = name <NEW_LINE> self.value = None <NEW_LINE> self.bytes = str(bytes) <NEW_LINE> if not bytes: <NEW_LINE> <INDENT> self.type = TYPE_BOOL <NEW_LINE> self.value = True <NEW_LINE> return <NEW_LINE> <DEDENT> self.type, self.value = self.BytesToValue(bytes) <NEW_LINE> <DEDENT> def GetPhandle(self): <NEW_LINE> <INDENT> return fdt_util.fdt32_to_cpu(self.value[:4]) <NEW_LINE> <DEDENT> def Widen(self, newprop): <NEW_LINE> <INDENT> if newprop.type < self.type: <NEW_LINE> <INDENT> self.type = newprop.type <NEW_LINE> <DEDENT> if type(newprop.value) == list and type(self.value) != list: <NEW_LINE> <INDENT> self.value = [self.value] <NEW_LINE> <DEDENT> if type(self.value) == list and len(newprop.value) > len(self.value): <NEW_LINE> <INDENT> val = self.GetEmpty(self.type) <NEW_LINE> while len(self.value) < len(newprop.value): <NEW_LINE> <INDENT> self.value.append(val) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def BytesToValue(self, bytes): <NEW_LINE> <INDENT> bytes = str(bytes) <NEW_LINE> size = len(bytes) <NEW_LINE> strings = bytes.split('\0') <NEW_LINE> is_string = True <NEW_LINE> count = len(strings) - 1 <NEW_LINE> if count > 0 and not strings[-1]: <NEW_LINE> <INDENT> for string in strings[:-1]: <NEW_LINE> <INDENT> if not string: <NEW_LINE> <INDENT> is_string = False <NEW_LINE> break <NEW_LINE> <DEDENT> for ch in string: <NEW_LINE> <INDENT> if ch < ' ' or ch > '~': <NEW_LINE> <INDENT> is_string = False <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> is_string = False <NEW_LINE> <DEDENT> if is_string: <NEW_LINE> <INDENT> if count == 1: <NEW_LINE> <INDENT> return TYPE_STRING, strings[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return TYPE_STRING, strings[:-1] <NEW_LINE> <DEDENT> <DEDENT> if size % 4: <NEW_LINE> <INDENT> if size == 1: <NEW_LINE> <INDENT> return TYPE_BYTE, bytes[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return TYPE_BYTE, list(bytes) <NEW_LINE> <DEDENT> <DEDENT> val = [] <NEW_LINE> for i in range(0, size, 4): <NEW_LINE> <INDENT> val.append(bytes[i:i + 4]) <NEW_LINE> <DEDENT> if size == 4: <NEW_LINE> <INDENT> return TYPE_INT, val[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return TYPE_INT, val <NEW_LINE> <DEDENT> <DEDENT> def GetEmpty(self, type): <NEW_LINE> <INDENT> if type == TYPE_BYTE: <NEW_LINE> <INDENT> return chr(0) <NEW_LINE> <DEDENT> elif type == TYPE_INT: <NEW_LINE> <INDENT> return struct.pack('<I', 0); <NEW_LINE> <DEDENT> elif type == TYPE_STRING: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> def GetOffset(self): <NEW_LINE> <INDENT> return self._node._fdt.GetStructOffset(self._offset)
A device tree property Properties: name: Property name (as per the device tree) value: Property value as a string of bytes, or a list of strings of bytes type: Value type
6259906d283ffb24f3cf50e4
class AssessmentOfferedSearchResults(abc_assessment_searches.AssessmentOfferedSearchResults, osid_searches.OsidSearchResults): <NEW_LINE> <INDENT> def get_assessments_offered(self): <NEW_LINE> <INDENT> raise errors.Unimplemented() <NEW_LINE> <DEDENT> assessments_offered = property(fget=get_assessments_offered) <NEW_LINE> def get_assessment_offered_query_inspector(self): <NEW_LINE> <INDENT> raise errors.Unimplemented() <NEW_LINE> <DEDENT> assessment_offered_query_inspector = property(fget=get_assessment_offered_query_inspector) <NEW_LINE> @utilities.arguments_not_none <NEW_LINE> def get_assessment_offered_search_results_record(self, assessment_offered_search_record_type): <NEW_LINE> <INDENT> raise errors.Unimplemented()
This interface provides a means to capture results of a search.
6259906d2ae34c7f260ac924
class EntrepreneurEmployee(Employee): <NEW_LINE> <INDENT> def __init__(self, name: str, rate: float): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.rate = rate <NEW_LINE> self.social_tax = 704 <NEW_LINE> <DEDENT> def get_name(self) -> str: <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def get_salary(self) -> float: <NEW_LINE> <INDENT> return 20.8 * 8 * 1.1 * self.rate <NEW_LINE> <DEDENT> def get_physical_tax(self) -> float: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> def get_military_tax(self) -> float: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> def get_united_tax(self) -> float: <NEW_LINE> <INDENT> return self.get_salary() * 0.05 <NEW_LINE> <DEDENT> def get_social_tax(self) -> float: <NEW_LINE> <INDENT> return self.social_tax
Calculate different taxes for Entrepreneur
6259906d92d797404e389779
class MetaCollectArgs( MetaListConstructor ): <NEW_LINE> <INDENT> def __call__( self, *args, **kwargs ): <NEW_LINE> <INDENT> argspec = inspect.getargspec( self.__init__ ) <NEW_LINE> argdict = collections.OrderedDict() <NEW_LINE> for i, arg_value in enumerate( args ): <NEW_LINE> <INDENT> key, value = argspec.args[i+1], arg_value <NEW_LINE> argdict[ key ] = value <NEW_LINE> <DEDENT> num_kwargs = len( argspec.args ) - len( args ) - 1 <NEW_LINE> if argspec.defaults and num_kwargs: <NEW_LINE> <INDENT> for i, arg_name in enumerate( argspec.args[-num_kwargs:] ): <NEW_LINE> <INDENT> key, value = arg_name, argspec.defaults[ i ] <NEW_LINE> if arg_name in kwargs: <NEW_LINE> <INDENT> value = kwargs[ arg_name ] <NEW_LINE> <DEDENT> argdict[ key ] = value <NEW_LINE> <DEDENT> <DEDENT> inst = super( MetaCollectArgs, self ).__call__( *args, **kwargs ) <NEW_LINE> inst._args = argdict <NEW_LINE> return inst
Metaclass which collects and stores the argument names and values used in the construction of a class instance. This metaclass subclasses MetaListConstructor so we can chain together Metaclass functionality.
6259906d4428ac0f6e659d6f
class Features(base.ECMCommand): <NEW_LINE> <INDENT> name = 'features' <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> self.add_subcommand(List, default=True) <NEW_LINE> self.add_subcommand(Delete) <NEW_LINE> self.add_subcommand(Routers) <NEW_LINE> self.add_subcommand(AddRouter) <NEW_LINE> self.add_subcommand(RemoveRouter)
View and edit features (bindings). For features that have router bindings or other settings those can be managed with these commands too.
6259906de5267d203ee6cfdc
class Connection(object): <NEW_LINE> <INDENT> def __init__(self, sock, addr, server): <NEW_LINE> <INDENT> self._sock = sock <NEW_LINE> self._addr = addr <NEW_LINE> self.server = server <NEW_LINE> self.logger = logging.getLogger(LoggerName) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> if len(self._addr) == 2: <NEW_LINE> <INDENT> self.logger.debug('Connection starting up (%s:%d)', self._addr[0], self._addr[1]) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.processInput() <NEW_LINE> <DEDENT> except (EOFError, KeyboardInterrupt): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> except ProtocolError as e: <NEW_LINE> <INDENT> self.logger.error("Protocol error '%s'", str(e)) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> self.logger.exception('Exception caught in Connection') <NEW_LINE> <DEDENT> if len(self._addr) == 2: <NEW_LINE> <INDENT> self.logger.debug('Connection shutting down (%s:%d)', self._addr[0], self._addr[1]) <NEW_LINE> <DEDENT> self._sock.close() <NEW_LINE> <DEDENT> def processInput(self): <NEW_LINE> <INDENT> headers = readNetstring(self._sock) <NEW_LINE> headers = headers.split('\x00')[:-1] <NEW_LINE> if len(headers) % 2 != 0: <NEW_LINE> <INDENT> raise ProtocolError('invalid headers') <NEW_LINE> <DEDENT> environ = {} <NEW_LINE> for i in range(len(headers) / 2): <NEW_LINE> <INDENT> environ[headers[2*i]] = headers[2*i+1] <NEW_LINE> <DEDENT> clen = environ.get('CONTENT_LENGTH') <NEW_LINE> if clen is None: <NEW_LINE> <INDENT> raise ProtocolError('missing CONTENT_LENGTH') <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> clen = int(clen) <NEW_LINE> if clen < 0: <NEW_LINE> <INDENT> raise ValueError <NEW_LINE> <DEDENT> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise ProtocolError('invalid CONTENT_LENGTH') <NEW_LINE> <DEDENT> self._sock.setblocking(1) <NEW_LINE> if clen: <NEW_LINE> <INDENT> input = self._sock.makefile('r') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> input = StringIO.StringIO() <NEW_LINE> <DEDENT> output = self._sock.makefile('w') <NEW_LINE> req = Request(self, environ, input, output) <NEW_LINE> req.run() <NEW_LINE> output.close() <NEW_LINE> input.close()
Represents a single client (web server) connection. A single request is handled, after which the socket is closed.
6259906d5fcc89381b266d75
class ApiOperation(Resource): <NEW_LINE> <INDENT> _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'properties': {'key': 'properties', 'type': 'ApiOperationPropertiesDefinition'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(ApiOperation, self).__init__(**kwargs) <NEW_LINE> self.properties = kwargs.get('properties', None)
The api operation. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The resource id. :vartype id: str :ivar name: Gets the resource name. :vartype name: str :ivar type: Gets the resource type. :vartype type: str :param location: The resource location. :type location: str :param tags: A set of tags. The resource tags. :type tags: dict[str, str] :param properties: The api operations properties. :type properties: ~azure.mgmt.logic.models.ApiOperationPropertiesDefinition
6259906d99fddb7c1ca639ef
class MoogLowAliasNonLinearOversampled(MoogLowAliasNonLinear): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(MoogLowAliasNonLinearOversampled, self).__init__() <NEW_LINE> <DEDENT> def ProcessSample(self, sample): <NEW_LINE> <INDENT> a = super(MoogLowAliasNonLinearOversampled, self).ProcessSample(sample) <NEW_LINE> b = super(MoogLowAliasNonLinearOversampled, self).ProcessSample(sample) <NEW_LINE> return b <NEW_LINE> <DEDENT> def Process4Samples(self, vector): <NEW_LINE> <INDENT> new_vec_first = numpy.array((vector[0], vector[0], vector[1], vector[1])) <NEW_LINE> new_vec_second = numpy.array((vector[2], vector[2], vector[3], vector[3])) <NEW_LINE> first_half = super(MoogLowAliasNonLinearOversampled, self).Process4Samples(new_vec_first) <NEW_LINE> second_half = super(MoogLowAliasNonLinearOversampled, self).Process4Samples(new_vec_second) <NEW_LINE> return filters_common.Decimate(first_half, second_half)
Implements a naive oversampling of the low alias, non-linear Moog filter
6259906d63d6d428bbee3ea8
class PasswordResetToken(db.Model): <NEW_LINE> <INDENT> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> user_id = db.Column(db.Integer, db.ForeignKey('user.id')) <NEW_LINE> user = db.relationship('User', backref=db.backref('reset_tokens', lazy='dynamic')) <NEW_LINE> token = db.Column(db.String) <NEW_LINE> def __init__(self, user_id, token): <NEW_LINE> <INDENT> self.user_id = user_id <NEW_LINE> self.token = token <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<Password reset token for user ID %s>" % self.user_id
Stores tokens used to authenticate users for a password reset.
6259906da17c0f6771d5d7c7
class ScreenControl(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.screen_list = [] <NEW_LINE> self.current_index = 0 <NEW_LINE> <DEDENT> def show(self): <NEW_LINE> <INDENT> while self.current_index >= 0: <NEW_LINE> <INDENT> if self.current_index < len(self.screen_list): <NEW_LINE> <INDENT> self.current_index = self.screen_list[self.current_index].show() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def add_screen(self, screen, loop_hook_function=None): <NEW_LINE> <INDENT> self.screen_list.append(screen) <NEW_LINE> added_index = len(self.screen_list) - 1 <NEW_LINE> if loop_hook_function is not None: <NEW_LINE> <INDENT> self.screen_list[added_index].loop_hook = loop_hook_function
Manages screens of type Screen. Handles screen switching, clicking and swiping and mpd status updating. :ivar screen_list: List containing all screen objects. :ivar current_index: Points to current screen in screen_list. :ivar mouse_down_pos: Mouse position on mouse down.
6259906d21bff66bcd7244a3
class Services: <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> dictionary = kwargs.get('dictionary') or dict() <NEW_LINE> self.database = Database( dictionary=dictionary.get('database') ) <NEW_LINE> self.channel_layer = ChannelLayer( dictionary=dictionary.get('channelLayer') ) <NEW_LINE> self.session_store = SessionStore( dictionary=dictionary.get('sessionStore') ) <NEW_LINE> self.communication_store = CommunicationStore( dictionary=dictionary.get('communicationStore') ) <NEW_LINE> self.verification_store = VerificationStore( dictionary=dictionary.get('verificationStore') ) <NEW_LINE> self.application_store = ApplicationStore( dictionary=dictionary.get('applicationStore') ) <NEW_LINE> self.cache = Cache( dictionary=dictionary.get('cache') ) <NEW_LINE> self.message_broker = MessageBroker( dictionary=dictionary.get('messageBroker') )
This class stores the Service objects for all the services involved
6259906d7047854f46340bf3
class PrintInvoice(Wizard): <NEW_LINE> <INDENT> __name__ = 'account.invoice.print' <NEW_LINE> start = StateTransition() <NEW_LINE> warning = StateView('account.invoice.print.warning', 'account_invoice.print_warning_view_form', [ Button('Cancel', 'end', 'tryton-cancel'), Button('Print', 'print_', 'tryton-print', default=True), ]) <NEW_LINE> print_ = StateAction('account_invoice.report_invoice') <NEW_LINE> def transition_start(self): <NEW_LINE> <INDENT> if len(Transaction().context['active_ids']) > 1: <NEW_LINE> <INDENT> return 'warning' <NEW_LINE> <DEDENT> return 'print_' <NEW_LINE> <DEDENT> def do_print_(self, action): <NEW_LINE> <INDENT> data = {} <NEW_LINE> data['id'] = Transaction().context['active_ids'].pop() <NEW_LINE> data['ids'] = [data['id']] <NEW_LINE> return action, data <NEW_LINE> <DEDENT> def transition_print_(self): <NEW_LINE> <INDENT> if Transaction().context['active_ids']: <NEW_LINE> <INDENT> return 'print_' <NEW_LINE> <DEDENT> return 'end'
Print Invoice Report
6259906d796e427e5384ffb4
class UsersConfig(AppConfig): <NEW_LINE> <INDENT> name = 'users' <NEW_LINE> varbose_name = 'Users'
User app config.
6259906d6e29344779b01e92
class MagentoAPILazyObject(LazyObject): <NEW_LINE> <INDENT> def __init__(self, func, *args, **kwargs): <NEW_LINE> <INDENT> self.__dict__['_setupfunc'] = func <NEW_LINE> self.__dict__['_args'] = args <NEW_LINE> self.__dict__['_kwargs'] = kwargs <NEW_LINE> if 'api_endpoint' in vars(func): <NEW_LINE> <INDENT> kwargs['api_endpoint'] = func.api_endpoint <NEW_LINE> <DEDENT> super(MagentoAPILazyObject, self).__init__() <NEW_LINE> <DEDENT> def __getattr__(self, name): <NEW_LINE> <INDENT> wrapped = self._wrapped <NEW_LINE> kwargs = self._kwargs <NEW_LINE> if wrapped is empty: <NEW_LINE> <INDENT> if name in kwargs: <NEW_LINE> <INDENT> return kwargs[name] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._setup() <NEW_LINE> <DEDENT> <DEDENT> return getattr(self._wrapped, name) <NEW_LINE> <DEDENT> def _setup(self): <NEW_LINE> <INDENT> endpoint = self._setupfunc.api_endpoint <NEW_LINE> data = api_call(endpoint, *self._args) <NEW_LINE> self._wrapped = self._setupfunc.fromAPIResponse(data)
This is SORT of like SimpleLazyObject, in that it takes a func, but it's not nearly as extensive
6259906d0a50d4780f7069df
class Mail(Plugin): <NEW_LINE> <INDENT> pass
Mail/File transfer-related commands.
6259906d1f037a2d8b9e5489
class HireFireTestHandler(tornado.web.RequestHandler): <NEW_LINE> <INDENT> def test(self): <NEW_LINE> <INDENT> self.write('HireFire Handler Found!') <NEW_LINE> self.finish() <NEW_LINE> <DEDENT> def get(self): <NEW_LINE> <INDENT> self.test() <NEW_LINE> <DEDENT> def post(self): <NEW_LINE> <INDENT> self.test()
RequestHandler that implements the test response.
6259906d7d847024c075dc1a
class SignalDispatcher(QObject): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def getDispatcher(): <NEW_LINE> <INDENT> return __SIGNAL_DISPATCHER__ <NEW_LINE> <DEDENT> def __init__(self): <NEW_LINE> <INDENT> super(SignalDispatcher, self).__init__() <NEW_LINE> self.__dispatcher__ = None <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def broadcastSignal(signal, *params): <NEW_LINE> <INDENT> __SIGNAL_DISPATCHER__.emitSignal(signal, *params) <NEW_LINE> <DEDENT> def emitSignal(self, signal, *params): <NEW_LINE> <INDENT> if len(params) > 0: <NEW_LINE> <INDENT> self.__dispatcher__.emit(signal, *params) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.__dispatcher__.emit(signal) <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def addSignalSubscriber(subscriber, signal, slot): <NEW_LINE> <INDENT> __SIGNAL_DISPATCHER__.signalSubscriber(subscriber, signal, slot) <NEW_LINE> <DEDENT> def mainDispatcher(self, _dispatcher): <NEW_LINE> <INDENT> self.__dispatcher__ = _dispatcher <NEW_LINE> <DEDENT> def removeSubscriber(self, subscriber): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def signalSubscriber(self, subscriber, signal, slot): <NEW_LINE> <INDENT> subscriber.connect(self.__dispatcher__, signal, slot) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def setMainDispatcher(_dispatcher): <NEW_LINE> <INDENT> __SIGNAL_DISPATCHER__.mainDispatcher(_dispatcher)
tool class - dispatcher for custom signals, subscribers have to register themselves for specified signal, if a signal is emitted all subscribers all notify
6259906d5fdd1c0f98e5f7c3
class ProfileFeedItemSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = models.ProfileFeedItem <NEW_LINE> fields = ('id','user_profile', 'status_text', 'created_on') <NEW_LINE> extra_kwargs = {'user_profile': {'read_only': True}}
Serializer for profile feed items
6259906de76e3b2f99fda23f
class DishesClassify(models.Model): <NEW_LINE> <INDENT> name = models.CharField('类别名称', max_length=64, db_index=True) <NEW_LINE> description = models.CharField('类别描述', max_length=256, null=True, blank=True) <NEW_LINE> user_id = models.IntegerField('用户ID') <NEW_LINE> status = models.IntegerField('数据状态', default=1) <NEW_LINE> created = models.DateTimeField('创建时间', default=now) <NEW_LINE> updated = models.DateTimeField('更新时间', auto_now=True) <NEW_LINE> objects = BaseManager() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> db_table = 'ys_dishes_classify' <NEW_LINE> unique_together = ('user_id', 'name', 'status') <NEW_LINE> ordering = ('name',) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_object(cls, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return cls.objects.get(**kwargs) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> return e <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def filter_objects(cls, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return cls.objects.filter(**kwargs) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> return e
菜品分类信息表
6259906dfff4ab517ebcf059
class _LiveLoggingStreamHandler(logging.StreamHandler): <NEW_LINE> <INDENT> def __init__(self, terminal_reporter, capture_manager): <NEW_LINE> <INDENT> logging.StreamHandler.__init__(self, stream=terminal_reporter) <NEW_LINE> self.capture_manager = capture_manager <NEW_LINE> self.reset() <NEW_LINE> self.set_when(None) <NEW_LINE> self._test_outcome_written = False <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self._first_record_emitted = False <NEW_LINE> <DEDENT> def set_when(self, when): <NEW_LINE> <INDENT> self._when = when <NEW_LINE> self._section_name_shown = False <NEW_LINE> if when == "start": <NEW_LINE> <INDENT> self._test_outcome_written = False <NEW_LINE> <DEDENT> <DEDENT> def emit(self, record): <NEW_LINE> <INDENT> ctx_manager = ( self.capture_manager.global_and_fixture_disabled() if self.capture_manager else nullcontext() ) <NEW_LINE> with ctx_manager: <NEW_LINE> <INDENT> if not self._first_record_emitted: <NEW_LINE> <INDENT> self.stream.write("\n") <NEW_LINE> self._first_record_emitted = True <NEW_LINE> <DEDENT> elif self._when in ("teardown", "finish"): <NEW_LINE> <INDENT> if not self._test_outcome_written: <NEW_LINE> <INDENT> self._test_outcome_written = True <NEW_LINE> self.stream.write("\n") <NEW_LINE> <DEDENT> <DEDENT> if not self._section_name_shown and self._when: <NEW_LINE> <INDENT> self.stream.section("live log " + self._when, sep="-", bold=True) <NEW_LINE> self._section_name_shown = True <NEW_LINE> <DEDENT> logging.StreamHandler.emit(self, record)
Custom StreamHandler used by the live logging feature: it will write a newline before the first log message in each test. During live logging we must also explicitly disable stdout/stderr capturing otherwise it will get captured and won't appear in the terminal.
6259906d2c8b7c6e89bd5025
class alloc_val(_Alloc): <NEW_LINE> <INDENT> name = 'Currency value' <NEW_LINE> parameters = OrderedDict([ ('rule', _Param.std_rule), ('val', dict(_Param.std_flt, **{'doc': 'Currency value that is allocated to each trade', 'verbose': 'Trade size (currency value)', 'range': (5000., 10000000.), 'default': 10000., 'format': '${:3.2f}', })), ]) <NEW_LINE> def description(self): <NEW_LINE> <INDENT> return 'Allocate {} to each entry.'.format(self.repr('val')) <NEW_LINE> <DEDENT> def size(self, entry_signal, date, **kwargs): <NEW_LINE> <INDENT> return self.val // entry_signal.stock.price.close[date]
Allocate a fixed currency value.
6259906d3346ee7daa33827d
class MediaRootS3BotoStorage(S3BotoStorage): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> kwargs['location'] = 'media' <NEW_LINE> super(MediaRootS3BotoStorage, self).__init__(*args, **kwargs)
Storage for uploaded media files.
6259906d379a373c97d9a85e
class CNNModel(): <NEW_LINE> <INDENT> def __init__(self, config, input_op, mode): <NEW_LINE> <INDENT> assert mode in ["training", "validation", "inference"] <NEW_LINE> self.config = config <NEW_LINE> self.inputs = input_op <NEW_LINE> self.mode = mode <NEW_LINE> self.is_training = self.mode == "training" <NEW_LINE> self.reuse = self.mode == "validation" <NEW_LINE> <DEDENT> def build_model(self, input_layer): <NEW_LINE> <INDENT> with tf.variable_scope("cnn_model", reuse=self.reuse, initializer=self.config['initializer']): <NEW_LINE> <INDENT> x = tf.layers.conv2d( inputs=input_layer, filters=self.config['cnn_filters'][0], kernel_size=[3, 3], padding="same") <NEW_LINE> x = tf.nn.relu(x) <NEW_LINE> x = tf.layers.max_pooling2d(inputs=x, pool_size=[2, 2], strides=2, padding='same') <NEW_LINE> x = tf.layers.conv2d( inputs=x, filters=self.config['cnn_filters'][1], kernel_size=[5, 5], padding="same") <NEW_LINE> x = tf.nn.relu(x) <NEW_LINE> x = tf.layers.max_pooling2d(inputs=x, pool_size=[2, 2], strides=2, padding='same') <NEW_LINE> x = tf.layers.conv2d( inputs=x, filters=self.config['cnn_filters'][2], kernel_size=[3, 3], padding="same") <NEW_LINE> x = tf.nn.relu(x) <NEW_LINE> x = tf.layers.max_pooling2d(inputs=x, pool_size=[2, 2], strides=2, padding='same') <NEW_LINE> x = tf.layers.conv2d( inputs=x, filters=self.config['cnn_filters'][3], kernel_size=[3, 3], padding="same") <NEW_LINE> x = tf.nn.relu(x) <NEW_LINE> x = tf.layers.max_pooling2d(inputs=x, pool_size=[2, 2], strides=2, padding='same') <NEW_LINE> conv_flat = tf.reshape(x, [-1, 5 * 5 * self.config['cnn_filters'][3]]) <NEW_LINE> dropout = tf.layers.dropout(inputs=conv_flat, rate=self.config['dropout_rate'], training=self.is_training) <NEW_LINE> dense = tf.layers.dense(inputs=dropout, units=self.config['num_hidden_units'], activation=tf.nn.relu) <NEW_LINE> dropout = tf.layers.dropout(inputs=dense, rate=self.config['dropout_rate'], training=self.is_training) <NEW_LINE> self.cnn_model = dropout <NEW_LINE> return dropout <NEW_LINE> <DEDENT> <DEDENT> def build_graph(self): <NEW_LINE> <INDENT> if self.is_training: <NEW_LINE> <INDENT> self.reuse = False <NEW_LINE> self.build_model(self.inputs[0]) <NEW_LINE> self.reuse = True <NEW_LINE> <DEDENT> self.cnn_representations = tf.map_fn(lambda x: self.build_model(x), elems=self.inputs, dtype=tf.float32, back_prop=True, swap_memory=True, parallel_iterations=2) <NEW_LINE> return self.cnn_representations
Creates training and validation computational graphs. Note that tf.variable_scope enables sharing the parameters so that both graphs share the parameters.
6259906d5fcc89381b266d76
class BusinessCardParser(): <NEW_LINE> <INDENT> def getContactInfo(self, document): <NEW_LINE> <INDENT> return ContactInfo(document)
Reads text on a business card.
6259906da17c0f6771d5d7c8
class ChoiceField(ChoiceFieldBase): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = "Choice field" <NEW_LINE> <DEDENT> form_field_class = forms.ChoiceField <NEW_LINE> def get_choices(self): <NEW_LINE> <INDENT> choices = super().get_choices() <NEW_LINE> choices.insert(0, ('', '---------')) <NEW_LINE> return choices
Model for a choice field, i.e. a field that allows the user to select from a set of pre-defined choices.
6259906d627d3e7fe0e086c7
class FoldersRequest(object): <NEW_LINE> <INDENT> swagger_types = { 'envelope_ids': 'list[str]', 'folders': 'list[Folder]', 'from_folder_id': 'str' } <NEW_LINE> attribute_map = { 'envelope_ids': 'envelopeIds', 'folders': 'folders', 'from_folder_id': 'fromFolderId' } <NEW_LINE> def __init__(self, _configuration=None, **kwargs): <NEW_LINE> <INDENT> if _configuration is None: <NEW_LINE> <INDENT> _configuration = Configuration() <NEW_LINE> <DEDENT> self._configuration = _configuration <NEW_LINE> self._envelope_ids = None <NEW_LINE> self._folders = None <NEW_LINE> self._from_folder_id = None <NEW_LINE> self.discriminator = None <NEW_LINE> setattr(self, "_{}".format('envelope_ids'), kwargs.get('envelope_ids', None)) <NEW_LINE> setattr(self, "_{}".format('folders'), kwargs.get('folders', None)) <NEW_LINE> setattr(self, "_{}".format('from_folder_id'), kwargs.get('from_folder_id', None)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def envelope_ids(self): <NEW_LINE> <INDENT> return self._envelope_ids <NEW_LINE> <DEDENT> @envelope_ids.setter <NEW_LINE> def envelope_ids(self, envelope_ids): <NEW_LINE> <INDENT> self._envelope_ids = envelope_ids <NEW_LINE> <DEDENT> @property <NEW_LINE> def folders(self): <NEW_LINE> <INDENT> return self._folders <NEW_LINE> <DEDENT> @folders.setter <NEW_LINE> def folders(self, folders): <NEW_LINE> <INDENT> self._folders = folders <NEW_LINE> <DEDENT> @property <NEW_LINE> def from_folder_id(self): <NEW_LINE> <INDENT> return self._from_folder_id <NEW_LINE> <DEDENT> @from_folder_id.setter <NEW_LINE> def from_folder_id(self, from_folder_id): <NEW_LINE> <INDENT> self._from_folder_id = from_folder_id <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> if issubclass(FoldersRequest, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, FoldersRequest): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.to_dict() == other.to_dict() <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, FoldersRequest): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.to_dict() != other.to_dict()
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
6259906d97e22403b383c74c
class JsonStr(fields.Field): <NEW_LINE> <INDENT> def _serialize(self, value, attr, obj): <NEW_LINE> <INDENT> if value in ["", "null", None]: <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> value = json.loads(value) <NEW_LINE> <DEDENT> except json.JSONDecodeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> value = {} <NEW_LINE> <DEDENT> return value <NEW_LINE> <DEDENT> def _deserialize(self, value, attr, data): <NEW_LINE> <INDENT> if value in ["null", None]: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> value = json.dumps(value, ensure_ascii=False) <NEW_LINE> <DEDENT> except json.JSONDecodeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return value
自定义Json字符串字段类 使用Schema.load方法时, 会调用_deserialize方法, 将dict(json)转换为model类 使用Schema.dump方法时, 会调用_serialize方法, 将符合格式的Json字符串转换为Dict
6259906dcc0a2c111447c6f0
class MercatorCatalogIndexes(AdhocracyCatalogIndexes): <NEW_LINE> <INDENT> mercator_location = Keyword() <NEW_LINE> mercator_requested_funding = Keyword() <NEW_LINE> mercator_budget = Keyword()
Mercator indexes for the adhocracy catalog.
6259906da8370b77170f1c06
class BytesIteratorIO(io.BytesIO): <NEW_LINE> <INDENT> def __init__(self, iterator): <NEW_LINE> <INDENT> self._iter = iterator <NEW_LINE> self._left = b'' <NEW_LINE> <DEDENT> def readable(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def _read1(self, n=None): <NEW_LINE> <INDENT> while not self._left: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._left = next(self._iter) <NEW_LINE> <DEDENT> except StopIteration: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._left = force_bytes(self._left) <NEW_LINE> <DEDENT> <DEDENT> ret = self._left[:n] <NEW_LINE> self._left = self._left[len(ret):] <NEW_LINE> return ret <NEW_LINE> <DEDENT> def read(self, n=None): <NEW_LINE> <INDENT> l = [] <NEW_LINE> if n is None or n < 0: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> m = self._read1() <NEW_LINE> if not m: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> l.append(m) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> while n > 0: <NEW_LINE> <INDENT> m = self._read1(n) <NEW_LINE> if not m: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> n -= len(m) <NEW_LINE> l.append(m) <NEW_LINE> <DEDENT> <DEDENT> return b''.join(l) <NEW_LINE> <DEDENT> def readline(self): <NEW_LINE> <INDENT> l = [] <NEW_LINE> while True: <NEW_LINE> <INDENT> i = self._left.find(b'\n') <NEW_LINE> if i == -1: <NEW_LINE> <INDENT> l.append(self._left) <NEW_LINE> try: <NEW_LINE> <INDENT> self._left = next(self._iter) <NEW_LINE> <DEDENT> except StopIteration: <NEW_LINE> <INDENT> self._left = b'' <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> l.append(self._left[:i + 1]) <NEW_LINE> self._left = self._left[i + 1:] <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> return b''.join(l)
A dynamically generated BytesIO-like object. Original code by Matt Joiner <[email protected]> from: * http://stackoverflow.com/questions/12593576/ * https://gist.github.com/anacrolix/3788413
6259906d1b99ca4002290155
class _MockStore(): <NEW_LINE> <INDENT> def commit(self): <NEW_LINE> <INDENT> pass
A mock store class
6259906d1f037a2d8b9e548a
@DATASETS.register_module() <NEW_LINE> class RepeatDataset(object): <NEW_LINE> <INDENT> def __init__(self, dataset, times): <NEW_LINE> <INDENT> self.dataset = dataset <NEW_LINE> self.times = times <NEW_LINE> self.CLASSES = dataset.CLASSES <NEW_LINE> if hasattr(self.dataset, 'flag'): <NEW_LINE> <INDENT> self.flag = np.tile(self.dataset.flag, times) <NEW_LINE> <DEDENT> self._ori_len = len(self.dataset) <NEW_LINE> <DEDENT> def __getitem__(self, idx): <NEW_LINE> <INDENT> return self.dataset[idx % self._ori_len] <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return self.times * self._ori_len
A wrapper of repeated dataset. The length of repeated dataset will be `times` larger than the original dataset. This is useful when the data loading time is long but the dataset is small. Using RepeatDataset can reduce the data loading time between epochs. Args: dataset (:obj:`Dataset`): The dataset to be repeated. times (int): Repeat times.
6259906d56ac1b37e6303902
class NoVersionChannelImport(NoLearningActivitiesChannelImport): <NEW_LINE> <INDENT> schema_mapping = { ContentNode: { "per_row": { "channel_id": "infer_channel_id_from_source", "tree_id": "available_tree_id", "available": "get_none", "license_name": "get_license_name", "license_description": "get_license_description", }, "post": ["set_learning_activities_from_kind"], }, File: { "per_row": { File._meta.get_field("local_file").attname: "checksum", "available": "get_none", } }, LocalFile: { "per_table": "generate_local_file_from_file", "per_row": { "id": "checksum", "extension": "extension", "file_size": "file_size", "available": "get_none", }, }, ChannelMetadata: { "per_row": { ChannelMetadata._meta.get_field( "min_schema_version" ).attname: "set_version_to_no_version", "root_id": "root_pk", } }, } <NEW_LINE> licenses = {} <NEW_LINE> def infer_channel_id_from_source(self, source_object): <NEW_LINE> <INDENT> return self.channel_id <NEW_LINE> <DEDENT> def generate_local_file_from_file(self, SourceTable): <NEW_LINE> <INDENT> SourceTable = self.source.get_table(File) <NEW_LINE> checksum_record = set() <NEW_LINE> for record in self.source.execute(select([SourceTable])).fetchall(): <NEW_LINE> <INDENT> if record.checksum not in checksum_record: <NEW_LINE> <INDENT> checksum_record.add(record.checksum) <NEW_LINE> yield record <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def set_version_to_no_version(self, source_object): <NEW_LINE> <INDENT> return NO_VERSION <NEW_LINE> <DEDENT> def get_license(self, SourceTable): <NEW_LINE> <INDENT> license_id = SourceTable.license_id <NEW_LINE> if not license_id: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if license_id not in self.licenses: <NEW_LINE> <INDENT> LicenseTable = self.source.get_table(License) <NEW_LINE> license = self.source.execute( select([LicenseTable]).where(LicenseTable.c.id == license_id) ).fetchone() <NEW_LINE> self.licenses[license_id] = license <NEW_LINE> <DEDENT> return self.licenses[license_id] <NEW_LINE> <DEDENT> def get_license_name(self, SourceTable): <NEW_LINE> <INDENT> license = self.get_license(SourceTable) <NEW_LINE> if not license: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return license.license_name <NEW_LINE> <DEDENT> def get_license_description(self, SourceTable): <NEW_LINE> <INDENT> license = self.get_license(SourceTable) <NEW_LINE> if not license: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return license.license_description
Class defining the schema mapping for importing old content databases (i.e. ones produced before the ChannelImport machinery was implemented). The schema mapping below defines how to bring in information from the old version of the Kolibri content databases into the database for the current version of Kolibri.
6259906d5fc7496912d48e88
class NumberConverter(BaseConverter): <NEW_LINE> <INDENT> def __init__(self, fixed_digits=0, min=None, max=None): <NEW_LINE> <INDENT> self.fixed_digits = fixed_digits <NEW_LINE> self.min = min <NEW_LINE> self.max = max <NEW_LINE> <DEDENT> def to_python(self, value): <NEW_LINE> <INDENT> if (self.fixed_digits and len(value) != self.fixed_digits): <NEW_LINE> <INDENT> raise Http404() <NEW_LINE> <DEDENT> value = self.num_convert(value) <NEW_LINE> if (self.min is not None and value < self.min) or (self.max is not None and value > self.max): <NEW_LINE> <INDENT> raise Http404() <NEW_LINE> <DEDENT> return value <NEW_LINE> <DEDENT> def to_url(self, value): <NEW_LINE> <INDENT> if (self.fixed_digits and len(str(value)) > self.fixed_digits): <NEW_LINE> <INDENT> raise ValueError() <NEW_LINE> <DEDENT> value = self.num_convert(value) <NEW_LINE> if (self.min is not None and value < self.min) or (self.max is not None and value > self.max): <NEW_LINE> <INDENT> raise ValueError() <NEW_LINE> <DEDENT> if self.fixed_digits: <NEW_LINE> <INDENT> value = ('%%0%sd' % self.fixed_digits) % value <NEW_LINE> <DEDENT> return str(value)
Baseclass for `IntegerConverter` and `FloatConverter`. :internal:
6259906d2c8b7c6e89bd5026
@unique <NEW_LINE> class HubProperty(IntEnum): <NEW_LINE> <INDENT> NAME = 0x01 <NEW_LINE> BUTTON = 0x02 <NEW_LINE> FW_VERSION = 0x03 <NEW_LINE> HW_VERSION = 0x04 <NEW_LINE> RSSI = 0x05 <NEW_LINE> BATTERY_VOLTAGE = 0x06 <NEW_LINE> BATTERY_KIND = 0x07 <NEW_LINE> MFG_NAME = 0x08 <NEW_LINE> RADIO_FW_VERSION = 0x09 <NEW_LINE> LWP_VERSION = 0x0A <NEW_LINE> HUB_KIND = 0x0B <NEW_LINE> HW_NET_ID = 0x0C <NEW_LINE> BDADDR = 0x0D <NEW_LINE> BOOTLOADER_BDADDR = 0x0E <NEW_LINE> HW_NET_FAMILY = 0x0F <NEW_LINE> VOLUME = 0x12
Properties used in :attr:`MessageKind.HUB_PROPERTY` messages.
6259906d2ae34c7f260ac929
class MusicaPorLetra(Resource): <NEW_LINE> <INDENT> def get(self, artista, letra_inicial): <NEW_LINE> <INDENT> artista = remover_acentos_char_especiais(artista) <NEW_LINE> if not vagalume.request(artista, ''): <NEW_LINE> <INDENT> sys.exit(2) <NEW_LINE> <DEDENT> top_musicas, alfabet_musicas = vagalume.search(artista) <NEW_LINE> musica_por_letra = [] <NEW_LINE> [musica_por_letra.append(mus) for mus in alfabet_musicas if mus.startswith(letra_inicial.upper())] <NEW_LINE> return {f'Musicas com a letra {letra_inicial}': musica_por_letra}
Recurso para listar as músicas de um artista baseado na primeira letra do título da música
6259906d99fddb7c1ca639f1
class ResourceApi(_compat.with_metaclass(ResourceApiMeta)): <NEW_LINE> <INDENT> api_name = None <NEW_LINE> resource = None <NEW_LINE> path_prefix = UrlPath() <NEW_LINE> tags = None <NEW_LINE> parent = None <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> if not self.api_name: <NEW_LINE> <INDENT> self.api_name = getmeta(self.resource).name.lower() <NEW_LINE> <DEDENT> self.path_prefix += self.api_name <NEW_LINE> <DEDENT> def op_paths(self, path_base): <NEW_LINE> <INDENT> path_base += self.path_prefix <NEW_LINE> for operation in self._operations: <NEW_LINE> <INDENT> for op_path in operation.op_paths(path_base): <NEW_LINE> <INDENT> yield op_path
Base framework specific ResourceAPI implementations.
6259906df548e778e596cdcd
class XmrSerializeBaseTest(aiounittest.AsyncTestCase): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(XmrSerializeBaseTest, self).__init__(*args, **kwargs) <NEW_LINE> <DEDENT> async def test_varint(self): <NEW_LINE> <INDENT> test_nums = [0, 1, 12, 44, 32, 63, 64, 127, 128, 255, 256, 1023, 1024, 8191, 8192, 2**16, 2**16 - 1, 2**32, 2**32 - 1, 2**64, 2**64 - 1, 2**72 - 1, 2**112] <NEW_LINE> for test_num in test_nums: <NEW_LINE> <INDENT> writer = x.MemoryReaderWriter() <NEW_LINE> await x.dump_uvarint(writer, test_num) <NEW_LINE> test_deser = await x.load_uvarint(x.MemoryReaderWriter(writer.get_buffer())) <NEW_LINE> self.assertEqual(test_num, test_deser)
Simple tests
6259906d4f6381625f19a0c8
class FullNeighborSampler(NeighborSampler): <NEW_LINE> <INDENT> def get(self, ids): <NEW_LINE> <INDENT> if len(self._meta_path) != len(self._expand_factor): <NEW_LINE> <INDENT> raise ValueError("The length of meta_path must be same with hop count.") <NEW_LINE> <DEDENT> ids = np.array(ids).flatten() <NEW_LINE> src_ids = ids <NEW_LINE> current_batch_size = ids.size <NEW_LINE> layers = Layers() <NEW_LINE> for i in range(len(self._meta_path)): <NEW_LINE> <INDENT> req = self._make_req(i, src_ids) <NEW_LINE> res = pywrap.new_sampling_response() <NEW_LINE> status = self._client.sample_neighbor(req, res) <NEW_LINE> if status.ok(): <NEW_LINE> <INDENT> src_degrees = pywrap.get_sampling_node_degrees(res) <NEW_LINE> dense_shape = (current_batch_size, max(src_degrees)) <NEW_LINE> nbr_ids = pywrap.get_sampling_node_ids(res) <NEW_LINE> edge_ids = pywrap.get_sampling_edge_ids(res) <NEW_LINE> <DEDENT> pywrap.del_op_response(res) <NEW_LINE> pywrap.del_op_request(req) <NEW_LINE> errors.raise_exception_on_not_ok_status(status) <NEW_LINE> dst_type = self._dst_types[i] <NEW_LINE> layer_nodes = self._graph.get_nodes( dst_type, nbr_ids, offsets=src_degrees, shape=dense_shape) <NEW_LINE> ids = np.concatenate([src_ids[idx].repeat(d) for idx, d in enumerate(src_degrees)]) <NEW_LINE> nbr_ids_flat = nbr_ids.flatten() <NEW_LINE> layer_edges = self._graph.get_edges( self._meta_path[i], ids, nbr_ids_flat, offsets=src_degrees, shape=dense_shape) <NEW_LINE> layer_edges.edge_ids = edge_ids <NEW_LINE> layers.append_layer(Layer(layer_nodes, layer_edges)) <NEW_LINE> current_batch_size = nbr_ids_flat.size <NEW_LINE> src_ids = nbr_ids <NEW_LINE> <DEDENT> return layers
Get all the neighbors of given node ids. The result is made up of SparseNodes and SparseEdges.
6259906d7c178a314d78e80c
class FigureCanvas(FigureCanvasQTAgg): <NEW_LINE> <INDENT> def __init__(self, map_, parent=None): <NEW_LINE> <INDENT> self.parent = parent <NEW_LINE> self.map = map_ <NEW_LINE> self.figure = Figure() <NEW_LINE> self.map.plot(figure=self.figure) <NEW_LINE> self.axes = self.figure.gca() <NEW_LINE> if self.map.norm() is not None: <NEW_LINE> <INDENT> self.vmin = self.map.norm().vmin <NEW_LINE> self.vmax = self.map.norm().vmax <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.vmin = self.map.min() <NEW_LINE> self.vmax = self.map.max() <NEW_LINE> <DEDENT> self.scaling = "Linear" <NEW_LINE> self.params = { "cmap": self.map.cmap, "norm": self.map.norm(), } <NEW_LINE> FigureCanvasQTAgg.__init__(self, self.figure) <NEW_LINE> FigureCanvasQTAgg.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding) <NEW_LINE> FigureCanvasQTAgg.updateGeometry(self) <NEW_LINE> <DEDENT> def get_cmap(self, cmapname, gamma=None): <NEW_LINE> <INDENT> mpl_cmaps = sorted(m for m in matplotlib.pyplot.cm.datad if not m.endswith("_r")) <NEW_LINE> if cmapname in mpl_cmaps: <NEW_LINE> <INDENT> return matplotlib.cm.get_cmap(cmapname) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return sunpy.cm.get_cmap(cmapname) <NEW_LINE> <DEDENT> <DEDENT> def get_norm(self): <NEW_LINE> <INDENT> if self.vmin < self.vmax: <NEW_LINE> <INDENT> if self.scaling == "Linear": <NEW_LINE> <INDENT> return matplotlib.colors.Normalize(vmin=self.vmin, vmax=self.vmax) <NEW_LINE> <DEDENT> elif self.scaling == "Logarithmic": <NEW_LINE> <INDENT> if self.vmin <= 0: <NEW_LINE> <INDENT> self.window().colorErrorLabel.setText("Cannot log scale zero or negative data!") <NEW_LINE> return self.params["norm"] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return matplotlib.colors.LogNorm(vmin=self.vmin, vmax=self.vmax) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.window().colorErrorLabel.setText("Min clip value must not exceed max clip value!") <NEW_LINE> return self.params["norm"] <NEW_LINE> <DEDENT> <DEDENT> def update_figure(self, cmapname=None, vmin=None, vmax=None, scaling=None): <NEW_LINE> <INDENT> self.figure.clear() <NEW_LINE> self.window().colorErrorLabel.clear() <NEW_LINE> if cmapname is not None: <NEW_LINE> <INDENT> self.params.update({"cmap": self.get_cmap(cmapname)}) <NEW_LINE> <DEDENT> elif vmax is not None: <NEW_LINE> <INDENT> self.vmax = vmax <NEW_LINE> self.params.update({"norm": self.get_norm()}) <NEW_LINE> <DEDENT> elif vmin is not None: <NEW_LINE> <INDENT> self.vmin = vmin <NEW_LINE> self.params.update({"norm": self.get_norm()}) <NEW_LINE> <DEDENT> elif scaling is not None: <NEW_LINE> <INDENT> self.scaling = scaling <NEW_LINE> self.params.update({"norm": self.get_norm()}) <NEW_LINE> <DEDENT> self.map.plot(figure=self.figure, **self.params) <NEW_LINE> self.axes = self.figure.gca() <NEW_LINE> self.resize_figure() <NEW_LINE> <DEDENT> def reset_figure(self): <NEW_LINE> <INDENT> self.figure = Figure() <NEW_LINE> self.map.plot(figure=self.figure) <NEW_LINE> self.axes = self.figure.gca() <NEW_LINE> self.resize_figure() <NEW_LINE> self.window().initialize_color_options() <NEW_LINE> <DEDENT> def resize_figure(self): <NEW_LINE> <INDENT> self.updateGeometry() <NEW_LINE> self.resize(1, 1) <NEW_LINE> self.draw() <NEW_LINE> <DEDENT> @property <NEW_LINE> def cmap(self): <NEW_LINE> <INDENT> return self.params["cmap"] <NEW_LINE> <DEDENT> @property <NEW_LINE> def norm(self): <NEW_LINE> <INDENT> return self.params["norm"]
General plot widget, resizes to fit window
6259906d627d3e7fe0e086c9
class PilotoPublicForm(ModelForm): <NEW_LINE> <INDENT> _model_class = Piloto <NEW_LINE> _include = [Piloto.categoria, Piloto.nome, Piloto.equipe]
Form used to show properties on app's home
6259906dcc0a2c111447c6f1
class ComponentTopology(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.name=None <NEW_LINE> self.domain_name=None <NEW_LINE> self.fasta_file=None <NEW_LINE> self.fasta_id=None <NEW_LINE> self.pdb_file=None <NEW_LINE> self.chain=None <NEW_LINE> self.residue_range=None <NEW_LINE> self.pdb_offset=None <NEW_LINE> self.bead_size=None <NEW_LINE> self.em_residues_per_gaussian=None <NEW_LINE> self.gmm_file=None <NEW_LINE> self.mrc_file=None <NEW_LINE> self.color=None <NEW_LINE> self.rmf_file_name=None <NEW_LINE> self.rmf_frame_number=None <NEW_LINE> <DEDENT> def recompute_default_dirs(self, topology): <NEW_LINE> <INDENT> pdb_filename=self.pdb_file.split("/")[-1] <NEW_LINE> self.pdb_filename=IMP.base.get_relative_path(topology.topology_file, topology.defaults)
Topology class stores the components required to build a standard IMP hierarchy using IMP.pmi.autobuild_model()
6259906d56ac1b37e6303903
class FiniteDimensionalHighestWeightCrystal_TypeE6(FiniteDimensionalHighestWeightCrystal_TypeE): <NEW_LINE> <INDENT> def __init__(self, dominant_weight): <NEW_LINE> <INDENT> B1 = CrystalOfLetters(['E',6]) <NEW_LINE> B6 = CrystalOfLetters(['E',6], dual = True) <NEW_LINE> self.column_crystal = {1 : B1, 6 : B6, 4 : TensorProductOfCrystals(B1,B1,B1,generators=[[B1([-3,4]),B1([-1,3]),B1([1])]]), 3 : TensorProductOfCrystals(B1,B1,generators=[[B1([-1,3]),B1([1])]]), 5 : TensorProductOfCrystals(B6,B6,generators=[[B6([5,-6]),B6([6])]]), 2 : TensorProductOfCrystals(B6,B1,generators=[[B6([2,-1]),B1([1])]])} <NEW_LINE> FiniteDimensionalHighestWeightCrystal_TypeE.__init__(self, dominant_weight)
Class of finite dimensional highest weight crystals of type `E_6`. EXAMPLES:: sage: C=CartanType(['E',6]) sage: La=C.root_system().weight_lattice().fundamental_weights() sage: T = HighestWeightCrystal(La[2]); T Finite dimensional highest weight crystal of type ['E', 6] and highest weight Lambda[2] sage: B1 = T.column_crystal[1]; B1 The crystal of letters for type ['E', 6] sage: B6 = T.column_crystal[6]; B6 The crystal of letters for type ['E', 6] (dual) sage: t = T(B6([-1]),B1([-1,3])); t [[-1], [-1, 3]] sage: [t.epsilon(i) for i in T.index_set()] [2, 0, 0, 0, 0, 0] sage: [t.phi(i) for i in T.index_set()] [0, 0, 1, 0, 0, 0] sage: TestSuite(t).run()
6259906d4e4d562566373c48
class Stack: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._values = [] <NEW_LINE> return <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> string_value = "" <NEW_LINE> for i in range(len(self._values)): <NEW_LINE> <INDENT> string_value = string_value + (", NYI" * i) <NEW_LINE> <DEDENT> return string_value <NEW_LINE> <DEDENT> def push(self, value): <NEW_LINE> <INDENT> self._values.append(deepcopy(value)) <NEW_LINE> return <NEW_LINE> <DEDENT> def pop(self): <NEW_LINE> <INDENT> top_value = self._values.pop() <NEW_LINE> return top_value <NEW_LINE> <DEDENT> def peek(self): <NEW_LINE> <INDENT> top_value = self._values.pop() <NEW_LINE> self.push(top_value) <NEW_LINE> return top_value <NEW_LINE> <DEDENT> def is_empty(self): <NEW_LINE> <INDENT> if len(self._values) == 0: <NEW_LINE> <INDENT> result = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result = False <NEW_LINE> <DEDENT> return result
Use s = Stack() to initialize the Stack.
6259906d67a9b606de5476c3
class UnknownValidatorError(Exception): <NEW_LINE> <INDENT> pass
Raised when we find an attribute type that we don't know how to validate.
6259906d283ffb24f3cf50ea
class _DoublyLinkedBase: <NEW_LINE> <INDENT> class _Node: <NEW_LINE> <INDENT> __slots__ = '_element', '_prev', '_next' <NEW_LINE> def __init__(self, element, prev, next_element): <NEW_LINE> <INDENT> self._element = element <NEW_LINE> self._prev = prev <NEW_LINE> self._next = next_element <NEW_LINE> <DEDENT> <DEDENT> def __init__(self): <NEW_LINE> <INDENT> self._header = self._Node(None, None, None) <NEW_LINE> self._trailer = self._Node(None, None, None) <NEW_LINE> self._header._next = self._trailer <NEW_LINE> self._trailer._prev = self._header <NEW_LINE> self._size = 0 <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return self._size <NEW_LINE> <DEDENT> def is_empty(self): <NEW_LINE> <INDENT> return self._size == 0 <NEW_LINE> <DEDENT> def _insert_between(self, elem, predecessor, successor): <NEW_LINE> <INDENT> newest = self._Node(elem, predecessor, successor) <NEW_LINE> predecessor._next = newest <NEW_LINE> successor._prev = newest <NEW_LINE> self._size += 1 <NEW_LINE> return newest <NEW_LINE> <DEDENT> def _delete_node(self, node): <NEW_LINE> <INDENT> predecessor = node._prev <NEW_LINE> successor = node._next <NEW_LINE> predecessor._next = successor <NEW_LINE> successor._prev = predecessor <NEW_LINE> self._size -= 1 <NEW_LINE> element = node._element <NEW_LINE> node._prev = node._next = node._element = None <NEW_LINE> return element
A base class providing a doubly linked list representation.
6259906de76e3b2f99fda243
class SchemeDictionaryDestination(WheelDestination): <NEW_LINE> <INDENT> def __init__( self, scheme_dict, interpreter, script_kind, hash_algorithm="sha256", ): <NEW_LINE> <INDENT> self.scheme_dict = scheme_dict <NEW_LINE> self.interpreter = interpreter <NEW_LINE> self.script_kind = script_kind <NEW_LINE> self.hash_algorithm = hash_algorithm <NEW_LINE> <DEDENT> def write_to_fs(self, scheme, path, stream): <NEW_LINE> <INDENT> target_path = os.path.join(self.scheme_dict[scheme], path) <NEW_LINE> if os.path.exists(target_path): <NEW_LINE> <INDENT> message = "File already exists: {}".format(target_path) <NEW_LINE> raise FileExistsError(message) <NEW_LINE> <DEDENT> parent_folder = os.path.dirname(target_path) <NEW_LINE> if not os.path.exists(parent_folder): <NEW_LINE> <INDENT> os.makedirs(parent_folder) <NEW_LINE> <DEDENT> with open(target_path, "wb") as f: <NEW_LINE> <INDENT> hash_, size = copyfileobj_with_hashing(stream, f, self.hash_algorithm) <NEW_LINE> <DEDENT> return RecordEntry(path, Hash(self.hash_algorithm, hash_), size) <NEW_LINE> <DEDENT> def write_file(self, scheme, path, stream): <NEW_LINE> <INDENT> if scheme == "scripts": <NEW_LINE> <INDENT> with fix_shebang(stream, self.interpreter) as stream_with_different_shebang: <NEW_LINE> <INDENT> return self.write_to_fs(scheme, path, stream_with_different_shebang) <NEW_LINE> <DEDENT> <DEDENT> return self.write_to_fs(scheme, path, stream) <NEW_LINE> <DEDENT> def write_script(self, name, module, attr, section): <NEW_LINE> <INDENT> script = Script(name, module, attr, section) <NEW_LINE> script_name, data = script.generate(self.interpreter, self.script_kind) <NEW_LINE> with io.BytesIO(data) as stream: <NEW_LINE> <INDENT> return self.write_to_fs(Scheme("scripts"), script_name, stream) <NEW_LINE> <DEDENT> <DEDENT> def finalize_installation(self, scheme, record_file_path, records): <NEW_LINE> <INDENT> with construct_record_file(records) as record_stream: <NEW_LINE> <INDENT> self.write_to_fs(scheme, record_file_path, record_stream)
Destination, based on a mapping of {scheme: file-system-path}.
6259906d442bda511e95d979
class PhenoWLParser(object): <NEW_LINE> <INDENT> def __init__(self, grammar = None): <NEW_LINE> <INDENT> self.grammar = grammar if grammar else PhenoWLGrammar() <NEW_LINE> self.tokens = ParseResults() <NEW_LINE> self.err = [] <NEW_LINE> <DEDENT> def error(self, *args): <NEW_LINE> <INDENT> self.err.append("{0}".format(', '.join(map(str, args)))) <NEW_LINE> <DEDENT> def parse(self, text): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.tokens = self.grammar.program.ignore(pythonStyleComment).parseString(text, parseAll=True) <NEW_LINE> return self.tokens <NEW_LINE> <DEDENT> except ParseException as err: <NEW_LINE> <INDENT> print(err) <NEW_LINE> self.error(err) <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> print(err) <NEW_LINE> self.error(err) <NEW_LINE> <DEDENT> <DEDENT> def parse_subgrammar(self, subgrammer, text): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.tokens = subgrammer.ignore(pythonStyleComment).parseString(text, parseAll=True) <NEW_LINE> return self.tokens <NEW_LINE> <DEDENT> except ParseException as err: <NEW_LINE> <INDENT> print(err) <NEW_LINE> self.error(err) <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> print(err) <NEW_LINE> self.error(err) <NEW_LINE> <DEDENT> <DEDENT> def parse_file(self, filename): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.tokens = self.grammar.program.ignore(pythonStyleComment).parseFile(filename, parseAll=True) <NEW_LINE> return self.tokens <NEW_LINE> <DEDENT> except ParseException as err: <NEW_LINE> <INDENT> print(err) <NEW_LINE> exit(3) <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> print(err) <NEW_LINE> self.error(err)
The parser for PhenoWL DSL.
6259906d01c39578d7f14356
class LoginForm(Form): <NEW_LINE> <INDENT> username = StringField('Username', validators=[DataRequired()]) <NEW_LINE> password = PasswordField('Password', validators=[DataRequired()]) <NEW_LINE> remember_me = BooleanField('Keep me logged in')
Login form with username, password and remember me fields
6259906d8a43f66fc4bf39d6
class JSMiddleware(object): <NEW_LINE> <INDENT> def click_button_repeat(self, driver, button_css, delay): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> logging.info("Has tried to find button") <NEW_LINE> next = driver.find_element_by_css_selector(button_css) <NEW_LINE> logging.info("Has found button") <NEW_LINE> next.click() <NEW_LINE> logging.info("Has clicked") <NEW_LINE> time.sleep(delay) <NEW_LINE> logging.info("Has slept") <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def process_request(self, request, spider): <NEW_LINE> <INDENT> logging.info('JS Middleware started!') <NEW_LINE> dcap = dict(DesiredCapabilities.PHANTOMJS) <NEW_LINE> dcap["phantomjs.page.settings.userAgent"] = ( "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/53 " "(KHTML, like Gecko) Chrome/15.0.87") <NEW_LINE> driver = webdriver.PhantomJS(executable_path='/usr/local/bin/phantomjs-2.1.1-linux-x86_64/bin/phantomjs',desired_capabilities=dcap) <NEW_LINE> driver.get(request.url) <NEW_LINE> self.click_button_repeat(driver, '.ecm_showMoreLink', 7) <NEW_LINE> self.click_button_repeat(driver,'.ecm_commentShowMore',7) <NEW_LINE> body = driver.page_source <NEW_LINE> current_url = driver.current_url <NEW_LINE> driver.close() <NEW_LINE> return HtmlResponse(current_url, body=body, encoding='utf-8', request=request)
Middleware that deals with javascript loading on braunkohle-sites
6259906de5267d203ee6cfdf
@six.add_metaclass(ABCMeta) <NEW_LINE> class BinaryGalpropModel(object): <NEW_LINE> <INDENT> def __init__(self, prim_haloprop_key = model_defaults.default_binary_galprop_haloprop, **kwargs): <NEW_LINE> <INDENT> required_kwargs = ['galprop_name'] <NEW_LINE> model_helpers.bind_required_kwargs(required_kwargs, self, **kwargs) <NEW_LINE> self.prim_haloprop_key = prim_haloprop_key <NEW_LINE> if 'sec_haloprop_key' in kwargs.keys(): <NEW_LINE> <INDENT> self.sec_haloprop_key = kwargs['sec_haloprop_key'] <NEW_LINE> <DEDENT> if 'new_haloprop_func_dict' in kwargs.keys(): <NEW_LINE> <INDENT> self.new_haloprop_func_dict = kwargs['new_haloprop_func_dict'] <NEW_LINE> <DEDENT> required_method_name = 'mean_'+self.galprop_name+'_fraction' <NEW_LINE> if not hasattr(self, required_method_name): <NEW_LINE> <INDENT> raise HalotoolsError("Any sub-class of BinaryGalpropModel must " "implement a method named %s " % required_method_name) <NEW_LINE> <DEDENT> setattr(self, 'mc_'+self.galprop_name, self._mc_galprop) <NEW_LINE> self._mock_generation_calling_sequence = ['mc_'+self.galprop_name] <NEW_LINE> self._methods_to_inherit = ( ['mean_'+self.galprop_name+'_fraction', 'mc_'+self.galprop_name]) <NEW_LINE> self._galprop_dtypes_to_allocate = np.dtype([(self.galprop_name, bool)]) <NEW_LINE> <DEDENT> def _mc_galprop(self, seed=None, **kwargs): <NEW_LINE> <INDENT> np.random.seed(seed=seed) <NEW_LINE> mean_func = getattr(self, 'mean_'+self.galprop_name+'_fraction') <NEW_LINE> mean_galprop_fraction = mean_func(**kwargs) <NEW_LINE> mc_generator = np.random.random(custom_len(mean_galprop_fraction)) <NEW_LINE> result = np.where(mc_generator < mean_galprop_fraction, True, False) <NEW_LINE> if 'table' in kwargs: <NEW_LINE> <INDENT> kwargs['table'][self.galprop_name] = result <NEW_LINE> <DEDENT> return result
Container class for any component model of a binary-valued galaxy property.
6259906d5fcc89381b266d78
class AvalonMM(BusDriver): <NEW_LINE> <INDENT> _signals = ["address"] <NEW_LINE> _optional_signals = ["readdata", "read", "write", "waitrequest", "writedata", "readdatavalid", "byteenable", "cs"] <NEW_LINE> def __init__(self, entity, name, clock): <NEW_LINE> <INDENT> BusDriver.__init__(self, entity, name, clock) <NEW_LINE> self._can_read = False <NEW_LINE> self._can_write = False <NEW_LINE> if hasattr(self.bus, "read"): <NEW_LINE> <INDENT> self.bus.read.setimmediatevalue(0) <NEW_LINE> self._can_read = True <NEW_LINE> <DEDENT> if hasattr(self.bus, "write"): <NEW_LINE> <INDENT> self.bus.write.setimmediatevalue(0) <NEW_LINE> v = self.bus.writedata.value <NEW_LINE> v.binstr = "x" * len(self.bus.writedata) <NEW_LINE> self.bus.writedata <= v <NEW_LINE> self._can_write = True <NEW_LINE> <DEDENT> if hasattr(self.bus, "byteenable"): <NEW_LINE> <INDENT> self.bus.byteenable.setimmediatevalue(0) <NEW_LINE> <DEDENT> if hasattr(self.bus, "cs"): <NEW_LINE> <INDENT> self.bus.cs.setimmediatevalue(0) <NEW_LINE> <DEDENT> v = self.bus.address.value <NEW_LINE> v.binstr = "x" * len(self.bus.address) <NEW_LINE> self.bus.address.setimmediatevalue(v) <NEW_LINE> <DEDENT> def read(self, address): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def write(self, address, value): <NEW_LINE> <INDENT> pass
Avalon-MM Driver Currently we only support the mode required to communicate with SF avalon_mapper which is a limited subset of all the signals Blocking operation is all that is supported at the moment, and for the near future as well Posted responses from a slave are not supported.
6259906df548e778e596cdcf
class IntersphinxRoleResolver(ReferencesResolver): <NEW_LINE> <INDENT> default_priority = ReferencesResolver.default_priority - 1 <NEW_LINE> def run(self, **kwargs: Any) -> None: <NEW_LINE> <INDENT> for node in self.document.traverse(pending_xref): <NEW_LINE> <INDENT> if 'intersphinx' not in node: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> contnode = cast(nodes.TextElement, node[0].deepcopy()) <NEW_LINE> inv_name = node['inventory'] <NEW_LINE> if inv_name is not None: <NEW_LINE> <INDENT> assert inventory_exists(self.env, inv_name) <NEW_LINE> newnode = resolve_reference_in_inventory(self.env, inv_name, node, contnode) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> newnode = resolve_reference_any_inventory(self.env, False, node, contnode) <NEW_LINE> <DEDENT> if newnode is None: <NEW_LINE> <INDENT> typ = node['reftype'] <NEW_LINE> msg = (__('external %s:%s reference target not found: %s') % (node['refdomain'], typ, node['reftarget'])) <NEW_LINE> logger.warning(msg, location=node, type='ref', subtype=typ) <NEW_LINE> node.replace_self(contnode) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> node.replace_self(newnode)
pending_xref node resolver for intersphinx role. This resolves pending_xref nodes generated by :intersphinx:***: role.
6259906d435de62698e9d648
class Lxc(Deployment): <NEW_LINE> <INDENT> compatibility = 1 <NEW_LINE> name = 'lxc' <NEW_LINE> def __init__(self, parent, parameters): <NEW_LINE> <INDENT> super(Lxc, self).__init__(parent) <NEW_LINE> self.action = LxcAction() <NEW_LINE> self.action.section = self.action_type <NEW_LINE> self.action.job = self.job <NEW_LINE> parent.add_action(self.action, parameters) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def accepts(cls, device, parameters): <NEW_LINE> <INDENT> if 'to' not in parameters: <NEW_LINE> <INDENT> return False, '"to" is not in deploy parameters' <NEW_LINE> <DEDENT> if 'os' not in parameters: <NEW_LINE> <INDENT> return False, '"os" is not in deploy parameters' <NEW_LINE> <DEDENT> if parameters['to'] != 'lxc': <NEW_LINE> <INDENT> return False, '"to" parameter is not "lxc"' <NEW_LINE> <DEDENT> if 'lxc' in device['actions']['deploy']['methods']: <NEW_LINE> <INDENT> return True, 'accepted' <NEW_LINE> <DEDENT> return False, '"lxc" was not in the device configuration deploy methods'
Strategy class for a lxc deployment. Downloads the relevant parts, copies to the locations using lxc.
6259906d091ae35668706477
class Record(object): <NEW_LINE> <INDENT> def __init__(self, type=FCGI_UNKNOWN_TYPE, requestId=FCGI_NULL_REQUEST_ID): <NEW_LINE> <INDENT> self.version = FCGI_VERSION_1 <NEW_LINE> self.type = type <NEW_LINE> self.requestId = requestId <NEW_LINE> self.contentLength = 0 <NEW_LINE> self.paddingLength = 0 <NEW_LINE> self.contentData = '' <NEW_LINE> <DEDENT> def _recvall(sock, length): <NEW_LINE> <INDENT> dataList = [] <NEW_LINE> recvLen = 0 <NEW_LINE> while length: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> data = sock.recv(length) <NEW_LINE> <DEDENT> except socket.error as e: <NEW_LINE> <INDENT> if e[0] == errno.EAGAIN: <NEW_LINE> <INDENT> select.select([sock], [], []) <NEW_LINE> continue <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> <DEDENT> if not data: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> dataList.append(data) <NEW_LINE> dataLen = len(data) <NEW_LINE> recvLen += dataLen <NEW_LINE> length -= dataLen <NEW_LINE> <DEDENT> return b''.join(dataList), recvLen <NEW_LINE> <DEDENT> _recvall = staticmethod(_recvall) <NEW_LINE> def read(self, sock): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> header, length = self._recvall(sock, FCGI_HEADER_LEN) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise EOFError <NEW_LINE> <DEDENT> if length < FCGI_HEADER_LEN: <NEW_LINE> <INDENT> raise EOFError <NEW_LINE> <DEDENT> self.version, self.type, self.requestId, self.contentLength, self.paddingLength = struct.unpack(FCGI_Header, header) <NEW_LINE> if __debug__: _debug(9, 'read: fd = %d, type = %d, requestId = %d, ' 'contentLength = %d' % (sock.fileno(), self.type, self.requestId, self.contentLength)) <NEW_LINE> if self.contentLength: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.contentData, length = self._recvall(sock, self.contentLength) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise EOFError <NEW_LINE> <DEDENT> if length < self.contentLength: <NEW_LINE> <INDENT> raise EOFError <NEW_LINE> <DEDENT> <DEDENT> if self.paddingLength: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._recvall(sock, self.paddingLength) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise EOFError <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _sendall(sock, data): <NEW_LINE> <INDENT> length = len(data) <NEW_LINE> while length: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> sent = sock.send(data) <NEW_LINE> <DEDENT> except socket.error as e: <NEW_LINE> <INDENT> if e[0] == errno.EAGAIN: <NEW_LINE> <INDENT> select.select([], [sock], []) <NEW_LINE> continue <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> <DEDENT> data = data[sent:] <NEW_LINE> length -= sent <NEW_LINE> <DEDENT> <DEDENT> _sendall = staticmethod(_sendall) <NEW_LINE> def write(self, sock): <NEW_LINE> <INDENT> self.paddingLength = -self.contentLength & 7 <NEW_LINE> if __debug__: _debug(9, 'write: fd = %d, type = %d, requestId = %d, ' 'contentLength = %d' % (sock.fileno(), self.type, self.requestId, self.contentLength)) <NEW_LINE> header = struct.pack(FCGI_Header, self.version, self.type, self.requestId, self.contentLength, self.paddingLength) <NEW_LINE> self._sendall(sock, header) <NEW_LINE> if self.contentLength: <NEW_LINE> <INDENT> self._sendall(sock, self.contentData) <NEW_LINE> <DEDENT> if self.paddingLength: <NEW_LINE> <INDENT> self._sendall(sock, b'\x00'*self.paddingLength)
A FastCGI Record. Used for encoding/decoding records.
6259906d1f5feb6acb164433
class TestContainerServer(unittest.TestCase): <NEW_LINE> <INDENT> def test_constructor(self): <NEW_LINE> <INDENT> raise SkipTest
Tests for container server subclass.
6259906dbaa26c4b54d50aec
@dataclass(slots=True) <NEW_LINE> class KnowledgeBase: <NEW_LINE> <INDENT> all_statements: list[Statement] = field(default_factory=list) <NEW_LINE> stated_roles: list[Role] = field(default_factory=list) <NEW_LINE> final_claims: list[Statement] = field(default_factory=list) <NEW_LINE> def __post_init__(self) -> None: <NEW_LINE> <INDENT> self.stated_roles = [Role.NONE] * const.NUM_PLAYERS <NEW_LINE> zero_priority = StatementLevel.NOT_YET_SPOKEN <NEW_LINE> self.final_claims = [Statement("", priority=zero_priority)] * const.NUM_PLAYERS <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_statement_list( cls, statement_list: tuple[Statement, ...] ) -> KnowledgeBase: <NEW_LINE> <INDENT> knowledge_base = cls() <NEW_LINE> for statement in statement_list: <NEW_LINE> <INDENT> speaker_index = statement.knowledge[0][0] <NEW_LINE> knowledge_base.add(statement, speaker_index) <NEW_LINE> <DEDENT> return knowledge_base <NEW_LINE> <DEDENT> def add(self, statement: Statement, curr_ind: int) -> None: <NEW_LINE> <INDENT> self.all_statements.append(statement) <NEW_LINE> self.stated_roles[curr_ind] = statement.speaker <NEW_LINE> self.final_claims[curr_ind] = statement
Class for storing all available knowledge shared by all players. Used during one_night, to avoid repeated computation and to help players make decisions.
6259906d2ae34c7f260ac92c
@python_2_unicode_compatible <NEW_LINE> class LearningResourceType(BaseModel): <NEW_LINE> <INDENT> name = models.TextField(unique=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name
Learning resource type: chapter, sequential, vertical, problem, video, html, etc.
6259906da8370b77170f1c0b
class _AutoSortingList(list): <NEW_LINE> <INDENT> def __init__(self, max_size=None, *args): <NEW_LINE> <INDENT> super(_AutoSortingList, self).__init__(*args) <NEW_LINE> self.max_size = max_size <NEW_LINE> <DEDENT> def append(self, item): <NEW_LINE> <INDENT> super(_AutoSortingList, self).append(item) <NEW_LINE> self.sort(key=lambda x: x[0]) <NEW_LINE> if self.max_size is not None and len(self) > self.max_size: <NEW_LINE> <INDENT> self.pop()
Simple auto-sorting list. Inefficient for large sizes since the queue is sorted at each push. Parameters --------- size : int, optional Max queue size.
6259906dd486a94d0ba2d803
class RegistryVFSStubber(object): <NEW_LINE> <INDENT> def __enter__(self): <NEW_LINE> <INDENT> self.Start() <NEW_LINE> return self <NEW_LINE> <DEDENT> def __exit__(self, exc_type, exc_value, traceback): <NEW_LINE> <INDENT> self.Stop() <NEW_LINE> <DEDENT> def Start(self): <NEW_LINE> <INDENT> modules = { "_winreg": mock.MagicMock(), "ctypes": mock.MagicMock(), "ctypes.wintypes": mock.MagicMock(), "exceptions": mock.MagicMock(), } <NEW_LINE> self.module_patcher = mock.patch.dict("sys.modules", modules) <NEW_LINE> self.module_patcher.start() <NEW_LINE> from grr.client.vfs_handlers import registry <NEW_LINE> import exceptions <NEW_LINE> import _winreg <NEW_LINE> fixture = RegistryFake() <NEW_LINE> self.stubber = utils.MultiStubber( (registry, "KeyHandle", RegistryFake.FakeKeyHandle), (registry, "OpenKey", fixture.OpenKey), (registry, "QueryValueEx", fixture.QueryValueEx), (registry, "QueryInfoKey", fixture.QueryInfoKey), (registry, "EnumValue", fixture.EnumValue), (registry, "EnumKey", fixture.EnumKey)) <NEW_LINE> self.stubber.Start() <NEW_LINE> vfs.VFSInit().Run() <NEW_LINE> _winreg.HKEY_USERS = "HKEY_USERS" <NEW_LINE> _winreg.HKEY_LOCAL_MACHINE = "HKEY_LOCAL_MACHINE" <NEW_LINE> exceptions.WindowsError = IOError <NEW_LINE> <DEDENT> def Stop(self): <NEW_LINE> <INDENT> self.module_patcher.stop() <NEW_LINE> self.stubber.Stop()
Stubber helper for tests that have to emulate registry VFS handler.
6259906dfff4ab517ebcf05f
class AdvancedAdminSite(AdminSiteWrapper): <NEW_LINE> <INDENT> def register_app_index_extra(self, app_label, func_dict_return): <NEW_LINE> <INDENT> self._app_index_register.update({ app_label: func_dict_return, }) <NEW_LINE> <DEDENT> def register_index_extra(self, func_dict_return): <NEW_LINE> <INDENT> self._index_register.append(func_dict_return) <NEW_LINE> <DEDENT> def register_notification(self, model, msg_callback): <NEW_LINE> <INDENT> self._notification_callbacks.update( { model: msg_callback } ) <NEW_LINE> <DEDENT> def __init__(self, instance, **kwargs): <NEW_LINE> <INDENT> super().__init__(instance) <NEW_LINE> self._app_index_register = {} <NEW_LINE> self._index_register = [] <NEW_LINE> self._notification_callbacks = {} <NEW_LINE> self._set_static() <NEW_LINE> <DEDENT> def _set_static(self): <NEW_LINE> <INDENT> self._instance.site_header = _('Advanced Django Administration') <NEW_LINE> <DEDENT> def _mk_notifications(self, request): <NEW_LINE> <INDENT> msgs = [] <NEW_LINE> for model, callback in self._notification_callbacks.items(): <NEW_LINE> <INDENT> msg = callback(request) <NEW_LINE> if msg: <NEW_LINE> <INDENT> tmp = { 'app_label': model._meta.app_label, 'model_name': model._meta.model_name } <NEW_LINE> tmp.update(msg) <NEW_LINE> msgs.append(tmp) <NEW_LINE> <DEDENT> <DEDENT> return msgs <NEW_LINE> <DEDENT> def _advanced_index(self, index_func): <NEW_LINE> <INDENT> def wrap_index(request, extra_context=None): <NEW_LINE> <INDENT> if not extra_context: <NEW_LINE> <INDENT> extra_context={} <NEW_LINE> <DEDENT> for e in self._index_register: <NEW_LINE> <INDENT> extra_context.update(e(request)) <NEW_LINE> <DEDENT> extra_context['notifications'] = self._mk_notifications(request) <NEW_LINE> return index_func(request, extra_context) <NEW_LINE> <DEDENT> return wrap_index <NEW_LINE> <DEDENT> def _advanced_app_index(self, app_index_func): <NEW_LINE> <INDENT> def wrap_app_index(request, app_label, extra_context=None): <NEW_LINE> <INDENT> if not extra_context: <NEW_LINE> <INDENT> extra_context={} <NEW_LINE> <DEDENT> if app_label in self._app_index_register.keys(): <NEW_LINE> <INDENT> extra_context.update(self._app_index_register[app_label](request)) <NEW_LINE> <DEDENT> return app_index_func(request, app_label, extra_context) <NEW_LINE> <DEDENT> return wrap_app_index <NEW_LINE> <DEDENT> @property <NEW_LINE> def urls(self): <NEW_LINE> <INDENT> self._instance.app_index = self._advanced_app_index(self._instance.app_index) <NEW_LINE> self._instance.index = self._advanced_index(self._instance.index) <NEW_LINE> return self._instance.urls
Adds funtionality to the 'normal' admin. BUt you can use the 'normal' admin for registering models. So there is no need to change admin.py from existing apps. It fowards all calls to the 'normal' admin if it self has no matching attribute or method (__getattr__). features: - add context to app_index view, each app can add its own context. - add context to index_view - add notifications to index_view Usage: Instead of 'normal' AdminSite import advanced admin in urls.py. Use it like 'normal' admin.site: from django.conf.urls import url form advanced_admin.admin import admin_site urlpatterns = [ url(r'^admin/', admin_site.urls), ] No need to register any ModelAdmin to advanced_admin.admin.admin_site. You can still use the normal admin.site to register your ModelAdmins: from django.contrib.admin import site site.register(MyModel, MyModelAdmin)
6259906d442bda511e95d97a
class InternalServerError(CasparError): <NEW_LINE> <INDENT> def __init__(self, command=None): <NEW_LINE> <INDENT> self.cmd = command <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return repr(self.cmd)
Exception raised after a code 500 is returned by CCG. 500 FAILED - Internal server error
6259906d8a43f66fc4bf39d8
class SignatureData(bytes): <NEW_LINE> <INDENT> def __init__(self, _): <NEW_LINE> <INDENT> super(SignatureData, self).__init__() <NEW_LINE> self.user_presence = six.indexbytes(self, 0) <NEW_LINE> self.counter = struct.unpack('>I', self[1:5])[0] <NEW_LINE> self.signature = self[5:] <NEW_LINE> <DEDENT> @property <NEW_LINE> def b64(self): <NEW_LINE> <INDENT> return websafe_encode(self) <NEW_LINE> <DEDENT> def verify(self, app_param, client_param, public_key): <NEW_LINE> <INDENT> m = app_param + self[:5] + client_param <NEW_LINE> ES256.from_ctap1(public_key).verify(m, self.signature) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return ('SignatureData(user_presence: 0x%02x, counter: %d, ' "signature: h'%s'") % (self.user_presence, self.counter, b2a_hex(self.signature)) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '%r' % self <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_b64(cls, data): <NEW_LINE> <INDENT> return cls(websafe_decode(data))
Binary response data for a CTAP1 authentication. :param _: The binary contents of the response data. :ivar user_presence: User presence byte. :ivar counter: Signature counter. :ivar signature: Cryptographic signature.
6259906d4527f215b58eb5c2
class Layout(object): <NEW_LINE> <INDENT> swagger_types = { 'name': 'str', 'width': 'float', 'height': 'float' } <NEW_LINE> attribute_map = { 'name': 'Name', 'width': 'Width', 'height': 'Height' } <NEW_LINE> def __init__(self, name=None, width=None, height=None, **kwargs): <NEW_LINE> <INDENT> self._name = None <NEW_LINE> self._width = None <NEW_LINE> self._height = None <NEW_LINE> if name is not None: <NEW_LINE> <INDENT> self.name = name <NEW_LINE> <DEDENT> if width is not None: <NEW_LINE> <INDENT> self.width = width <NEW_LINE> <DEDENT> if height is not None: <NEW_LINE> <INDENT> self.height = height <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @name.setter <NEW_LINE> def name(self, name): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> <DEDENT> @property <NEW_LINE> def width(self): <NEW_LINE> <INDENT> return self._width <NEW_LINE> <DEDENT> @width.setter <NEW_LINE> def width(self, width): <NEW_LINE> <INDENT> if width is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `width`, must not be `None`") <NEW_LINE> <DEDENT> self._width = width <NEW_LINE> <DEDENT> @property <NEW_LINE> def height(self): <NEW_LINE> <INDENT> return self._height <NEW_LINE> <DEDENT> @height.setter <NEW_LINE> def height(self, height): <NEW_LINE> <INDENT> if height is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `height`, must not be `None`") <NEW_LINE> <DEDENT> self._height = height <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, Layout): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
Represents layout contained by the CAD drawing
6259906dd486a94d0ba2d804