code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class AltitudeAlgorithm(FlatAlgorithm): <NEW_LINE> <INDENT> def test_stations_altitude(self): <NEW_LINE> <INDENT> x = (0., 10., 10.) <NEW_LINE> y = (0, 0., 10.) <NEW_LINE> z = (2., 0., -2.) <NEW_LINE> zenith = arctan(4. / 10. / sqrt(2)) <NEW_LINE> t = [0., 0., 0.] <NEW_LINE> azimuth = pi / 4. <NEW_LINE> theta, phi = self.call_reconstruct(t, x, y, z) <NEW_LINE> self.assertAlmostEqual(phi, azimuth, 5) <NEW_LINE> self.assertAlmostEqual(theta, zenith, 5)
Use this class to check the altitude support They should give similar results and errors in some cases.
6259905c4428ac0f6e659b68
class TogglePublic(BaseForm): <NEW_LINE> <INDENT> permission = RadioField( 'Permission', choices=[('public', 'Public'), ('private', 'Private')], validators=[DataRequired()])
Form to toggle the public ACL permission.
6259905c2c8b7c6e89bd4e19
class Node: <NEW_LINE> <INDENT> def __init__(self, name, isLeaf, nodeValue = None, counter = None): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.children = [] <NEW_LINE> self.isLeaf = isLeaf <NEW_LINE> self.nodeValue = nodeValue <NEW_LINE> self.counter = counter <NEW_LINE> self.value = None <NEW_LINE> if self.nodeValue != None and self.counter != None: <NEW_LINE> <INDENT> self.value = self.nodeValue * self.counter <NEW_LINE> <DEDENT> <DEDENT> def addChild(self, child): <NEW_LINE> <INDENT> assert type(child) is Node, 'Child should be a valid Node' <NEW_LINE> assert not self.isLeaf, 'Attaching child to leaf node' <NEW_LINE> self.children.append(child) <NEW_LINE> <DEDENT> def addChildren (self, children): <NEW_LINE> <INDENT> assert type(children) is list, 'children should be a list' <NEW_LINE> assert not self.isLeaf, 'Attaching children to leaf node' <NEW_LINE> self.children = self.children + children <NEW_LINE> <DEDENT> def updateTreeValue(self): <NEW_LINE> <INDENT> for child in self.children: <NEW_LINE> <INDENT> child.updateTreeValue() <NEW_LINE> <DEDENT> if not self.isLeaf: <NEW_LINE> <INDENT> childVals = [x.value for x in self.children] <NEW_LINE> for i, val in enumerate(childVals): <NEW_LINE> <INDENT> assert val != None, self.children[i].name + ' not complete ' <NEW_LINE> <DEDENT> self.value = sum(childVals) <NEW_LINE> <DEDENT> <DEDENT> def printNode(self): <NEW_LINE> <INDENT> verbose_print (pformat(self.__dict__) + '\n') <NEW_LINE> <DEDENT> def printNodeName(self): <NEW_LINE> <INDENT> verbose_print (self.name) <NEW_LINE> <DEDENT> def printTreePreorder(self, full = 0): <NEW_LINE> <INDENT> if full == 0: <NEW_LINE> <INDENT> self.printNodeName() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.printNode() <NEW_LINE> <DEDENT> for child in self.children: <NEW_LINE> <INDENT> child.printTreePreorder(full) <NEW_LINE> <DEDENT> <DEDENT> def _constructDotNodes(self, G, full = 0): <NEW_LINE> <INDENT> if full == 0: <NEW_LINE> <INDENT> desc = self.name + '\n' + str(self.value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> desc = pformat(self.__dict__) <NEW_LINE> <DEDENT> G.node(self.name, label = desc) <NEW_LINE> for child in self.children: <NEW_LINE> <INDENT> child._constructDotNodes(G,full) <NEW_LINE> <DEDENT> <DEDENT> def _constructDotEdges(self, G, full = 0): <NEW_LINE> <INDENT> for child in self.children: <NEW_LINE> <INDENT> G.edge(self.name, child.name) <NEW_LINE> child._constructDotEdges(G,full) <NEW_LINE> <DEDENT> <DEDENT> def dumpGraphPng(self, filename ='graph', full = 0): <NEW_LINE> <INDENT> G = Graph('ppa', format='png') <NEW_LINE> self._constructDotNodes(G,full) <NEW_LINE> self._constructDotEdges(G,full) <NEW_LINE> verbose_print('Dumping Graph to file:' + filename) <NEW_LINE> G.render(filename, cleanup = True)
Node represents a node in the expression tree for recursively calculating top level Value
6259905cbaa26c4b54d508d1
class GsCoordinateTransformation(GsRefObject): <NEW_LINE> <INDENT> thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> raise AttributeError("No constructor defined") <NEW_LINE> <DEDENT> __repr__ = _swig_repr <NEW_LINE> __swig_destroy__ = _gskernel.delete_GsCoordinateTransformation <NEW_LINE> def Transformation(self, *args) -> "bool": <NEW_LINE> <INDENT> return _gskernel.GsCoordinateTransformation_Transformation(self, *args)
坐标转换基类
6259905c21a7993f00c67598
class PropertiesSearchMode(bb.Union): <NEW_LINE> <INDENT> _catch_all = 'other' <NEW_LINE> other = None <NEW_LINE> @classmethod <NEW_LINE> def field_name(cls, val): <NEW_LINE> <INDENT> return cls('field_name', val) <NEW_LINE> <DEDENT> def is_field_name(self): <NEW_LINE> <INDENT> return self._tag == 'field_name' <NEW_LINE> <DEDENT> def is_other(self): <NEW_LINE> <INDENT> return self._tag == 'other' <NEW_LINE> <DEDENT> def get_field_name(self): <NEW_LINE> <INDENT> if not self.is_field_name(): <NEW_LINE> <INDENT> raise AttributeError("tag 'field_name' not set") <NEW_LINE> <DEDENT> return self._value <NEW_LINE> <DEDENT> def _process_custom_annotations(self, annotation_type, processor): <NEW_LINE> <INDENT> super(PropertiesSearchMode, self)._process_custom_annotations(annotation_type, processor) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'PropertiesSearchMode(%r, %r)' % (self._tag, self._value)
This class acts as a tagged union. Only one of the ``is_*`` methods will return true. To get the associated value of a tag (if one exists), use the corresponding ``get_*`` method. :ivar str field_name: Search for a value associated with this field name.
6259905c3539df3088ecd8c7
class Pressable(Element): <NEW_LINE> <INDENT> def __init__(self, text="", elements=None, normal_params=None, press_params=None): <NEW_LINE> <INDENT> self.press_params = init_params(press_params) <NEW_LINE> super(Pressable, self).__init__(text, elements, normal_params) <NEW_LINE> self.set_painter(painterstyle.DEF_PAINTER(size=style.SIZE)) <NEW_LINE> self._set_press_reaction(parameters.BUTTON_PRESS_EVENT, {"button": parameters.LEFT_CLICK_BUTTON}) <NEW_LINE> self._set_unpress_reaction(parameters.BUTTON_UNPRESS_EVENT, {"button": parameters.LEFT_CLICK_BUTTON}) <NEW_LINE> <DEDENT> def finish(self): <NEW_LINE> <INDENT> Element.finish(self) <NEW_LINE> self.press_params._normalize(self) <NEW_LINE> fusionner_press = self.press_params.get_fusionner() <NEW_LINE> state_pressed = State(fusionner_press) <NEW_LINE> self._states[constants.STATE_PRESSED] = state_pressed <NEW_LINE> <DEDENT> def set_style(self, new_style): <NEW_LINE> <INDENT> Element.set_style(self, new_style) <NEW_LINE> self.press_params.params["style"] = new_style <NEW_LINE> <DEDENT> def set_painter(self, painter, autopress=True): <NEW_LINE> <INDENT> Element.set_painter(self, painter) <NEW_LINE> if autopress: <NEW_LINE> <INDENT> painter = copy(painter) <NEW_LINE> painter.pressed = True <NEW_LINE> <DEDENT> self.press_params.params["painter"] = painter <NEW_LINE> <DEDENT> def _set_press_reaction(self, typ, args=None): <NEW_LINE> <INDENT> if not args: <NEW_LINE> <INDENT> args = {} <NEW_LINE> <DEDENT> reac_pressed = Reaction(typ, self._reaction_press, args, reac_name=constants.REAC_PRESSED) <NEW_LINE> self.add_reaction(reac_pressed) <NEW_LINE> <DEDENT> def _set_unpress_reaction(self, typ, args=None): <NEW_LINE> <INDENT> if not args: <NEW_LINE> <INDENT> args = {} <NEW_LINE> <DEDENT> reac_unpress = Reaction(typ, self._reaction_unpress, args, reac_name=constants.REAC_UNPRESS) <NEW_LINE> self.add_reaction(reac_unpress) <NEW_LINE> <DEDENT> def _reaction_press(self, pygame_event): <NEW_LINE> <INDENT> state_ok = self.current_state == self._states[constants.STATE_NORMAL] <NEW_LINE> if state_ok: <NEW_LINE> <INDENT> if self.collide(pygame_event.pos, constants.STATE_NORMAL): <NEW_LINE> <INDENT> self._press() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _reaction_unpress(self, pygame_event): <NEW_LINE> <INDENT> state_ok = (self.current_state_key == constants.STATE_PRESSED) <NEW_LINE> if state_ok: <NEW_LINE> <INDENT> self._unpress() <NEW_LINE> if self.collide(pygame_event.pos, constants.STATE_PRESSED): <NEW_LINE> <INDENT> self.run_user_func() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _press(self): <NEW_LINE> <INDENT> self.unblit() <NEW_LINE> self.change_state(constants.STATE_PRESSED) <NEW_LINE> self.blit() <NEW_LINE> self.update() <NEW_LINE> ev_press = Event(constants.THORPY_EVENT, id=constants.EVENT_PRESS, el=self) <NEW_LINE> post(ev_press) <NEW_LINE> <DEDENT> def _unpress(self): <NEW_LINE> <INDENT> self.unblit() <NEW_LINE> self.change_state(constants.STATE_NORMAL) <NEW_LINE> self.blit() <NEW_LINE> self.update()
Pressable Element
6259905c8da39b475be04812
class Genre(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=200, help_text='Enter a book genre (e.g. Science Fiction)') <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name
Model representing a book genre.
6259905cf548e778e596cbb6
class PartOfSpeech(Component): <NEW_LINE> <INDENT> def __init__(self, content, link_attributes=None): <NEW_LINE> <INDENT> assert isinstance(content, GenericContent) <NEW_LINE> self.content = content <NEW_LINE> if link_attributes is not None: <NEW_LINE> <INDENT> assert isinstance(link_attributes, LinkAttributes) <NEW_LINE> <DEDENT> self.link_attributes = link_attributes <NEW_LINE> <DEDENT> def serialize_xml(self): <NEW_LINE> <INDENT> content_text, attrs = self.content.serialize_xml() <NEW_LINE> if self.link_attributes is not None: <NEW_LINE> <INDENT> link_attributes_attrs = elf.link_attributes.serialize_xml() <NEW_LINE> attrs.update(link_attributes_attrs) <NEW_LINE> <DEDENT> pos_e = E('pos', **attrs) <NEW_LINE> pos_e.text = content_text <NEW_LINE> return pos_e
partOfSpeech |= element xobis:pos { linkAttributes?, genericContent }
6259905cdd821e528d6da496
class LoginManager(gui.Tag): <NEW_LINE> <INDENT> def __init__(self, cookieInterface, session_timeout_seconds = 60, **kwargs): <NEW_LINE> <INDENT> super(LoginManager, self).__init__(**kwargs) <NEW_LINE> self.eventManager = gui._EventManager(self) <NEW_LINE> self.expired = True <NEW_LINE> self.session_uid = str(random.randint(1,999999999)) <NEW_LINE> self.cookieInterface = cookieInterface <NEW_LINE> self.session_timeout_seconds = session_timeout_seconds <NEW_LINE> self.timer_request_cookies() <NEW_LINE> self.timeout_timer = None <NEW_LINE> self.EVENT_ONSESSIONEXPIRED = "on_session_expired" <NEW_LINE> <DEDENT> def timer_request_cookies(self): <NEW_LINE> <INDENT> self.cookieInterface.request_cookies() <NEW_LINE> threading.Timer(self.session_timeout_seconds/10.0, self.timer_request_cookies).start() <NEW_LINE> <DEDENT> def set_on_session_expired_listener(self, callback, *userdata): <NEW_LINE> <INDENT> self.eventManager.register_listener(self.EVENT_ONSESSIONEXPIRED, callback, *userdata) <NEW_LINE> <DEDENT> def on_session_expired(self): <NEW_LINE> <INDENT> self.expired = True <NEW_LINE> return self.eventManager.propagate(self.EVENT_ONSESSIONEXPIRED, ()) <NEW_LINE> <DEDENT> def renew_session(self): <NEW_LINE> <INDENT> if ((not 'user_uid' in self.cookieInterface.cookies) or self.cookieInterface.cookies['user_uid']!=self.session_uid) and (not self.expired): <NEW_LINE> <INDENT> self.on_session_expired() <NEW_LINE> <DEDENT> if self.expired: <NEW_LINE> <INDENT> self.session_uid = str(random.randint(1,999999999)) <NEW_LINE> <DEDENT> self.cookieInterface.set_cookie('user_uid', self.session_uid, str(self.session_timeout_seconds)) <NEW_LINE> if self.timeout_timer: <NEW_LINE> <INDENT> self.timeout_timer.cancel() <NEW_LINE> <DEDENT> self.timeout_timer = threading.Timer(self.session_timeout_seconds, self.on_session_expired) <NEW_LINE> self.expired = False <NEW_LINE> self.timeout_timer.start()
Login manager class allows to simply manage user access safety by session cookies It requires a cookieInterface instance to query and set user session id When the user login to the system you have to call login_manager.renew_session() #in order to force new session uid setup The session have to be refreshed each user action (like button click or DB access) in order to avoid expiration. BUT before renew, check if expired in order to ask user login if not login_manager.expired: login_manager.renew_session() #RENEW OK else: #UNABLE TO RENEW #HAVE TO ASK FOR LOGIN In order to know session expiration, you should register to on_session_expired event login_manager.set_on_session_expired_listener(mylistener.on_user_logout) When this event happens, ask for user login
6259905c8a43f66fc4bf37b9
class OrderInfo(models.Model): <NEW_LINE> <INDENT> ORDER_STATUS = ( ("TRADE_SUCCESS", "成功"), ("TRADE_CLOSED", "超时关闭"), ("WAIT_BUYER_PAY", "交易创建"), ("TRADE_FINISHED", "交易结束"), ("paying", "待支付"), ) <NEW_LINE> PAY_TYPE = ( ("alipay", "支付宝"), ("wechat", "微信"), ) <NEW_LINE> user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="用户") <NEW_LINE> order_sn = models.CharField(max_length=30, null=True, blank=True, unique=True, verbose_name="订单编号") <NEW_LINE> trade_no = models.CharField(max_length=100, unique=True, null=True, blank=True, verbose_name=u"交易号") <NEW_LINE> pay_status = models.CharField(choices=ORDER_STATUS, default="paying", max_length=30, verbose_name="订单状态") <NEW_LINE> pay_type = models.CharField(choices=PAY_TYPE, default="alipay", max_length=10, verbose_name="支付类型") <NEW_LINE> post_script = models.CharField(max_length=200, verbose_name="订单留言") <NEW_LINE> order_mount = models.FloatField(default=0.0, verbose_name="订单金额") <NEW_LINE> pay_time = models.DateTimeField(null=True, blank=True, verbose_name="支付时间") <NEW_LINE> address = models.CharField(max_length=100, default="", verbose_name="收货地址") <NEW_LINE> signer_name = models.CharField(max_length=20, default="", verbose_name="签收人") <NEW_LINE> singer_mobile = models.CharField(max_length=11, verbose_name="联系电话") <NEW_LINE> add_time = models.DateTimeField(default=datetime.now, verbose_name="添加时间") <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = u"订单信息" <NEW_LINE> verbose_name_plural = verbose_name <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.order_sn)
订单信息
6259905c38b623060ffaa365
class ExpectimaxAgent(MultiAgentSearchAgent): <NEW_LINE> <INDENT> def getAction(self, gameState): <NEW_LINE> <INDENT> move = self.maxPlyr(gameState, gameState.getNumAgents(), self.depth) <NEW_LINE> legalMoves = gameState.getLegalActions() <NEW_LINE> moveIndex = [index for index in range(len(legalMoves)) if legalMoves[index] == move[1]] <NEW_LINE> return legalMoves[moveIndex[0]] <NEW_LINE> <DEDENT> def expPlyr(self,state, agentIndex, numOfAgents, depth): <NEW_LINE> <INDENT> minScore = 9999 <NEW_LINE> temp = 0.0 <NEW_LINE> if(agentIndex >= numOfAgents): <NEW_LINE> <INDENT> if(depth == 1): <NEW_LINE> <INDENT> return self.evaluationFunction(state) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.maxPlyr(state, numOfAgents, depth - 1) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> legalMoves = state.getLegalActions(agentIndex) <NEW_LINE> for action in legalMoves: <NEW_LINE> <INDENT> successorGameState = state.generateSuccessor(agentIndex, action) <NEW_LINE> if(successorGameState.isLose() or successorGameState.isWin()): <NEW_LINE> <INDENT> tempScore = self.evaluationFunction(successorGameState) <NEW_LINE> temp += tempScore <NEW_LINE> continue <NEW_LINE> <DEDENT> tempScore = self.expPlyr(successorGameState, agentIndex + 1, numOfAgents, depth) <NEW_LINE> temp += tempScore <NEW_LINE> <DEDENT> <DEDENT> return temp/float(len(legalMoves)) <NEW_LINE> <DEDENT> def maxPlyr(self, state, numOfAgents, depth): <NEW_LINE> <INDENT> bestAction = None <NEW_LINE> maxScore = -9999 <NEW_LINE> legalMoves = state.getLegalActions(0) <NEW_LINE> for action in legalMoves: <NEW_LINE> <INDENT> successorGameState = state.generateSuccessor(0, action) <NEW_LINE> if(successorGameState.isLose() or successorGameState.isWin()): <NEW_LINE> <INDENT> tempScore = self.evaluationFunction(successorGameState) <NEW_LINE> if tempScore > maxScore: <NEW_LINE> <INDENT> maxScore = tempScore <NEW_LINE> bestAction = action <NEW_LINE> <DEDENT> continue <NEW_LINE> <DEDENT> tempScore = self.expPlyr(successorGameState, 1, numOfAgents, depth) <NEW_LINE> if tempScore > maxScore: <NEW_LINE> <INDENT> maxScore = tempScore <NEW_LINE> bestAction = action <NEW_LINE> <DEDENT> <DEDENT> if(depth == self.depth): <NEW_LINE> <INDENT> return maxScore,bestAction <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return maxScore <NEW_LINE> <DEDENT> util.raiseNotDefined()
Your expectimax agent (question 4)
6259905c0c0af96317c57875
class Saltelli(object): <NEW_LINE> <INDENT> def __init__(self, dist, samples, poly=None, rule="R"): <NEW_LINE> <INDENT> self.dist = dist <NEW_LINE> samples_ = dist.sample(2*samples, rule=rule) <NEW_LINE> self.samples1 = samples_.T[:samples].T <NEW_LINE> self.samples2 = samples_.T[samples:].T <NEW_LINE> self.poly = poly <NEW_LINE> self.buffer = {} <NEW_LINE> <DEDENT> def get_matrix(self, indices): <NEW_LINE> <INDENT> new = numpy.empty(self.samples1.shape) <NEW_LINE> for idx in range(len(indices)): <NEW_LINE> <INDENT> if indices[idx]: <NEW_LINE> <INDENT> new[idx] = self.samples1[idx] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> new[idx] = self.samples2[idx] <NEW_LINE> <DEDENT> <DEDENT> if self.poly: <NEW_LINE> <INDENT> new = self.poly(*new) <NEW_LINE> <DEDENT> return new <NEW_LINE> <DEDENT> def __getitem__(self, indices): <NEW_LINE> <INDENT> assert len(self.dist) == len(indices) <NEW_LINE> key = tuple(bool(idx) for idx in indices) <NEW_LINE> if key in self.buffer: <NEW_LINE> <INDENT> matrix = self.buffer[key] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> matrix = self.get_matrix(indices) <NEW_LINE> self.buffer[key] = matrix <NEW_LINE> <DEDENT> return matrix
Buffer class to be able to retrieve Saltelli matrices. The core of the method relies on cross-combining the columns of two random matrices as part of a double expectation. Examples: >>> dist = chaospy.Iid(chaospy.Uniform(), 2) >>> generator = Saltelli(dist, 3, rule="H") >>> print(generator[(False, False)]) [[ 0.875 0.0625 0.5625 ] [ 0.55555556 0.88888889 0.03703704]] >>> print(generator[(False, True)]) [[ 0.875 0.0625 0.5625 ] [ 0.44444444 0.77777778 0.22222222]] >>> print(generator[(True, False)]) [[ 0.125 0.625 0.375 ] [ 0.55555556 0.88888889 0.03703704]] >>> print(generator[(True, True)]) [[ 0.125 0.625 0.375 ] [ 0.44444444 0.77777778 0.22222222]]
6259905c4f6381625f199fb8
class ControllerBase(object): <NEW_LINE> <INDENT> def __init__(self, clock, broker, portfolio, strategies): <NEW_LINE> <INDENT> self._clock = clock <NEW_LINE> self._broker = broker <NEW_LINE> self._strategies = strategies <NEW_LINE> self._portfolio = portfolio <NEW_LINE> <DEDENT> def initialize(self, tick): <NEW_LINE> <INDENT> for strategy in self._strategies: <NEW_LINE> <INDENT> strategy.start(self._broker, tick) <NEW_LINE> <DEDENT> <DEDENT> def run(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def run_until_stopped(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def is_running(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def execute_tick(self, tick): <NEW_LINE> <INDENT> raise NotImplementedError()
A controller class takes care to run the actions returned by the strategies for each clock tick. How exactly this is implemented is deferred to the concrete subclass.
6259905c8e71fb1e983bd0f7
class User(Base): <NEW_LINE> <INDENT> __tablename__ = 'users' <NEW_LINE> id = Column( UUID(as_uuid=True), primary_key=True, default=uuid4 ) <NEW_LINE> name = Column( Text, nullable=False, unique=True ) <NEW_LINE> appointments = orm.relationship( "Appointment", back_populates="user" )
The SQLAlchemy declarative model class for a User object.
6259905c07f4c71912bb0a69
class Eyes(object): <NEW_LINE> <INDENT> def __init__(self, face): <NEW_LINE> <INDENT> self.face = face <NEW_LINE> self.size = self.face.determine_facial_feature(feature_type="eye size") <NEW_LINE> self.shape = self.face.determine_facial_feature(feature_type="eye shape") <NEW_LINE> self.color = self.face.determine_facial_feature(feature_type="eye color") <NEW_LINE> self.horizontal_settedness = self.face.determine_facial_feature(feature_type="eye horizontal settedness") <NEW_LINE> self.vertical_settedness = self.face.determine_facial_feature(feature_type="eye vertical settedness")
A person's eyes.
6259905c63b5f9789fe8679f
class AssetItemURL(SingleAssetURL): <NEW_LINE> <INDENT> path: str <NEW_LINE> def get_assets( self, client: DandiAPIClient, order: Optional[str] = None, strict: bool = False ) -> Iterator[BaseRemoteAsset]: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> dandiset = self.get_dandiset(client, lazy=not strict) <NEW_LINE> assert dandiset is not None <NEW_LINE> dandiset.version_id <NEW_LINE> <DEDENT> except NotFoundError: <NEW_LINE> <INDENT> if strict: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> try: <NEW_LINE> <INDENT> yield dandiset.get_asset_by_path(self.path) <NEW_LINE> <DEDENT> except NotFoundError: <NEW_LINE> <INDENT> if strict: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> next(dandiset.get_assets_with_path_prefix(self.path + "/")) <NEW_LINE> <DEDENT> except NotFoundError: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> except StopIteration: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError( f"Asset path {self.path!r} points to a directory but lacks trailing /" )
Parsed from a URL that refers to a specific asset by path
6259905c0a50d4780f7068d5
class UserManager(BaseUserManager): <NEW_LINE> <INDENT> use_in_migrations = True <NEW_LINE> def _create_user(self, username, email, password,role, **extra_fields): <NEW_LINE> <INDENT> if not email: <NEW_LINE> <INDENT> raise ValueError("Email is required") <NEW_LINE> <DEDENT> if not username: <NEW_LINE> <INDENT> raise ValueError("Username is required") <NEW_LINE> <DEDENT> if not role: <NEW_LINE> <INDENT> raise ValueError("Role is required") <NEW_LINE> <DEDENT> email = self.normalize_email(email) <NEW_LINE> if role == 'is_technician': <NEW_LINE> <INDENT> user = self.model(username=username,email=email,is_technician='True', **extra_fields) <NEW_LINE> <DEDENT> if role == 'is_customer': <NEW_LINE> <INDENT> user = self.model(username=username,email=email, is_customer="True", **extra_fields) <NEW_LINE> <DEDENT> if role == 'admin': <NEW_LINE> <INDENT> user = self.model(username=username,email=email, **extra_fields) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> validate_password(password,user) <NEW_LINE> <DEDENT> except ValidationError as e: <NEW_LINE> <INDENT> raise ValidationError({"password": e }) <NEW_LINE> <DEDENT> user.set_password(password) <NEW_LINE> user.is_active = False <NEW_LINE> user.save(using=self._db) <NEW_LINE> return user <NEW_LINE> <DEDENT> def create_user(self, username, email, role,password=None, **extra_fields): <NEW_LINE> <INDENT> extra_fields.setdefault("is_staff", False) <NEW_LINE> extra_fields.setdefault("is_superuser", False) <NEW_LINE> return self._create_user(username, email, password,role, **extra_fields) <NEW_LINE> <DEDENT> def create_superuser(self, username, email, password,role=None,**extra_fields): <NEW_LINE> <INDENT> extra_fields.setdefault("is_staff", True) <NEW_LINE> extra_fields.setdefault("is_superuser", True) <NEW_LINE> if extra_fields.get("is_staff") is not True: <NEW_LINE> <INDENT> raise ValueError("Superuser must have is_staff=True.") <NEW_LINE> <DEDENT> if extra_fields.get("is_superuser") is not True: <NEW_LINE> <INDENT> raise ValueError("Superuser must have is_superuser=True.") <NEW_LINE> <DEDENT> return self._create_user(username,email, password,role="admin", **extra_fields) <NEW_LINE> <DEDENT> def get_filter(self,user_id): <NEW_LINE> <INDENT> return self.filter(id=user_id) <NEW_LINE> <DEDENT> def get_instance(self,user_id): <NEW_LINE> <INDENT> return self.get(id=user_id) <NEW_LINE> <DEDENT> def user_address(self,User): <NEW_LINE> <INDENT> inst = self.get_instance(User) <NEW_LINE> return inst.currentaddress
Define a model manager for User model with no username field.
6259905c6e29344779b01c7b
class ThreadTests(KBForumTestCase): <NEW_LINE> <INDENT> def test_watch_forum(self): <NEW_LINE> <INDENT> u = UserFactory() <NEW_LINE> self.client.login(username=u.username, password='testpass') <NEW_LINE> d = DocumentFactory() <NEW_LINE> post(self.client, 'wiki.discuss.watch_forum', {'watch': 'yes'}, args=[d.slug]) <NEW_LINE> assert NewThreadEvent.is_notifying(u, d) <NEW_LINE> t = ThreadFactory(document=d) <NEW_LINE> p = t.new_post(creator=t.creator, content='test') <NEW_LINE> assert not NewPostEvent.is_notifying(u, p) <NEW_LINE> post(self.client, 'wiki.discuss.watch_forum', {'watch': 'no'}, args=[d.slug]) <NEW_LINE> assert not NewThreadEvent.is_notifying(u, d) <NEW_LINE> <DEDENT> def test_watch_thread(self): <NEW_LINE> <INDENT> u = UserFactory() <NEW_LINE> self.client.login(username=u.username, password='testpass') <NEW_LINE> t = ThreadFactory() <NEW_LINE> post(self.client, 'wiki.discuss.watch_thread', {'watch': 'yes'}, args=[t.document.slug, t.id]) <NEW_LINE> assert NewPostEvent.is_notifying(u, t) <NEW_LINE> assert not NewThreadEvent.is_notifying(u, t.document) <NEW_LINE> post(self.client, 'wiki.discuss.watch_thread', {'watch': 'no'}, args=[t.document.slug, t.id]) <NEW_LINE> assert not NewPostEvent.is_notifying(u, t) <NEW_LINE> <DEDENT> def test_edit_thread(self): <NEW_LINE> <INDENT> u = UserFactory() <NEW_LINE> self.client.login(username=u.username, password='testpass') <NEW_LINE> d = DocumentFactory() <NEW_LINE> t = ThreadFactory(title='Sticky Thread', document=d, creator=u) <NEW_LINE> post(self.client, 'wiki.discuss.edit_thread', {'title': 'A new title'}, args=[d.slug, t.id]) <NEW_LINE> edited_t = d.thread_set.get(pk=t.id) <NEW_LINE> eq_('Sticky Thread', t.title) <NEW_LINE> eq_('A new title', edited_t.title) <NEW_LINE> <DEDENT> def test_edit_thread_moderator(self): <NEW_LINE> <INDENT> u = UserFactory() <NEW_LINE> add_permission(u, Thread, 'change_thread') <NEW_LINE> t = ThreadFactory(title='Sticky Thread') <NEW_LINE> d = t.document <NEW_LINE> self.client.login(username=u.username, password='testpass') <NEW_LINE> eq_('Sticky Thread', t.title) <NEW_LINE> r = post(self.client, 'wiki.discuss.edit_thread', {'title': 'new title'}, args=[d.slug, t.id]) <NEW_LINE> eq_(200, r.status_code) <NEW_LINE> edited_t = Thread.objects.get(pk=t.id) <NEW_LINE> eq_('new title', edited_t.title) <NEW_LINE> <DEDENT> def test_disallowed_404(self): <NEW_LINE> <INDENT> u = UserFactory() <NEW_LINE> self.client.login(username=u.username, password='testpass') <NEW_LINE> doc = DocumentFactory(allow_discussion=False) <NEW_LINE> def check(url): <NEW_LINE> <INDENT> response = get(self.client, url, args=[doc.slug]) <NEW_LINE> st = response.status_code <NEW_LINE> eq_(404, st, '%s was %s, not 404' % (url, st)) <NEW_LINE> <DEDENT> check('wiki.discuss.threads') <NEW_LINE> check('wiki.discuss.new_thread') <NEW_LINE> check('wiki.discuss.threads.feed')
Test thread views.
6259905c7cff6e4e811b7072
class NotFound(ParcelBrightAPIException): <NEW_LINE> <INDENT> pass
Raised when server response is 404
6259905c21a7993f00c6759a
class PacanowskiPhilanderModelOptions(TurbulenceModelOptions): <NEW_LINE> <INDENT> name = 'Pacanowski-Philander turbulence closure model' <NEW_LINE> max_viscosity = PositiveFloat(5e-2, help=r"float: Constant maximum viscosity :math:`\nu_{max}`").tag(config=True) <NEW_LINE> alpha = PositiveFloat(10.0, help="float: Richardson number multiplier").tag(config=True) <NEW_LINE> exponent = PositiveFloat(2.0, help=r"float: Exponent of viscosity numerator :math:`n`").tag(config=True)
Options for Pacanowski-Philander turbulence model
6259905c7047854f463409ed
class AuditlogModelRegistry(object): <NEW_LINE> <INDENT> def __init__(self, create=True, update=True, delete=True, custom=None): <NEW_LINE> <INDENT> from auditlog.receivers import log_create, log_update, log_delete <NEW_LINE> self._registry = {} <NEW_LINE> self._signals = {} <NEW_LINE> if create: <NEW_LINE> <INDENT> self._signals[post_save] = log_create <NEW_LINE> <DEDENT> if update: <NEW_LINE> <INDENT> self._signals[pre_save] = log_update <NEW_LINE> <DEDENT> if delete: <NEW_LINE> <INDENT> self._signals[post_delete] = log_delete <NEW_LINE> <DEDENT> if custom is not None: <NEW_LINE> <INDENT> self._signals.update(custom) <NEW_LINE> <DEDENT> <DEDENT> def register(self, model, include_fields=[], exclude_fields=[]): <NEW_LINE> <INDENT> if issubclass(model, Model): <NEW_LINE> <INDENT> self._registry[model] = { 'include_fields': include_fields, 'exclude_fields': exclude_fields, } <NEW_LINE> self._connect_signals(model) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError("Supplied model is not a valid model.") <NEW_LINE> <DEDENT> <DEDENT> def contains(self, model): <NEW_LINE> <INDENT> return model in self._registry <NEW_LINE> <DEDENT> def unregister(self, model): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> del self._registry[model] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._disconnect_signals(model) <NEW_LINE> <DEDENT> <DEDENT> def _connect_signals(self, model): <NEW_LINE> <INDENT> for signal in self._signals: <NEW_LINE> <INDENT> receiver = self._signals[signal] <NEW_LINE> signal.connect(receiver, sender=model, dispatch_uid=self._dispatch_uid(signal, model)) <NEW_LINE> <DEDENT> <DEDENT> def _disconnect_signals(self, model): <NEW_LINE> <INDENT> for signal, receiver in self._signals: <NEW_LINE> <INDENT> signal.disconnect(dispatch_uid=self._dispatch_uid(signal, model)) <NEW_LINE> <DEDENT> <DEDENT> def _dispatch_uid(self, signal, model): <NEW_LINE> <INDENT> return (self.__class__, model, signal) <NEW_LINE> <DEDENT> def get_model_fields(self, model): <NEW_LINE> <INDENT> return { 'include_fields': self._registry[model]['include_fields'], 'exclude_fields': self._registry[model]['exclude_fields'], }
A registry that keeps track of the models that use Auditlog to track changes.
6259905ca8ecb03325872845
@dataclass <NEW_LINE> class Teacher: <NEW_LINE> <INDENT> first_name: str <NEW_LINE> second_name: str <NEW_LINE> full_name: str <NEW_LINE> abbreviation: str <NEW_LINE> email: str <NEW_LINE> phone: str <NEW_LINE> room: str <NEW_LINE> url: str
Class storing information about a teacher.
6259905c8da39b475be04814
class ResponseFactoryPreparator: <NEW_LINE> <INDENT> def __init__(self, response_factory): <NEW_LINE> <INDENT> self._response_factory = response_factory <NEW_LINE> <DEDENT> def prepare_fixed_response(self, fixed_response_class): <NEW_LINE> <INDENT> def _parser(response_type, parameters): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> encoded_body = parameters["body"] <NEW_LINE> status = parameters["status"] <NEW_LINE> headers = parameters["headers"] <NEW_LINE> <DEDENT> except (TypeError, KeyError) as error: <NEW_LINE> <INDENT> message = ( "Response parameters must be a dictionary with keys 'body', 'status', 'headers'" ) <NEW_LINE> raise ResponseParseError(message) from error <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> body = base64.b64decode(encoded_body.encode("utf8")) <NEW_LINE> <DEDENT> except (AttributeError, binascii.Error) as error: <NEW_LINE> <INDENT> message = "Body can't be decoded with base64 encoding" <NEW_LINE> raise ResponseParseError(message) from error <NEW_LINE> <DEDENT> return fixed_response_class( response_type=response_type, body=body, status=status, headers=headers, ) <NEW_LINE> <DEDENT> def _serializer(response_type, response): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> body = response.body <NEW_LINE> status = response.status <NEW_LINE> headers = response.headers <NEW_LINE> <DEDENT> except AttributeError as error: <NEW_LINE> <INDENT> message = "Response must have attributes 'body', 'status' and 'headers'" <NEW_LINE> raise ResponseSerializeError(message) from error <NEW_LINE> <DEDENT> if isinstance(body, str): <NEW_LINE> <INDENT> body = body.encode("utf8") <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> encoded_body = base64.b64encode(body).decode("utf8") <NEW_LINE> <DEDENT> except TypeError as error: <NEW_LINE> <INDENT> message = "Body can't be encoded with base64 encoding" <NEW_LINE> raise ResponseSerializeError(message) from error <NEW_LINE> <DEDENT> return { "body": encoded_body, "status": status, "headers": headers, } <NEW_LINE> <DEDENT> self._response_factory.register_response( response_type=ResponseType.FIXED.name, parser=_parser, serializer=_serializer, )
Class to prepare response factory.
6259905cf548e778e596cbb8
class Config(object): <NEW_LINE> <INDENT> SECRET_KEY = '29693eaa35867118e267082e9060d194'
Base config class.
6259905c009cb60464d02b63
class PeerObject: <NEW_LINE> <INDENT> def __init__(self, peer_info: PeerInfo): <NEW_LINE> <INDENT> self.__peer_info: PeerInfo = peer_info <NEW_LINE> self.__stub_manager: StubManager = None <NEW_LINE> self.__cert_verifier: PublicVerifier = None <NEW_LINE> self.__no_response_count = 0 <NEW_LINE> self.__create_live_data() <NEW_LINE> <DEDENT> def __create_live_data(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.__stub_manager = StubManager(self.__peer_info.target, loopchain_pb2_grpc.PeerServiceStub) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logging.exception(f"Create Peer create stub_manager fail target : {self.__peer_info.target} \n" f"exception : {e}") <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.__cert_verifier = PublicVerifier(self.peer_info.cert) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logging.exception(f"create cert verifier error : {self.__peer_info.cert} \n" f"exception {e}") <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def peer_info(self)-> PeerInfo: <NEW_LINE> <INDENT> return self.__peer_info <NEW_LINE> <DEDENT> @property <NEW_LINE> def stub_manager(self) -> StubManager: <NEW_LINE> <INDENT> return self.__stub_manager <NEW_LINE> <DEDENT> @property <NEW_LINE> def cert_verifier(self) -> PublicVerifier: <NEW_LINE> <INDENT> return self.__cert_verifier <NEW_LINE> <DEDENT> @property <NEW_LINE> def no_response_count(self): <NEW_LINE> <INDENT> return self.__no_response_count <NEW_LINE> <DEDENT> def no_response_count_up(self): <NEW_LINE> <INDENT> self.__no_response_count += 1 <NEW_LINE> <DEDENT> def no_response_count_reset(self): <NEW_LINE> <INDENT> self.__no_response_count = 0
Peer object has PeerInfo and live data
6259905ca79ad1619776b5d4
class UserDetailSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> profile = serializers.SerializerMethodField('get_profile_data') <NEW_LINE> full_name = serializers.Field(source='get_full_name') <NEW_LINE> organizations = serializers.SerializerMethodField('list_organizations') <NEW_LINE> def get_profile_data(self, obj): <NEW_LINE> <INDENT> if obj.is_anonymous(): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> serializer = UserProfileSerializer(obj.profile) <NEW_LINE> return serializer.data <NEW_LINE> <DEDENT> def list_organizations(self, obj): <NEW_LINE> <INDENT> ngo = {'count': 0, 'items': [], } <NEW_LINE> if obj.is_anonymous(): <NEW_LINE> <INDENT> return ngo <NEW_LINE> <DEDENT> ngo['count'] = obj.organizations.count() <NEW_LINE> for org in obj.organizations.all(): <NEW_LINE> <INDENT> ngo['items'].append({ 'id': org.pk, 'name': org.name, 'url': org.get_absolute_url(), }) <NEW_LINE> <DEDENT> return ngo <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> model = User <NEW_LINE> fields = ('id', 'username', 'first_name', 'last_name', 'full_name', 'email', 'is_superuser', 'date_joined', 'last_login', 'profile', 'organizations', )
Detailed serializer presenting user data. Meant to be read-only.
6259905ca219f33f346c7e34
class Component(Resource): <NEW_LINE> <INDENT> def __init__( self, options: Dict[str, str], session: ResilientSession, raw: Dict[str, Any] = None, ): <NEW_LINE> <INDENT> Resource.__init__(self, "component/{0}", options, session) <NEW_LINE> if raw: <NEW_LINE> <INDENT> self._parse_raw(raw) <NEW_LINE> <DEDENT> self.raw: Dict[str, Any] = cast(Dict[str, Any], self.raw) <NEW_LINE> <DEDENT> def delete(self, moveIssuesTo: Optional[str] = None): <NEW_LINE> <INDENT> params = {} <NEW_LINE> if moveIssuesTo is not None: <NEW_LINE> <INDENT> params["moveIssuesTo"] = moveIssuesTo <NEW_LINE> <DEDENT> super().delete(params)
A project component.
6259905c0c0af96317c57876
class SecureValueTypeDriverLicense(TLObject): <NEW_LINE> <INDENT> __slots__ = [] <NEW_LINE> ID = 0x06e425c4 <NEW_LINE> QUALNAME = "types.SecureValueTypeDriverLicense" <NEW_LINE> def __init__(self, ): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def read(b: BytesIO, *args) -> "SecureValueTypeDriverLicense": <NEW_LINE> <INDENT> return SecureValueTypeDriverLicense() <NEW_LINE> <DEDENT> def write(self) -> bytes: <NEW_LINE> <INDENT> b = BytesIO() <NEW_LINE> b.write(Int(self.ID, False)) <NEW_LINE> return b.getvalue()
Attributes: LAYER: ``112`` Attributes: ID: ``0x06e425c4`` No parameters required.
6259905c4e4d562566373a36
class InlineResponse500(object): <NEW_LINE> <INDENT> openapi_types = { 'http_code': 'int', 'http_status': 'str', 'internal_server_error': 'InlineResponse500InternalServerError' } <NEW_LINE> attribute_map = { 'http_code': 'http_code', 'http_status': 'http_status', 'internal_server_error': 'internal_server_error' } <NEW_LINE> def __init__(self, http_code=None, http_status=None, internal_server_error=None): <NEW_LINE> <INDENT> self._http_code = None <NEW_LINE> self._http_status = None <NEW_LINE> self._internal_server_error = None <NEW_LINE> self.discriminator = None <NEW_LINE> if http_code is not None: <NEW_LINE> <INDENT> self.http_code = http_code <NEW_LINE> <DEDENT> if http_status is not None: <NEW_LINE> <INDENT> self.http_status = http_status <NEW_LINE> <DEDENT> if internal_server_error is not None: <NEW_LINE> <INDENT> self.internal_server_error = internal_server_error <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def http_code(self): <NEW_LINE> <INDENT> return self._http_code <NEW_LINE> <DEDENT> @http_code.setter <NEW_LINE> def http_code(self, http_code): <NEW_LINE> <INDENT> self._http_code = http_code <NEW_LINE> <DEDENT> @property <NEW_LINE> def http_status(self): <NEW_LINE> <INDENT> return self._http_status <NEW_LINE> <DEDENT> @http_status.setter <NEW_LINE> def http_status(self, http_status): <NEW_LINE> <INDENT> allowed_values = ["Internal server error"] <NEW_LINE> if http_status not in allowed_values: <NEW_LINE> <INDENT> raise ValueError( "Invalid value for `http_status` ({0}), must be one of {1}" .format(http_status, allowed_values) ) <NEW_LINE> <DEDENT> self._http_status = http_status <NEW_LINE> <DEDENT> @property <NEW_LINE> def internal_server_error(self): <NEW_LINE> <INDENT> return self._internal_server_error <NEW_LINE> <DEDENT> @internal_server_error.setter <NEW_LINE> def internal_server_error(self, internal_server_error): <NEW_LINE> <INDENT> self._internal_server_error = internal_server_error <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.openapi_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, InlineResponse500): <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
NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually.
6259905c379a373c97d9a653
class IC_4077(Base_14pin): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.pins = [None, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] <NEW_LINE> self.pins = pinlist_quick(self.pins) <NEW_LINE> self.uses_pincls = True <NEW_LINE> self.set_IC({1: {'desc': 'A1: Input 1 of XNOR gate 1'}, 2: {'desc': 'B1: Input 2 of XNOR gate 1'}, 3: {'desc': 'Q1: Output of XNOR gate 1'}, 4: {'desc': 'Q2: Output of XNOR gate 2'}, 5: {'desc': 'B2: Input 2 of XNOR gate 2'}, 6: {'desc': 'A2: Input 1 of XNOR gate 2'}, 7: {'desc': 'GND'}, 8: {'desc': 'A3: Input 1 of XNOR gate 3'}, 9: {'desc': 'B3: Input 2 of XNOR gate 3'}, 10: {'desc': 'Q3: Output of XNOR gate 3'}, 11: {'desc': 'Q4: Output of XNOR gate 4'}, 12: {'desc': 'B4: Input 2 of XNOR gate 4'}, 13: {'desc': 'A4: Input 1 of XNOR gate 4'}, 14: {'desc': 'VCC'} }) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> output = {} <NEW_LINE> output[3] = XNOR(self.pins[1].value, self.pins[2].value).output() <NEW_LINE> output[4] = XNOR(self.pins[5].value, self.pins[6].value).output() <NEW_LINE> output[10] = XNOR(self.pins[8].value, self.pins[9].value).output() <NEW_LINE> output[11] = XNOR(self.pins[12].value, self.pins[13].value).output() <NEW_LINE> if self.pins[7].value == 0 and self.pins[14].value == 1: <NEW_LINE> <INDENT> self.set_IC(output) <NEW_LINE> for i in self.output_connector: <NEW_LINE> <INDENT> self.output_connector[i].state = output[i] <NEW_LINE> <DEDENT> return output <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print ("Ground and VCC pins have not been configured correctly.")
Quad 2 input XNOR gate Pin_3 = XNOR(Pin_1, Pin_2) Pin_4 = XNOR(Pin_5, Pin_6) Pin_10 = XNOR(Pin_8, Pin_9) Pin_11 = XNOR(Pin_12, Pin_13)
6259905c1b99ca400229004e
class DesignMatrix(): <NEW_LINE> <INDENT> def __init__(self, matrix, names, frametimes=None): <NEW_LINE> <INDENT> matrix_ = np.atleast_2d(matrix) <NEW_LINE> if matrix_.shape[1] != len(names): <NEW_LINE> <INDENT> raise ValueError( 'The number of names should equate the number of columns') <NEW_LINE> <DEDENT> if frametimes is not None: <NEW_LINE> <INDENT> if frametimes.size != matrix.shape[0]: <NEW_LINE> <INDENT> raise ValueError( 'The number %d of frametimes is different from the' + 'number %d of rows' % (frametimes.size, matrix.shape[0])) <NEW_LINE> <DEDENT> <DEDENT> self.frametimes = np.asarray(frametimes, dtype=np.float) <NEW_LINE> self.matrix = matrix_ <NEW_LINE> self.names = names <NEW_LINE> <DEDENT> def write_csv(self, path): <NEW_LINE> <INDENT> import csv <NEW_LINE> with open4csv(path, "w") as fid: <NEW_LINE> <INDENT> writer = csv.writer(fid) <NEW_LINE> writer.writerow(self.names) <NEW_LINE> writer.writerows(self.matrix) <NEW_LINE> <DEDENT> <DEDENT> def show(self, rescale=True, ax=None): <NEW_LINE> <INDENT> import matplotlib.pyplot as plt <NEW_LINE> x = self.matrix.copy() <NEW_LINE> if rescale: <NEW_LINE> <INDENT> x = x / np.sqrt(np.sum(x ** 2, 0)) <NEW_LINE> <DEDENT> if ax is None: <NEW_LINE> <INDENT> plt.figure() <NEW_LINE> ax = plt.subplot(1, 1, 1) <NEW_LINE> <DEDENT> ax.imshow(x, interpolation='Nearest', aspect='auto') <NEW_LINE> ax.set_label('conditions') <NEW_LINE> ax.set_ylabel('scan number') <NEW_LINE> if self.names is not None: <NEW_LINE> <INDENT> ax.set_xticks(range(len(self.names))) <NEW_LINE> ax.set_xticklabels(self.names, rotation=60, ha='right') <NEW_LINE> <DEDENT> return ax
This is a container for a light-weight class for design matrices This class is only used to make IO and visualization Class members ------------- matrix: array of shape(n_scans, n_regressors), the numerical specification of the matrix names: list of len (n_regressors); the names associated with the columns frametimes: array of shape(n_scans), optional, the occurrence time of the matrix rows
6259905c91f36d47f22319a6
class LogHandler(logging.Handler): <NEW_LINE> <INDENT> def __init__(self, type_name=None): <NEW_LINE> <INDENT> super(LogHandler, self).__init__() <NEW_LINE> self.type_name = type_name <NEW_LINE> <DEDENT> def emit(self, record): <NEW_LINE> <INDENT> if record.name.startswith('blueox'): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> with Context(self.type_name or '.log') as c: <NEW_LINE> <INDENT> c.set('name', record.name) <NEW_LINE> c.set('level', record.levelname) <NEW_LINE> c.set('msg', record.getMessage()) <NEW_LINE> if record.exc_info: <NEW_LINE> <INDENT> c.set('exception', ''.join(traceback.format_exception(*record.exc_info)))
Handler to provide log events as blueox events. Records standard fields such as logger name, level the message and if an exception was provided, the string formatted exception. The type name, if not specified will be something like '<my parent context>.log'
6259905c45492302aabfdb07
class Question(ndb.Model): <NEW_LINE> <INDENT> poll = ndb.IntegerProperty(indexed=True) <NEW_LINE> text = ndb.StringProperty(indexed=False) <NEW_LINE> questionType = ndb.StringProperty(indexed=False, default="MultipleChoice", choices=["MultipleChoice","Numeric"]) <NEW_LINE> def getChoices(self): <NEW_LINE> <INDENT> return Choice.query().filter(Choice._properties["question"]==self.key.integer_id()).fetch()
A question, which will be featured in a single poll.
6259905c32920d7e50bc7675
class SubmitFeedResultSet(ResultSet): <NEW_LINE> <INDENT> def getJSONFromString(self, str): <NEW_LINE> <INDENT> return json.loads(str) <NEW_LINE> <DEDENT> def get_Response(self): <NEW_LINE> <INDENT> return self._output.get('Response', None) <NEW_LINE> <DEDENT> def get_SubmissionResult(self): <NEW_LINE> <INDENT> return self._output.get('SubmissionResult', None) <NEW_LINE> <DEDENT> def get_SubmissionId(self): <NEW_LINE> <INDENT> return self._output.get('SubmissionId', None) <NEW_LINE> <DEDENT> def get_ProcessingStatus(self): <NEW_LINE> <INDENT> return self._output.get('ProcessingStatus', None)
A ResultSet with methods tailored to the values returned by the SubmitFeed Choreo. The ResultSet object is used to retrieve the results of a Choreo execution.
6259905c15baa723494635c1
class _QuadPhaseShifted(QuadPhase): <NEW_LINE> <INDENT> def __init__(self, z, **kwargs): <NEW_LINE> <INDENT> QuadPhase.__init__(self, z, **kwargs) <NEW_LINE> <DEDENT> def get_phasor(self, wave): <NEW_LINE> <INDENT> return accel_math._fftshift(super(_QuadPhaseShifted, self).get_phasor(wave))
Identical to class 'QuadPhase' except for array origin. This class provides a quadratic phase factor for application to FFT shifted wavefronts, with the origin in the corner. For centered "physical" coordinate system optics with an origin at the wavefront center use `QuadPhase`.
6259905c07f4c71912bb0a6b
class SPECTEQ(Effect): <NEW_LINE> <INDENT> instrument = "SPECTEQ" <NEW_LINE> pfields = () <NEW_LINE> def __init__(self, outsk=None, insk=None, dur=None, amp=None, ringdowndur=None, fftsize=None, windowsize=None, windowtype=None, overlap=None, inputchan=None, pan=None, *extra_args, **extra_kwargs): <NEW_LINE> <INDENT> self._passback(locals())
SPECTEQ(outsk, insk, dur, amp, ringdowndur, fftsize, windowsize, windowtype, overlap[, inputchan, pan {default: 0.5}])
6259905c627d3e7fe0e084ba
class CourseHomeMessageFragmentView(EdxFragmentView): <NEW_LINE> <INDENT> def render_to_fragment(self, request, course_id, user_access, **kwargs): <NEW_LINE> <INDENT> course_key = CourseKey.from_string(course_id) <NEW_LINE> course = get_course_with_access(request.user, 'load', course_key) <NEW_LINE> now = datetime.now(UTC) <NEW_LINE> already_started = course.start and now > course.start <NEW_LINE> days_until_start_string = "started" if already_started else format_timedelta( course.start - now, locale=to_locale(get_language()) ) <NEW_LINE> course_start_data = { 'course_start_date': format_date(course.start, locale=to_locale(get_language())), 'already_started': already_started, 'days_until_start_string': days_until_start_string } <NEW_LINE> _register_course_home_messages(request, course, user_access, course_start_data) <NEW_LINE> for course_date_block in get_course_date_blocks(course, request.user, request): <NEW_LINE> <INDENT> course_date_block.register_alerts(request, course) <NEW_LINE> <DEDENT> user_goal = get_course_goal(auth.get_user(request), course_key) <NEW_LINE> is_already_verified = CourseEnrollment.is_enrolled_as_verified(request.user, course_key) <NEW_LINE> if has_course_goal_permission(request, course_id, user_access) and not is_already_verified and not user_goal: <NEW_LINE> <INDENT> _register_course_goal_message(request, course) <NEW_LINE> <DEDENT> course_home_messages = list(CourseHomeMessages.user_messages(request)) <NEW_LINE> goal_api_url = get_goal_api_url(request) <NEW_LINE> image_src = 'course_experience/images/home_message_author.png' <NEW_LINE> context = { 'course_home_messages': course_home_messages, 'goal_api_url': goal_api_url, 'image_src': image_src, 'course_id': course_id, 'username': request.user.username, } <NEW_LINE> html = render_to_string('course_experience/course-messages-fragment.html', context) <NEW_LINE> return Fragment(html)
A fragment that displays a course message with an alert and call to action for three types of users: 1) Not logged in users are given a link to sign in or register. 2) Unenrolled users are given a link to enroll. 3) Enrolled users who get to the page before the course start date are given the option to add the start date to their calendar. This fragment requires a user_access map as follows: user_access = { 'is_anonymous': True if the user is logged in, False otherwise 'is_enrolled': True if the user is enrolled in the course, False otherwise 'is_staff': True if the user is a staff member of the course, False otherwise }
6259905c8e7ae83300eea6bc
class User(TweettrBase): <NEW_LINE> <INDENT> id: int <NEW_LINE> id_str: str <NEW_LINE> name: str <NEW_LINE> screen_name: str <NEW_LINE> location: Optional[str] <NEW_LINE> url: Optional[str] <NEW_LINE> description: Optional[str] <NEW_LINE> protected: bool <NEW_LINE> verified: bool <NEW_LINE> followers_count: int <NEW_LINE> friends_count: int <NEW_LINE> listed_count: int <NEW_LINE> favourites_count: int <NEW_LINE> statuses_count: int <NEW_LINE> created_at: str <NEW_LINE> default_profile: bool <NEW_LINE> default_profile_image: bool <NEW_LINE> profile_image_url_https: str <NEW_LINE> profile_banner_url: Optional[str] <NEW_LINE> withheld_in_countries: Optional[List[str]] <NEW_LINE> withheld_scope: Optional[str] <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return f'{self.__class__.__name__}(screen_name={repr(self.screen_name)}, id={repr(self.id)})'
User see: https://developer.twitter.com/en/docs/tweets/data-dictionary/overview/user-object Attributes ---------- {attributes}
6259905ccb5e8a47e493cc9d
class SetCalibrationSpeed10Action(SetCalibrationSpeedAction): <NEW_LINE> <INDENT> name = 'setCalibrationSpeed10' <NEW_LINE> text = gettext('Speed Factor _10') <NEW_LINE> radioValue = 10
The calibration procedure is sped up by a factor of ten.
6259905c6e29344779b01c7d
class AdminDeleteExpenseTests(ManagerDeleteExpenseTests): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.current_client = self.admin_client <NEW_LINE> self.current_user = self.admin_user <NEW_LINE> <DEDENT> def main_test_for_user(self, user): <NEW_LINE> <INDENT> user_expense_ids = get_expense_ids_from_user(user) <NEW_LINE> for exp_id in user_expense_ids: <NEW_LINE> <INDENT> url = reverse( 'expenses:detail', kwargs={ 'pk': exp_id, } ) <NEW_LINE> response = self.current_client.delete(url) <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) <NEW_LINE> <DEDENT> <DEDENT> def test_delete_self_exp(self): <NEW_LINE> <INDENT> user_expense_ids = get_expense_ids_from_user(self.current_user) <NEW_LINE> for exp_id in user_expense_ids: <NEW_LINE> <INDENT> url = reverse( 'expenses:detail', kwargs={ 'pk': exp_id, } ) <NEW_LINE> data = { 'name': 'new_name', 'descr': 'New description.', 'value': 322, } <NEW_LINE> response = self.current_client.delete(url, data) <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
Admin user can delete any Expense objects.
6259905c435de62698e9d434
class SignInPage(Handler): <NEW_LINE> <INDENT> def render_main(self, username="", error="", users=""): <NEW_LINE> <INDENT> self.render("signin.html", username=username, error=error, users=users) <NEW_LINE> <DEDENT> def get(self): <NEW_LINE> <INDENT> self.render_main() <NEW_LINE> <DEDENT> def post(self): <NEW_LINE> <INDENT> username = self.request.get("username") <NEW_LINE> password = self.request.get("password") <NEW_LINE> user = Users.by_name(str(username)) <NEW_LINE> if user: <NEW_LINE> <INDENT> passwordHash = user.password <NEW_LINE> userSalt = user.salt <NEW_LINE> userID = user.key().id() <NEW_LINE> <DEDENT> if not username and not password: <NEW_LINE> <INDENT> error = "username and password required" <NEW_LINE> self.render_main(error=error) <NEW_LINE> <DEDENT> elif username and not password: <NEW_LINE> <INDENT> error = "password required" <NEW_LINE> self.render_main(error=error) <NEW_LINE> <DEDENT> elif not username and password: <NEW_LINE> <INDENT> error = "username required" <NEW_LINE> self.render_main(error=error) <NEW_LINE> <DEDENT> elif not user: <NEW_LINE> <INDENT> error = "username does not exists" <NEW_LINE> self.render_main(error=error) <NEW_LINE> <DEDENT> elif passwordHash != make_pass_hash(password, userSalt): <NEW_LINE> <INDENT> error = "incorrect password" <NEW_LINE> self.render_main(error=error) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.response.headers.add_header('Set-Cookie', 'userID=%s' % make_cookie(userID)) <NEW_LINE> return self.redirect('/')
Sign In Page Handler
6259905c30dc7b76659a0d98
class ViewsTestCase(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.client = Client() <NEW_LINE> self.obj1 = TestModel.objects.create() <NEW_LINE> self.obj2 = TestModel.objects.create() <NEW_LINE> <DEDENT> def test_like(self): <NEW_LINE> <INDENT> response = self.client.get("/like/tests-testmodel/%s/1/" % self.obj1.id) <NEW_LINE> self.assertEqual(response.status_code, 302) <NEW_LINE> <DEDENT> def test_like_ajax(self): <NEW_LINE> <INDENT> response = self.client.get("/like/tests-testmodel/%s/1/" % self.obj2.id, HTTP_X_REQUESTED_WITH="XMLHttpRequest") <NEW_LINE> self.assertEqual(response.status_code, 200)
Liking cannot be done programatically since it is tied too closely to a request. Do through-the-web tests.
6259905cf7d966606f7493d0
class Config(xtask.Task): <NEW_LINE> <INDENT> def __init__(self, directory_path, *args): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.directory_path = xtask.parse_path(directory_path) <NEW_LINE> self.args = [xtask.task_variables_to_value(arg) for arg in args] <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> if not self.directory_path.exists(): <NEW_LINE> <INDENT> self._error("Location {} does not exist".format(self.directory_path)) <NEW_LINE> return False <NEW_LINE> <DEDENT> if (self.directory_path / "configure").is_file(): <NEW_LINE> <INDENT> args = ["./configure"] + self.args <NEW_LINE> <DEDENT> elif (self.directory_path / "config").is_file(): <NEW_LINE> <INDENT> args = ["./config"] + self.args <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._error("No configure file found in {}".format(self.directory_path)) <NEW_LINE> <DEDENT> self._info( "Calling '{}' in directory {}".format(" ".join(args), self.directory_path) ) <NEW_LINE> try: <NEW_LINE> <INDENT> results = subprocess.run( args, cwd=self.directory_path, capture_output=True, text=True, ) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> self._exception("An error occured during the call") <NEW_LINE> return False <NEW_LINE> <DEDENT> returncode = results.returncode <NEW_LINE> if returncode != 0: <NEW_LINE> <INDENT> self._error("Something went wrong during the configuration") <NEW_LINE> self._error(results.stderr) <NEW_LINE> return False <NEW_LINE> <DEDENT> return True
Invoke configure script inside a directory.
6259905cf548e778e596cbb9
class PocketException(Exception): <NEW_LINE> <INDENT> pass
Base class for all pocket exceptions http://getpocket.com/developer/docs/errors
6259905c4e4d562566373a37
class CDBHandlerCheck(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testConstructor(self): <NEW_LINE> <INDENT> h = Acspy.Common.CDBAccess.CDBhandler('target') <NEW_LINE> self.assertEqual('target', h.element_name) <NEW_LINE> self.assertEqual('', h.tempName) <NEW_LINE> self.assertEqual(0, len(h.return_values)) <NEW_LINE> <DEDENT> def testPlainElementNoAttr(self): <NEW_LINE> <INDENT> h = Acspy.Common.CDBAccess.CDBhandler('target') <NEW_LINE> xml.sax.parseString("<target>Text</target>", h) <NEW_LINE> self.assertEqual('target', h.element_name) <NEW_LINE> self.assertEqual('', h.tempName) <NEW_LINE> self.assertEqual(1, len(h.return_values)) <NEW_LINE> self.assertEqual({}, h.return_values[0]) <NEW_LINE> <DEDENT> def testPlainElementAttr(self): <NEW_LINE> <INDENT> h = Acspy.Common.CDBAccess.CDBhandler('target') <NEW_LINE> xml.sax.parseString("<target attr1='label' attr2='9.0'>Text</target>", h) <NEW_LINE> self.assertEqual('target', h.element_name) <NEW_LINE> self.assertEqual('', h.tempName) <NEW_LINE> self.assertEqual(1, len(h.return_values)) <NEW_LINE> self.assertEqual(2, len(h.return_values[0])) <NEW_LINE> self.assertEqual({'attr1': 'label', 'attr2': '9.0'}, h.return_values[0]) <NEW_LINE> <DEDENT> def testNestedElementNoAttr(self): <NEW_LINE> <INDENT> h = Acspy.Common.CDBAccess.CDBhandler('parent/target') <NEW_LINE> xml.sax.parseString("<parent><target>Text</target></parent>", h) <NEW_LINE> self.assertEqual('parent/target', h.element_name) <NEW_LINE> self.assertEqual('', h.tempName) <NEW_LINE> self.assertEqual(1, len(h.return_values)) <NEW_LINE> self.assertEqual({}, h.return_values[0]) <NEW_LINE> <DEDENT> def testNestedElementAttr(self): <NEW_LINE> <INDENT> h = Acspy.Common.CDBAccess.CDBhandler('parent/target') <NEW_LINE> xml.sax.parseString("<parent><target attr1='label' attr2='9.0'>Text</target></parent>", h) <NEW_LINE> self.assertEqual('parent/target', h.element_name) <NEW_LINE> self.assertEqual('', h.tempName) <NEW_LINE> self.assertEqual(1, len(h.return_values)) <NEW_LINE> self.assertEqual(2, len(h.return_values[0])) <NEW_LINE> self.assertEqual({'attr1': 'label', 'attr2': '9.0'}, h.return_values[0]) <NEW_LINE> <DEDENT> def testNestedWrongElementNoAttr(self): <NEW_LINE> <INDENT> h = Acspy.Common.CDBAccess.CDBhandler('parent/target') <NEW_LINE> xml.sax.parseString("<parent><target2>Text</target2></parent>", h) <NEW_LINE> self.assertEqual('parent/target', h.element_name) <NEW_LINE> self.assertEqual('', h.tempName) <NEW_LINE> self.assertEqual(0, len(h.return_values)) <NEW_LINE> <DEDENT> def testNestedWrongKeyNoAttr(self): <NEW_LINE> <INDENT> h = Acspy.Common.CDBAccess.CDBhandler('parent/target2') <NEW_LINE> xml.sax.parseString("<parent><target>Text</target></parent>", h) <NEW_LINE> self.assertEqual('parent/target2', h.element_name) <NEW_LINE> self.assertEqual('', h.tempName) <NEW_LINE> self.assertEqual(0, len(h.return_values))
Test of the CDBhandler class.
6259905c3cc13d1c6d466d70
class BreakOutsideLoop(Message): <NEW_LINE> <INDENT> message = '\'break\' outside loop'
Indicates a break statement outside of a while or for loop.
6259905c435de62698e9d435
class Alphabet(object): <NEW_LINE> <INDENT> def __init__(self, alphabet, max_size=300, eos=None, unk='', sos=None): <NEW_LINE> <INDENT> self.unk_char = unk <NEW_LINE> self.eos_char = eos <NEW_LINE> self.sos_char = sos <NEW_LINE> self.max_size = max_size <NEW_LINE> def dict_to_list(char_dict, max_size): <NEW_LINE> <INDENT> chars = list(char_dict.copy().keys()) <NEW_LINE> freqs = list(char_dict.copy().values()) <NEW_LINE> sorted_idx = np.argsort(freqs) <NEW_LINE> sorted_chars = [chars[ii] for ii in sorted_idx[::-1]] <NEW_LINE> max_size = min(max_size, len(sorted_chars)) <NEW_LINE> char_list = sorted_chars[:max_size] <NEW_LINE> return char_list <NEW_LINE> <DEDENT> if type(alphabet) is list: <NEW_LINE> <INDENT> self.char_list = alphabet <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.char_dict = pickle.load(open(alphabet, 'br'), encoding='utf-8') <NEW_LINE> self.char_list = dict_to_list(self.char_dict, self.max_size) <NEW_LINE> <DEDENT> seen = set() <NEW_LINE> seen_add = seen.add <NEW_LINE> self.char_list = [x for x in self.char_list if not (x in seen or seen_add(x))] <NEW_LINE> self.encode_dict = {char: i for i, char in enumerate(self.char_list)} <NEW_LINE> self.decode_dict = {i: char for i, char in enumerate(self.char_list)} <NEW_LINE> self.unk_id = len(self.encode_dict) <NEW_LINE> if self.eos_char is not None: <NEW_LINE> <INDENT> self.eos_id = len(self.decode_dict) + 1 <NEW_LINE> self.decode_dict[self.eos_id] = self.eos_char <NEW_LINE> <DEDENT> if self.sos_char is not None: <NEW_LINE> <INDENT> self.sos_id = len(self.decode_dict) + 1 <NEW_LINE> self.decode_dict[self.sos_id] = self.sos_char <NEW_LINE> <DEDENT> <DEDENT> def encode(self, string): <NEW_LINE> <INDENT> encoded = [self.encode_dict.get(c, self.unk_id) for c in string] <NEW_LINE> if self.eos_char: <NEW_LINE> <INDENT> encoded.append(self.eos_id) <NEW_LINE> <DEDENT> return encoded <NEW_LINE> <DEDENT> def decode(self, seq): <NEW_LINE> <INDENT> str_sequence = [self.decode_dict.get(i, self.unk_char) for i in seq] <NEW_LINE> return ''.join(str_sequence)
Easily encode and decode strings using a set of characters.
6259905c38b623060ffaa367
class Channel: <NEW_LINE> <INDENT> def __init__(self, lines, offset, version, n_chan): <NEW_LINE> <INDENT> self.volt_range = struct.unpack('<H', lines[offset: offset + 2])[0] <NEW_LINE> offset += 2 <NEW_LINE> self.impedance = struct.unpack('<B', lines[offset:offset + 1])[0] <NEW_LINE> offset += 1 <NEW_LINE> if self.impedance == 0: <NEW_LINE> <INDENT> self.impedance_string = '1 MOhm' <NEW_LINE> <DEDENT> elif self.impedance == 1: <NEW_LINE> <INDENT> self.impedance_string = '50 Ohm' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('Unknown Impedance for Channel {:d}'.format(n_chan)) <NEW_LINE> <DEDENT> self.coupling = struct.unpack('<B', lines[offset:offset + 1])[0] <NEW_LINE> offset += 1 <NEW_LINE> if self.coupling == 0: <NEW_LINE> <INDENT> self.coupling_string = 'DC' <NEW_LINE> <DEDENT> elif self.coupling == 1: <NEW_LINE> <INDENT> self.coupling_string = 'AC' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('Unknown Coupling for Channel {:d}'.format(n_chan)) <NEW_LINE> <DEDENT> if version < 3.6: <NEW_LINE> <INDENT> offset += 27 <NEW_LINE> <DEDENT> self.offset = offset
Information about a channel.
6259905c4f6381625f199fba
class TestHtmlView(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testHtmlView(self): <NEW_LINE> <INDENT> model = flockos.models.html_view.HtmlView()
HtmlView unit test stubs
6259905c4e4d562566373a38
class TweetAnalyzer(): <NEW_LINE> <INDENT> def clean_tweet(self, tweet): <NEW_LINE> <INDENT> return ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)", " ", tweet).split()) <NEW_LINE> <DEDENT> def analyze_sentiment(self, tweet): <NEW_LINE> <INDENT> analysis = TextBlob(self.clean_tweet(tweet)) <NEW_LINE> if analysis.sentiment.polarity > 0: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> elif analysis.sentiment.polarity == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> <DEDENT> def tweets_to_data_frame(self, tweets): <NEW_LINE> <INDENT> df = pd.DataFrame([tweet.full_text for tweet in tweets], columns=['tweets']) <NEW_LINE> df['id'] = np.array([tweet.id for tweet in tweets]) <NEW_LINE> df['len'] = np.array([len(tweet.full_text) for tweet in tweets]) <NEW_LINE> df['date'] = np.array([tweet.created_at for tweet in tweets]) <NEW_LINE> df['source'] = np.array([tweet.source for tweet in tweets]) <NEW_LINE> df['likes'] = np.array([tweet.favorite_count for tweet in tweets]) <NEW_LINE> df['retweets'] = np.array([tweet.retweet_count for tweet in tweets]) <NEW_LINE> df['sentiment'] = np.array([self.analyze_sentiment(tweet) for tweet in df['tweets']]) <NEW_LINE> df['polarity']=np.array([self.Polarity(tweet) for tweet in df['tweets']]) <NEW_LINE> df['subjectivity']=np.array([self.subjectivity(tweet) for tweet in df['tweets']]) <NEW_LINE> return df <NEW_LINE> <DEDENT> def Polarity(self, tweet): <NEW_LINE> <INDENT> analysis = TextBlob(self.clean_tweet(tweet)) <NEW_LINE> polarity = analysis.sentiment.polarity <NEW_LINE> return polarity <NEW_LINE> <DEDENT> def subjectivity(self, tweet): <NEW_LINE> <INDENT> analysis = TextBlob(self.clean_tweet(tweet)) <NEW_LINE> subjectivity = analysis.sentiment.subjectivity <NEW_LINE> return subjectivity
Functionality for analyzing and categorizing content from tweets.
6259905c1b99ca400229004f
class Main(object): <NEW_LINE> <INDENT> def __init__(self, socket_port, db_file): <NEW_LINE> <INDENT> self.__socket_port = socket_port <NEW_LINE> self.__event = threading.Event() <NEW_LINE> self.__db_file = db_file <NEW_LINE> self.__socket = None <NEW_LINE> self.__prepare_socket() <NEW_LINE> self.__supervisor = None <NEW_LINE> repositories = Repositories(self.__db_file) <NEW_LINE> gpio_repository = repositories.get_gpio_repository() <NEW_LINE> gpios = gpio_repository.get_all_gpio() <NEW_LINE> SupervisorThread.gpios = gpios <NEW_LINE> Main.prepare_gpios(gpios) <NEW_LINE> <DEDENT> def listen_new_connection(self): <NEW_LINE> <INDENT> conn, client_address = self.__socket.accept() <NEW_LINE> connection = Connection(conn, (client_address[0], self.__socket_port), self.__event, self.__db_file) <NEW_LINE> connection.start() <NEW_LINE> if not self.__supervisor: <NEW_LINE> <INDENT> self.__supervisor = SupervisorThread(self.__event) <NEW_LINE> self.__supervisor.start() <NEW_LINE> <DEDENT> <DEDENT> def close_socket_connection(self): <NEW_LINE> <INDENT> print('Closing connections and threads...') <NEW_LINE> self.__socket.close() <NEW_LINE> self.__supervisor.stop() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def prepare_gpios(gpios): <NEW_LINE> <INDENT> for gpio in gpios: <NEW_LINE> <INDENT> service_path = os.path.dirname(os.path.realpath(__file__)) <NEW_LINE> script_path = os.path.join(service_path, 'lib', 'gpio_setup.sh') <NEW_LINE> gpio_status = '1' if gpio.is_inverted() else '0' <NEW_LINE> script = "sh " + script_path + " " + str(gpio.get_port()) + " " + gpio_status <NEW_LINE> try: <NEW_LINE> <INDENT> os.system(script) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> sys.stderr.write('On Gpio: ' + str(gpio.get_port()) + e.message) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __prepare_socket(self): <NEW_LINE> <INDENT> if not self.__socket: <NEW_LINE> <INDENT> self.__socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) <NEW_LINE> <DEDENT> server_address = ('', self.__socket_port) <NEW_LINE> self.__socket.bind(server_address) <NEW_LINE> self.__socket.listen(1)
Main class
6259905c8e71fb1e983bd0fa
class HostTimeStamp: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.pid = b'\x1B' <NEW_LINE> self.cnt = b'\x01' <NEW_LINE> self.payload_len = int2bytearray(16, 2) <NEW_LINE> self.device_ts = b'\x00\x00\x00\x00' <NEW_LINE> self.host_ts = None <NEW_LINE> self.fletcher = b'\xFF\xFF\xFF\xFF' <NEW_LINE> <DEDENT> def translate(self): <NEW_LINE> <INDENT> timestamp = int(time.time() + time.localtime().tm_gmtoff) <NEW_LINE> self.host_ts = int2bytearray(timestamp, 8) <NEW_LINE> return self.pid + self.cnt + self.payload_len + self.device_ts + self.host_ts + self.fletcher <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "Host timestamp"
Host timestamp data packet
6259905c15baa723494635c2
@pom.register_pages(pages.pages) <NEW_LINE> class Application(pom.App): <NEW_LINE> <INDENT> def __init__(self, url, *args, **kwgs): <NEW_LINE> <INDENT> super(Application, self).__init__( url, browser='Chrome', executable_path=config.CHROMEDRIVER_PATH, *args, **kwgs) <NEW_LINE> self.webdriver.maximize_window() <NEW_LINE> self.webdriver.set_window_size(*config.RESOLUTION) <NEW_LINE> self.webdriver.set_page_load_timeout(config.ACTION_TIMEOUT) <NEW_LINE> <DEDENT> def open(self, page): <NEW_LINE> <INDENT> url = page if isinstance(page, str) else page.url <NEW_LINE> super(Application, self).open(url) <NEW_LINE> <DEDENT> def flush_session(self): <NEW_LINE> <INDENT> self.webdriver.delete_all_cookies() <NEW_LINE> <DEDENT> @property <NEW_LINE> def current_page(self): <NEW_LINE> <INDENT> current_url = self.webdriver.current_url <NEW_LINE> current_url = self._remove_protocol(current_url) <NEW_LINE> app_url = self._remove_protocol(self.app_url) <NEW_LINE> for page in self._registered_pages: <NEW_LINE> <INDENT> if re.match(app_url + page.url, current_url): <NEW_LINE> <INDENT> return getattr(self, camel2snake(page.__name__)) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception("Can't define current page") <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def _remove_protocol(url): <NEW_LINE> <INDENT> return url.split('://', 1)[-1]
Application to launch IMDB in browser.
6259905c23849d37ff8526f6
class ConstructorMix(object): <NEW_LINE> <INDENT> def __init__(self, *args, **kwa): <NEW_LINE> <INDENT> cls = self.__class__ <NEW_LINE> for key, val in kwa.items(): <NEW_LINE> <INDENT> if self.__table__.columns.has_key(key): <NEW_LINE> <INDENT> setattr(self, key, val) <NEW_LINE> <DEDENT> elif hasattr(cls, key): <NEW_LINE> <INDENT> attr = getattr(cls, key) <NEW_LINE> if hasattr(attr, 'descriptor'): <NEW_LINE> <INDENT> if isinstance(getattr(attr, 'descriptor'), property): <NEW_LINE> <INDENT> setattr(self, key, val) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> logger.warning("Key `%s` was not found in model. Ignoring.")
This sets column values using constructor keyword args.
6259905c7d43ff2487427f28
class SHA1: <NEW_LINE> <INDENT> def getSHA1(self, token, timestamp, nonce, encrypt): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> sortlist = [token, timestamp, nonce, encrypt] <NEW_LINE> sortlist.sort() <NEW_LINE> sha = hashlib.sha1() <NEW_LINE> sha.update("".join(sortlist).encode("ascii")) <NEW_LINE> return ierror.WXBizMsgCrypt_OK, sha.hexdigest() <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print (e) <NEW_LINE> return ierror.WXBizMsgCrypt_ComputeSignature_Error, None
计算公众平台的消息签名接口
6259905c627d3e7fe0e084bc
class Marca(TimeStampedModel): <NEW_LINE> <INDENT> name = models.CharField( 'Nombre', max_length=30 ) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = 'Marca' <NEW_LINE> verbose_name_plural = 'Marcas' <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.name
Marca de un producto
6259905c0a50d4780f7068d7
class Quad(object): <NEW_LINE> <INDENT> def __init__(self, *args): <NEW_LINE> <INDENT> if not args: <NEW_LINE> <INDENT> raise InvalidIC('<null>') <NEW_LINE> <DEDENT> if args[0] not in QUADS.keys(): <NEW_LINE> <INDENT> errors.throw_invalid_quad_code(args[0]) <NEW_LINE> <DEDENT> if len(args) - 1 != QUADS[args[0]][0]: <NEW_LINE> <INDENT> errors.throw_invalid_quad_params(args[0], len(args) - 1) <NEW_LINE> <DEDENT> args = tuple([str(x) for x in args]) <NEW_LINE> self.quad = args <NEW_LINE> self.op = args[0] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.quad)
Implements a Quad code instruction.
6259905c3617ad0b5ee0777c
class GadgetbridgeDatabase: <NEW_LINE> <INDENT> def __init__(self, filename, device): <NEW_LINE> <INDENT> self._db_filename = filename <NEW_LINE> self._db = sqlite3.connect(self._db_filename) <NEW_LINE> self._cursor = self._db.cursor() <NEW_LINE> self.results = ResultIterator(self._cursor) <NEW_LINE> self._query('SELECT name FROM sqlite_master WHERE type="table";') <NEW_LINE> self.tables = [x[0] for x in self.results.all()] <NEW_LINE> self.device = device <NEW_LINE> self._db_names = device_db_mapping[self.device] <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> self._cursor.close() <NEW_LINE> self._db.close() <NEW_LINE> <DEDENT> def _query(self, querystring): <NEW_LINE> <INDENT> self._cursor.execute(querystring) <NEW_LINE> <DEDENT> def query_tableinfo(self, table_name): <NEW_LINE> <INDENT> if table_name in self.tables: <NEW_LINE> <INDENT> self.query('pragma table_info({table_name:s});'.format( table_name=table_name)) <NEW_LINE> res = {'name': [], 'type': [], 'index': []} <NEW_LINE> for row in self.results: <NEW_LINE> <INDENT> res['index'].append(row[0]) <NEW_LINE> res['name'].append(row[1]) <NEW_LINE> res['type'].append(row[2]) <NEW_LINE> <DEDENT> return res <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def _build_querystring(self, dataset, timestamp_min=None, timestamp_max=None): <NEW_LINE> <INDENT> restrictions = [] <NEW_LINE> if not timestamp_min is None: <NEW_LINE> <INDENT> val = str(int(time.mktime(timestamp_min.timetuple()))) <NEW_LINE> restrictions.append([self._db_names['timestamp'], '>=', val]) <NEW_LINE> <DEDENT> if not timestamp_max is None: <NEW_LINE> <INDENT> val = str(int(time.mktime(timestamp_max.timetuple()))) <NEW_LINE> restrictions.append([self._db_names['timestamp'], '<', val]) <NEW_LINE> <DEDENT> query_template = 'SELECT {dataset_col:s} FROM {table:s}' <NEW_LINE> dataset_cols = self._db_names['timestamp'] + ', ' + self._db_names[dataset] <NEW_LINE> res = query_template.format(dataset_col=dataset_cols, table=self._db_names['table']) <NEW_LINE> if len(restrictions) != 0: <NEW_LINE> <INDENT> field, operator, limit = restrictions[0] <NEW_LINE> query_restrictions = ' WHERE ' + field + ' ' + operator + ' ' + limit <NEW_LINE> for field, operator, limit in restrictions[1:]: <NEW_LINE> <INDENT> query_restrictions += ' AND ' + field + ' ' + operator + ' ' + limit <NEW_LINE> <DEDENT> res += query_restrictions <NEW_LINE> <DEDENT> return res + ';' <NEW_LINE> <DEDENT> def query_dataset(self, dataset, timestamp_min=None, timestamp_max=None): <NEW_LINE> <INDENT> datasets = self._db_names.keys() <NEW_LINE> datasets.remove('table') <NEW_LINE> datasets.remove('timestamp') <NEW_LINE> if not dataset in datasets: <NEW_LINE> <INDENT> raise LookupError('Dataset not available, must be in ' + str(datasets)) <NEW_LINE> <DEDENT> self._query(self._build_querystring(dataset, timestamp_min=timestamp_min, timestamp_max=timestamp_max)) <NEW_LINE> <DEDENT> def retrieve_dataset(self, dataset, timestamp_min=None, timestamp_max=None, time_resolution=None): <NEW_LINE> <INDENT> self.query_dataset(dataset, timestamp_min=timestamp_min, timestamp_max=timestamp_max) <NEW_LINE> res = DatasetContainer(dataset, time_resolution=time_resolution) <NEW_LINE> for ts, val in self.results: <NEW_LINE> <INDENT> res.append(datetime.fromtimestamp(ts), val) <NEW_LINE> <DEDENT> return res
Provides a simple abstraction layer around the Sqlite DB.
6259905ca8370b77170f19fe
class Config(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.items = {} <NEW_LINE> <DEDENT> def has(self, key): <NEW_LINE> <INDENT> return True if self._dot(key, False) is not False else False <NEW_LINE> <DEDENT> def get(self, key, default=None): <NEW_LINE> <INDENT> if isinstance(key, list): <NEW_LINE> <INDENT> return self.get_many(key) <NEW_LINE> <DEDENT> return self._dot(key, default) <NEW_LINE> <DEDENT> def all(self): <NEW_LINE> <INDENT> return self.items <NEW_LINE> <DEDENT> def get_many(self, keys): <NEW_LINE> <INDENT> return { key: self._dot(key, default) for key, default in keys } <NEW_LINE> <DEDENT> def _dot(self, path, default): <NEW_LINE> <INDENT> arr = self.items <NEW_LINE> keys = path.split('.') <NEW_LINE> for key in keys: <NEW_LINE> <INDENT> arr = arr.get(key, default) <NEW_LINE> if not isinstance(arr, dict): <NEW_LINE> <INDENT> return arr <NEW_LINE> <DEDENT> <DEDENT> return arr <NEW_LINE> <DEDENT> def set(self, key, value=None): <NEW_LINE> <INDENT> def set_to(items, data): <NEW_LINE> <INDENT> item = items.pop(0) <NEW_LINE> if items: <NEW_LINE> <INDENT> if item not in data: <NEW_LINE> <INDENT> data[item] = {} <NEW_LINE> <DEDENT> set_to(items, data[item]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> data[item] = value <NEW_LINE> <DEDENT> <DEDENT> if isinstance(key, str): <NEW_LINE> <INDENT> set_to(key.split('.'), self.items) <NEW_LINE> <DEDENT> elif isinstance(key, dict): <NEW_LINE> <INDENT> self.items.update(key)
Manages all the config items. Attributes: items (dict): Loaded config items.
6259905c2c8b7c6e89bd4e1f
class TwoFactorAuthenticationModelResponse(object): <NEW_LINE> <INDENT> _names = { "key" : "key", "uid" : "uid", "to" : "to" } <NEW_LINE> def __init__(self, key=None, uid=None, to=None, additional_properties = {}): <NEW_LINE> <INDENT> self.key = key <NEW_LINE> self.uid = uid <NEW_LINE> self.to = to <NEW_LINE> self.additional_properties = additional_properties <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_dictionary(cls, dictionary): <NEW_LINE> <INDENT> if dictionary is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> key = dictionary.get("key") <NEW_LINE> uid = dictionary.get("uid") <NEW_LINE> to = dictionary.get("to") <NEW_LINE> for key in cls._names.values(): <NEW_LINE> <INDENT> if key in dictionary: <NEW_LINE> <INDENT> del dictionary[key] <NEW_LINE> <DEDENT> <DEDENT> return cls(key, uid, to, dictionary)
Implementation of the 'Two Factor Authentication Model Response' model. TODO: type model description here. Attributes: key (string): TODO: type description here. uid (string): TODO: type description here. to (string): TODO: type description here.
6259905ce64d504609df9ee7
class Linear(object): <NEW_LINE> <INDENT> def __init__(self, start, end): <NEW_LINE> <INDENT> self.start = start <NEW_LINE> self.end = end <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, Line): <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> return not self == other <NEW_LINE> <DEDENT> def point(self, pos): <NEW_LINE> <INDENT> distance = self.end - self.start <NEW_LINE> return self.start + distance * pos <NEW_LINE> <DEDENT> def length(self, error=None, min_depth=None): <NEW_LINE> <INDENT> distance = self.end - self.start <NEW_LINE> return sqrt(distance.real ** 2 + distance.imag ** 2)
A straight line The base for Line() and Close().
6259905d76e4537e8c3f0bbe
class LogoutHandler(BaseHandler): <NEW_LINE> <INDENT> def get(self): <NEW_LINE> <INDENT> cuser=self.get_current_user() <NEW_LINE> ip=self.request.remote_ip <NEW_LINE> self.clear_current_user() <NEW_LINE> goto=self.get_argument("next","/") <NEW_LINE> at=time.strftime("%Y-%m-%d %X",time.localtime()) <NEW_LINE> upsql="update userstatus set ip='%s',time='%s' where id='%d'"%(ip,at,cuser.id) <NEW_LINE> self.db.execute(upsql) <NEW_LINE> self.redirect(goto)
logout website
6259905d8e7ae83300eea6bf
class FilebeatCharm(CharmBase): <NEW_LINE> <INDENT> def __init__(self, *args): <NEW_LINE> <INDENT> super().__init__(*args) <NEW_LINE> self._elastic_ops_manager = ElasticOpsManager("filebeat") <NEW_LINE> event_handler_bindings = { self.on.install: self._on_install, self.on.start: self._on_start, self.on.upgrade_charm: self._on_upgrade_charm, self.on.config_changed: self._on_handle_config, } <NEW_LINE> for event, handler in event_handler_bindings.items(): <NEW_LINE> <INDENT> self.framework.observe(event, handler) <NEW_LINE> <DEDENT> <DEDENT> def _on_install(self, event): <NEW_LINE> <INDENT> resource = self.model.resources.fetch('elastic-resource') <NEW_LINE> self._elastic_ops_manager.install(resource) <NEW_LINE> self.unit.status = ActiveStatus("Filebeat installed") <NEW_LINE> <DEDENT> def _on_start(self, event): <NEW_LINE> <INDENT> self._elastic_ops_manager.start_elastic_service() <NEW_LINE> self.unit.status = ActiveStatus("Filebeat available") <NEW_LINE> <DEDENT> def _on_upgrade_charm(self, event): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def _on_handle_config(self, event): <NEW_LINE> <INDENT> ctxt = { 'logging_hosts': [], 'logpath': self.model.config.get('logpath').split(" ") } <NEW_LINE> user_provided_logging_hosts = self.model.config.get('logging-hosts') <NEW_LINE> if user_provided_logging_hosts: <NEW_LINE> <INDENT> ctxt['logging_hosts'] = user_provided_logging_hosts.split(",") <NEW_LINE> <DEDENT> self._elastic_ops_manager.render_config_and_restart(ctxt)
Filebeat charm.
6259905d10dbd63aa1c72193
class AssertionError(Exception): <NEW_LINE> <INDENT> pass
AssertionError.
6259905c7047854f463409f1
class Comments(Page): <NEW_LINE> <INDENT> id = "edit-comments" <NEW_LINE> title = _(u"Comments") <NEW_LINE> description = _(u"Manage your comments") <NEW_LINE> content_template_name = "editcomments.pt"
Dashboard page
6259905d462c4b4f79dbd037
class _vivante(Structure): <NEW_LINE> <INDENT> _fields_ = [("display", c_void_p), ("window", c_void_p)]
Window information for Vivante.
6259905df7d966606f7493d1
class TestModelTransactionalTestCase(TestModelMixin, TransactionTestCase): <NEW_LINE> <INDENT> pass
A TestCase Similar to `TestModelTestCase` but with transaction support.
6259905d16aa5153ce401b15
class Meta: <NEW_LINE> <INDENT> model = Ride <NEW_LINE> exclude = ('offered_in', 'passengers', 'rating', 'is_active')
Meta class
6259905d435de62698e9d436
class _Action(object): <NEW_LINE> <INDENT> _command = None <NEW_LINE> _arguments = None <NEW_LINE> check_hangup = True <NEW_LINE> def __init__(self, command, *arguments): <NEW_LINE> <INDENT> self._command = command <NEW_LINE> self._arguments = arguments <NEW_LINE> <DEDENT> @property <NEW_LINE> def command(self): <NEW_LINE> <INDENT> command = ' '.join([self._command.strip()] + [str(arg) for arg in self._arguments if not arg is None]).strip() <NEW_LINE> if not command.endswith('\n'): <NEW_LINE> <INDENT> command += '\n' <NEW_LINE> <DEDENT> return command <NEW_LINE> <DEDENT> def process_response(self, response): <NEW_LINE> <INDENT> return response
Provides the basis for assembling and issuing an action via AGI.
6259905d99cbb53fe6832512
class TimedCache(AbstractCache): <NEW_LINE> <INDENT> def __init__(self, name, timeout, update_stamp=TRUE, cleanup_threshold=100): <NEW_LINE> <INDENT> super(TimedCache, self).__init__(name) <NEW_LINE> self.timeout = timeout <NEW_LINE> self.update_stamp = update_stamp <NEW_LINE> self.cleanup_threshold = cleanup_threshold <NEW_LINE> self.cache = {} <NEW_LINE> <DEDENT> def cleanup(self): <NEW_LINE> <INDENT> now = time.time() <NEW_LINE> for x in self.cache.keys(): <NEW_LINE> <INDENT> if now - self.cache[x][0] > self.timeout: <NEW_LINE> <INDENT> del self.cache[x] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def lookup(self, key): <NEW_LINE> <INDENT> if len(self.cache) > self.cleanup_threshold: <NEW_LINE> <INDENT> self.cleanup() <NEW_LINE> <DEDENT> if self.cache.has_key(key): <NEW_LINE> <INDENT> entry = self.cache[key] <NEW_LINE> if time.time() - entry[0] > self.timeout: <NEW_LINE> <INDENT> del self.cache[key] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self.update_stamp: <NEW_LINE> <INDENT> entry[0] = time.time() <NEW_LINE> <DEDENT> return entry[1] <NEW_LINE> <DEDENT> <DEDENT> return None <NEW_LINE> <DEDENT> def store(self, key, value): <NEW_LINE> <INDENT> if value: <NEW_LINE> <INDENT> if not self.cache.has_key(key) or self.cache[key][1] != value: <NEW_LINE> <INDENT> self.cache[key] = [time.time(), value] <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> del self.cache[key] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def clear(self): <NEW_LINE> <INDENT> self.cache = {}
<class internal="yes"> </class>
6259905d7d847024c075da03
class CreateRadFolder(QueenbeeTask): <NEW_LINE> <INDENT> _input_params = luigi.DictParameter() <NEW_LINE> @property <NEW_LINE> def view_filter(self): <NEW_LINE> <INDENT> return self._input_params['view_filter'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def input_model(self): <NEW_LINE> <INDENT> value = pathlib.Path(self._input_params['model']) <NEW_LINE> return value.as_posix() if value.is_absolute() else pathlib.Path(self.initiation_folder, value).resolve().as_posix() <NEW_LINE> <DEDENT> @property <NEW_LINE> def execution_folder(self): <NEW_LINE> <INDENT> return pathlib.Path(self._input_params['simulation_folder']).as_posix() <NEW_LINE> <DEDENT> @property <NEW_LINE> def initiation_folder(self): <NEW_LINE> <INDENT> return pathlib.Path(self._input_params['simulation_folder']).as_posix() <NEW_LINE> <DEDENT> @property <NEW_LINE> def params_folder(self): <NEW_LINE> <INDENT> return pathlib.Path(self.initiation_folder, self._input_params['params_folder']).resolve().as_posix() <NEW_LINE> <DEDENT> def command(self): <NEW_LINE> <INDENT> return 'honeybee-radiance translate model-to-rad-folder model.hbjson --view "{view_filter}" --view-check'.format(view_filter=self.view_filter) <NEW_LINE> <DEDENT> def output(self): <NEW_LINE> <INDENT> return { 'model_folder': luigi.LocalTarget( pathlib.Path(self.execution_folder, 'model').resolve().as_posix() ), 'bsdf_folder': luigi.LocalTarget( pathlib.Path(self.execution_folder, 'model/bsdf').resolve().as_posix() ), 'views_file': luigi.LocalTarget( pathlib.Path(self.execution_folder, 'results/views_info.json').resolve().as_posix() ), 'views': luigi.LocalTarget( pathlib.Path( self.params_folder, 'model/view/_info.json').resolve().as_posix() ) } <NEW_LINE> <DEDENT> @property <NEW_LINE> def input_artifacts(self): <NEW_LINE> <INDENT> return [ {'name': 'input_model', 'to': 'model.hbjson', 'from': self.input_model, 'optional': False}] <NEW_LINE> <DEDENT> @property <NEW_LINE> def output_artifacts(self): <NEW_LINE> <INDENT> return [ { 'name': 'model-folder', 'from': 'model', 'to': pathlib.Path(self.execution_folder, 'model').resolve().as_posix(), 'optional': False, 'type': 'folder' }, { 'name': 'bsdf-folder', 'from': 'model/bsdf', 'to': pathlib.Path(self.execution_folder, 'model/bsdf').resolve().as_posix(), 'optional': True, 'type': 'folder' }, { 'name': 'views-file', 'from': 'model/view/_info.json', 'to': pathlib.Path(self.execution_folder, 'results/views_info.json').resolve().as_posix(), 'optional': False, 'type': 'file' }] <NEW_LINE> <DEDENT> @property <NEW_LINE> def output_parameters(self): <NEW_LINE> <INDENT> return [{'name': 'views', 'from': 'model/view/_info.json', 'to': pathlib.Path(self.params_folder, 'model/view/_info.json').resolve().as_posix()}]
Create a Radiance folder from a HBJSON input file.
6259905d24f1403a926863e7
class Option(object): <NEW_LINE> <INDENT> __slots__ = ["__name", "__value", "__otype"] <NEW_LINE> def __init__(self, value, otype): <NEW_LINE> <INDENT> self.__otype = otype <NEW_LINE> self.value = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def value(self): <NEW_LINE> <INDENT> return self.__value <NEW_LINE> <DEDENT> @value.setter <NEW_LINE> def value(self, new_value): <NEW_LINE> <INDENT> if self.__otype == OptionType.NUMBER and not (isinstance(new_value, int) or isinstance(new_value, float)): <NEW_LINE> <INDENT> raise OptionException("attemped to set value to incorrect type") <NEW_LINE> <DEDENT> if self.__otype == OptionType.NUMBER and (new_value == True or new_value == False): <NEW_LINE> <INDENT> raise OptionException("attemped to set value to incorrect type") <NEW_LINE> <DEDENT> if self.__otype == OptionType.BOOL and not isinstance(new_value, bool): <NEW_LINE> <INDENT> raise OptionException("attemped to set value to incorrect type") <NEW_LINE> <DEDENT> if self.__otype == OptionType.STRING and not isinstance(new_value, str): <NEW_LINE> <INDENT> raise OptionException("attemped to set value to incorrect type") <NEW_LINE> <DEDENT> self.__value = new_value
stores the an option for a class dervived from Base. contains both its value and type(value) to ensure that an option is not set to some bizzare value. Option objects should not be generated directly but will be made in an Options object that each class dervived from Base should contain :param value: the value of a given option to be stored :param otype: the type of the value :type value: unknown :type otype: Type object Attributes ---------- `value` : Unknown type the value of the option to be stored `otype` : Type object the type of a given value
6259905dadb09d7d5dc0bb9c
class M: <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def do_nothing(): <NEW_LINE> <INDENT> return None
A Method Resolution Order Used To Describe Inheritance Properties From A Parent Class Towards Child-Classes.
6259905d4a966d76dd5f0524
class Strain(models.Model): <NEW_LINE> <INDENT> nomenclature = models.CharField( primary_key=True, max_length=100 ) <NEW_LINE> label = models.CharField( max_length=50, null=True, blank=True ) <NEW_LINE> species = models.ForeignKey( Species ) <NEW_LINE> url = models.URLField( null=True, blank=True, help_text="web page describing the strain" ) <NEW_LINE> notes = models.TextField( null=True, blank=True ) <NEW_LINE> class Meta : <NEW_LINE> <INDENT> ordering = ['species__english_name', 'label'] <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> st = "%s - %s" % (self.species, self.nomenclature) <NEW_LINE> if self.label : <NEW_LINE> <INDENT> st += " (%s)" % (self.label) <NEW_LINE> <DEDENT> return st <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.__unicode__()
Strain of a subject.
6259905d4e4d562566373a39
class ProbCheck(object): <NEW_LINE> <INDENT> def __init__(self, prob): <NEW_LINE> <INDENT> if isinstance(prob, dict): <NEW_LINE> <INDENT> self._prob = prob.items() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._prob = prob <NEW_LINE> <DEDENT> <DEDENT> def __call__(self, hour_of_day): <NEW_LINE> <INDENT> if isinstance(self._prob, list): <NEW_LINE> <INDENT> p = math.interpolate_1d(self._prob, hour_of_day) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> p = self._prob <NEW_LINE> <DEDENT> return random.random() < p
Function object to randomly return True or False with probability This function object randomly returns true or false with a chance of success that can optionally vary given the hour of the day.
6259905d498bea3a75a59116
class TimeoutException(AnnotationException): <NEW_LINE> <INDENT> pass
Exception raised when the CoreNLP server timed out.
6259905d9c8ee82313040ca3
class PrefixMiddleware(object): <NEW_LINE> <INDENT> def __init__(self, app, prefix=''): <NEW_LINE> <INDENT> self.app = app <NEW_LINE> self.prefix = prefix <NEW_LINE> <DEDENT> def __call__(self, environ, start_response): <NEW_LINE> <INDENT> if environ['PATH_INFO'].startswith(self.prefix): <NEW_LINE> <INDENT> environ['PATH_INFO'] = environ['PATH_INFO'][len(self.prefix):] <NEW_LINE> environ['SCRIPT_NAME'] = self.prefix <NEW_LINE> return self.app(environ, start_response) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> start_response('404', [('Content-Type', 'text/plain')]) <NEW_LINE> return ["This url does not belong to the app.".encode()]
Class to enable serving the app from a prefix
6259905d0c0af96317c57878
class GroupLine(dataLine): <NEW_LINE> <INDENT> def __init__(self,_root,_parent,_name): <NEW_LINE> <INDENT> dataLine.__init__(self, _root, _parent, _name) <NEW_LINE> self.expanded = False <NEW_LINE> self.toggle_button = Button(self,text='- '+_name,command=self.toggleCollapse,anchor="w") <NEW_LINE> self.childElements = [] <NEW_LINE> self.update() <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> if self.expanded: <NEW_LINE> <INDENT> self.toggle_button.config(text='- '+self.display_name.get()) <NEW_LINE> self.toggle_button.config(relief=SUNKEN) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.toggle_button.config(text='+ '+self.display_name.get()) <NEW_LINE> self.toggle_button.config(relief=RAISED) <NEW_LINE> <DEDENT> self.packChildren() <NEW_LINE> <DEDENT> def pack(self, cnf={}, **kw): <NEW_LINE> <INDENT> for child in self.childElements: <NEW_LINE> <INDENT> child.pack_forget() <NEW_LINE> <DEDENT> dataLine.pack(self, cnf=cnf, **kw) <NEW_LINE> if self.expanded: <NEW_LINE> <INDENT> for child in self.childElements: <NEW_LINE> <INDENT> child.pack(cnf=cnf,**kw) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def packChildren(self): <NEW_LINE> <INDENT> self.toggle_button.pack(side=LEFT,fill=BOTH,expand=TRUE) <NEW_LINE> <DEDENT> def toggleCollapse(self): <NEW_LINE> <INDENT> self.expanded = not self.expanded <NEW_LINE> self.update() <NEW_LINE> self.root.loadDataList()
A group selector has an expand/collapse button to view or hide its children.
6259905d7b25080760ed87f9
class Profiler(object): <NEW_LINE> <INDENT> timer = None <NEW_LINE> stats = None <NEW_LINE> top_frame = None <NEW_LINE> top_code = None <NEW_LINE> _running = False <NEW_LINE> def __init__(self, timer=None, top_frame=None, top_code=None): <NEW_LINE> <INDENT> if timer is None: <NEW_LINE> <INDENT> timer = Timer() <NEW_LINE> <DEDENT> self.timer = timer <NEW_LINE> self.top_frame = top_frame <NEW_LINE> self.top_code = top_code <NEW_LINE> self.clear() <NEW_LINE> <DEDENT> def result(self): <NEW_LINE> <INDENT> return FrozenStatistics(self.stats) <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> if sys.getprofile() is not None: <NEW_LINE> <INDENT> raise RuntimeError('Another profiler already registered.') <NEW_LINE> <DEDENT> self._running = True <NEW_LINE> sys.setprofile(self._profile) <NEW_LINE> threading.setprofile(self._profile) <NEW_LINE> self.timer.start() <NEW_LINE> self.stats.record_starting(time.clock()) <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> self.stats.record_stopping(time.clock()) <NEW_LINE> self.timer.stop() <NEW_LINE> threading.setprofile(None) <NEW_LINE> sys.setprofile(None) <NEW_LINE> self._running = False <NEW_LINE> <DEDENT> def is_running(self): <NEW_LINE> <INDENT> return self._running <NEW_LINE> <DEDENT> def clear(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.stats.clear() <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> self.stats = RecordingStatistics() <NEW_LINE> <DEDENT> <DEDENT> if speedup: <NEW_LINE> <INDENT> def _frame_stack(self, frame): <NEW_LINE> <INDENT> return speedup.frame_stack(frame, self.top_frame, self.top_code) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> def _frame_stack(self, frame): <NEW_LINE> <INDENT> frame_stack = deque() <NEW_LINE> top_frame = self.top_frame <NEW_LINE> top_code = self.top_code <NEW_LINE> while frame is not None: <NEW_LINE> <INDENT> frame_stack.appendleft(frame) <NEW_LINE> if frame is top_frame or frame.f_code is top_code: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> frame = frame.f_back <NEW_LINE> <DEDENT> return frame_stack <NEW_LINE> <DEDENT> <DEDENT> def _profile(self, frame, event, arg): <NEW_LINE> <INDENT> time = self.timer() <NEW_LINE> if event.startswith('c_'): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> frame_stack = self._frame_stack(frame) <NEW_LINE> frame_stack.pop() <NEW_LINE> if not frame_stack: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> parent_stat = self.stats <NEW_LINE> for f in frame_stack: <NEW_LINE> <INDENT> parent_stat = parent_stat.ensure_child(f.f_code) <NEW_LINE> <DEDENT> code = frame.f_code <NEW_LINE> frame_key = id(frame) <NEW_LINE> if event in ('call',): <NEW_LINE> <INDENT> time = self.timer() <NEW_LINE> self._entered(time, code, frame_key, parent_stat) <NEW_LINE> <DEDENT> elif event in ('return', 'exception'): <NEW_LINE> <INDENT> self._left(time, code, frame_key, parent_stat) <NEW_LINE> <DEDENT> <DEDENT> def _entered(self, time, code, frame_key, parent_stat): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> stat = parent_stat.get_child(code) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> stat = RecordingStat(code) <NEW_LINE> parent_stat.add_child(code, stat) <NEW_LINE> <DEDENT> stat.record_entering(time, frame_key) <NEW_LINE> <DEDENT> def _left(self, time, code, frame_key, parent_stat): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> stat = parent_stat.get_child(code) <NEW_LINE> stat.record_leaving(time, frame_key) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass
The profiler.
6259905d0a50d4780f7068d8
class PublicIPAddressDnsSettings(Model): <NEW_LINE> <INDENT> _attribute_map = { 'domain_name_label': {'key': 'domainNameLabel', 'type': 'str'}, 'fqdn': {'key': 'fqdn', 'type': 'str'}, 'reverse_fqdn': {'key': 'reverseFqdn', 'type': 'str'}, } <NEW_LINE> def __init__(self, *, domain_name_label: str=None, fqdn: str=None, reverse_fqdn: str=None, **kwargs) -> None: <NEW_LINE> <INDENT> super(PublicIPAddressDnsSettings, self).__init__(**kwargs) <NEW_LINE> self.domain_name_label = domain_name_label <NEW_LINE> self.fqdn = fqdn <NEW_LINE> self.reverse_fqdn = reverse_fqdn
Contains FQDN of the DNS record associated with the public IP address. :param domain_name_label: Gets or sets the Domain name label.The concatenation of the domain name label and the regionalized DNS zone make up the fully qualified domain name associated with the public IP address. If a domain name label is specified, an A DNS record is created for the public IP in the Microsoft Azure DNS system. :type domain_name_label: str :param fqdn: Gets the FQDN, Fully qualified domain name of the A DNS record associated with the public IP. This is the concatenation of the domainNameLabel and the regionalized DNS zone. :type fqdn: str :param reverse_fqdn: Gets or Sets the Reverse FQDN. A user-visible, fully qualified domain name that resolves to this public IP address. If the reverseFqdn is specified, then a PTR DNS record is created pointing from the IP address in the in-addr.arpa domain to the reverse FQDN. :type reverse_fqdn: str
6259905d01c39578d7f14250
class RemoteWebServer(): <NEW_LINE> <INDENT> def __init__(self, remote_url, connection_timeout=.25): <NEW_LINE> <INDENT> self.control_url = remote_url <NEW_LINE> self.time = 0. <NEW_LINE> self.angle = 0. <NEW_LINE> self.throttle = 0. <NEW_LINE> self.mode = 'user' <NEW_LINE> self.recording = False <NEW_LINE> self.session = requests.Session() <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> self.angle, self.throttle, self.mode, self.recording = self.run() <NEW_LINE> <DEDENT> <DEDENT> def run_threaded(self): <NEW_LINE> <INDENT> return self.angle, self.throttle, self.mode, self.recording <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> data = {} <NEW_LINE> response = None <NEW_LINE> while response == None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> response = self.session.post(self.control_url, files={'json': json.dumps(data)}, timeout=0.25) <NEW_LINE> <DEDENT> except (requests.exceptions.ReadTimeout) as err: <NEW_LINE> <INDENT> print("\n Request took too long. Retrying") <NEW_LINE> return self.angle, self.throttle * .8, None <NEW_LINE> <DEDENT> except (requests.ConnectionError) as err: <NEW_LINE> <INDENT> print("\n Vehicle could not connect to server. Make sure you've " + "started your server and you're referencing the right port.") <NEW_LINE> time.sleep(3) <NEW_LINE> <DEDENT> <DEDENT> data = json.loads(response.text) <NEW_LINE> angle = float(data['angle']) <NEW_LINE> throttle = float(data['throttle']) <NEW_LINE> drive_mode = str(data['drive_mode']) <NEW_LINE> recording = bool(data['recording']) <NEW_LINE> return angle, throttle, drive_mode, recording
A controller that repeatedly polls a remote webserver and expects the response to be angle, throttle and drive mode.
6259905d4428ac0f6e659b70
class ToTensor(object): <NEW_LINE> <INDENT> def __call__(self, sample): <NEW_LINE> <INDENT> left = np.transpose(sample['left'], (2, 0, 1)) <NEW_LINE> sample['left'] = torch.from_numpy(left) / 255. <NEW_LINE> right = np.transpose(sample['right'], (2, 0, 1)) <NEW_LINE> sample['right'] = torch.from_numpy(right) / 255. <NEW_LINE> if 'depth' in sample.keys(): <NEW_LINE> <INDENT> disp = np.transpose(sample['depth'], (2, 0, 1)) <NEW_LINE> sample['depth'] = torch.from_numpy(disp) <NEW_LINE> mask = np.transpose(sample['mask'], (2, 0, 1)) <NEW_LINE> sample['mask'] = torch.from_numpy(mask) <NEW_LINE> <DEDENT> if 'pseudo_disp' in sample.keys(): <NEW_LINE> <INDENT> disp = sample['pseudo_disp'] <NEW_LINE> sample['pseudo_disp'] = torch.from_numpy(disp) <NEW_LINE> <DEDENT> return sample
Convert numpy array to torch tensor
6259905dcc0a2c111447c5e8
class Battery(_Battery): <NEW_LINE> <INDENT> defaults = [ ('low_foreground', 'FF0000', 'font color when battery is low'), ( 'format', '{char} {percent:2.0%} {hour:d}:{min:02d}', 'Display format' ), ('charge_char', '^', 'Character to indicate the battery is charging'), ( 'discharge_char', 'V', 'Character to indicate the battery' ' is discharging' ), ( 'low_percentage', 0.10, "0 < x < 1 at which to indicate battery is low with low_foreground" ), ('hide_threshold', None, 'Hide the text when there is enough energy'), ] <NEW_LINE> def __init__(self, **config): <NEW_LINE> <INDENT> _Battery.__init__(self, **config) <NEW_LINE> self.add_defaults(Battery.defaults) <NEW_LINE> self.timeout_add(self.update_delay, self.update) <NEW_LINE> self.update() <NEW_LINE> <DEDENT> def _get_text(self): <NEW_LINE> <INDENT> info = self._get_info() <NEW_LINE> if info is False: <NEW_LINE> <INDENT> return 'Error' <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> if self.hide_threshold and info['now'] / info['full'] * 100.0 >= self.hide_threshold and info['stat'] != CHARGED: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> elif info['stat'] == DISCHARGING: <NEW_LINE> <INDENT> char = self.discharge_char <NEW_LINE> time = info['now'] / info['power'] <NEW_LINE> <DEDENT> elif info['stat'] == CHARGING: <NEW_LINE> <INDENT> char = self.charge_char <NEW_LINE> time = (info['full'] - info['now']) / info['power'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 'Full' <NEW_LINE> <DEDENT> <DEDENT> except ZeroDivisionError: <NEW_LINE> <INDENT> time = -1 <NEW_LINE> <DEDENT> if time >= 0: <NEW_LINE> <INDENT> hour = int(time) <NEW_LINE> min = int(time * 60) % 60 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> hour = -1 <NEW_LINE> min = -1 <NEW_LINE> <DEDENT> percent = info['now'] / info['full'] <NEW_LINE> if info['stat'] == DISCHARGING and percent < self.low_percentage: <NEW_LINE> <INDENT> self.layout.colour = self.low_foreground <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.layout.colour = self.foreground <NEW_LINE> <DEDENT> return self.format.format( char=char, percent=percent, hour=hour, min=min ) <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> if self.configured: <NEW_LINE> <INDENT> ntext = self._get_text() <NEW_LINE> if ntext != self.text: <NEW_LINE> <INDENT> self.text = ntext <NEW_LINE> self.bar.draw() <NEW_LINE> <DEDENT> <DEDENT> return True
A simple but flexible text-based battery widget.
6259905d3617ad0b5ee0777f
class IndividualTagsColumn(CommunityTagsColumn): <NEW_LINE> <INDENT> def get_value(self, trans, grid, item): <NEW_LINE> <INDENT> return trans.fill_template( "/tagging_common.mako", tag_type="individual", user=trans.user, tagged_item=item, elt_context=self.grid_name, tag_click_fn="add_tag_to_grid_filter", use_toggle_link=True, ) <NEW_LINE> <DEDENT> def get_filter(self, trans, user, column_filter): <NEW_LINE> <INDENT> if isinstance(column_filter, list): <NEW_LINE> <INDENT> column_filter = ",".join(column_filter) <NEW_LINE> <DEDENT> raw_tags = trans.app.tag_handler.parse_tags(column_filter) <NEW_LINE> clause_list = [] <NEW_LINE> for name, value in raw_tags: <NEW_LINE> <INDENT> if name: <NEW_LINE> <INDENT> clause_list.append( self.model_class.tags.any( and_( func.lower(self.model_tag_association_class.user_tname).like(f"%{name.lower()}%"), self.model_tag_association_class.user == user, ) ) ) <NEW_LINE> if value: <NEW_LINE> <INDENT> clause_list.append( self.model_class.tags.any( and_( func.lower(self.model_tag_association_class.user_value).like(f"%{value.lower()}%"), self.model_tag_association_class.user == user, ) ) ) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return and_(*clause_list)
Column that supports individual tags.
6259905d7047854f463409f3
class IRootDesigner(IDesigner, IDisposable): <NEW_LINE> <INDENT> def GetView(self, technology): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __enter__(self, *args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __exit__(self, *args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __init__(self, *args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> SupportedTechnologies = property(lambda self: object(), lambda self, v: None, lambda self: None)
Provides support for root-level designer view technologies.
6259905d3539df3088ecd8cf
class ATF_Temperature(base.Parser,instruments.ATF,experiments.Temperature): <NEW_LINE> <INDENT> pass
Processes an ATF Temperature experiment.
6259905df7d966606f7493d2
class ConverterDialogTest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.dialog = ConverterDialog(None) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> self.dialog = None <NEW_LINE> <DEDENT> def test_dialog_ok(self): <NEW_LINE> <INDENT> button = self.dialog.button_box.button(QDialogButtonBox.Ok) <NEW_LINE> button.click() <NEW_LINE> result = self.dialog.result() <NEW_LINE> self.assertEqual(result, QDialog.Accepted) <NEW_LINE> <DEDENT> def test_dialog_cancel(self): <NEW_LINE> <INDENT> button = self.dialog.button_box.button(QDialogButtonBox.Cancel) <NEW_LINE> button.click() <NEW_LINE> result = self.dialog.result() <NEW_LINE> self.assertEqual(result, QDialog.Rejected)
Test dialog works.
6259905dd99f1b3c44d06cd5
class AWS(Source): <NEW_LINE> <INDENT> BUCKET = "bucket" <NEW_LINE> REPORT_PREFIX = "report_prefix" <NEW_LINE> REPORT_NAME = "report_name" <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.kwargs = kwargs <NEW_LINE> self.access_key = os.environ.get("AWS_ACCESS_KEY_ID") <NEW_LINE> self.secret = os.environ.get("AWS_SECRET_ACCESS_KEY") <NEW_LINE> self.s3_bucket = kwargs.get(self.BUCKET) <NEW_LINE> self.report_prefix = kwargs.get(self.REPORT_PREFIX, "cur") <NEW_LINE> self.report_name = kwargs.get(self.REPORT_NAME, "cur") <NEW_LINE> self.static_file = kwargs.get(self.STATIC_FILE) <NEW_LINE> self.credentials = { "aws_access_key_id": self.access_key, "aws_secret_access_key": self.secret, } <NEW_LINE> self.s3_client = boto3.client("s3", **self.credentials) <NEW_LINE> super().__init__(**kwargs) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_source_type(): <NEW_LINE> <INDENT> return "AWS" <NEW_LINE> <DEDENT> def check_configuration(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.s3_client.head_bucket(Bucket=self.s3_bucket) <NEW_LINE> <DEDENT> except ClientError as err: <NEW_LINE> <INDENT> LOG.info(f"Error: {err}") <NEW_LINE> return False <NEW_LINE> <DEDENT> <DEDENT> def _get_existing_objects(self): <NEW_LINE> <INDENT> objects = None <NEW_LINE> response = self.s3_client.list_objects( Bucket=self.s3_bucket, Prefix=self.report_prefix ) <NEW_LINE> if response.get("Contents"): <NEW_LINE> <INDENT> objects = [ item.get("Key") for item in response.get("Contents", []) ] <NEW_LINE> <DEDENT> return objects <NEW_LINE> <DEDENT> def _delete_objects(self, objects_to_delete): <NEW_LINE> <INDENT> LOG.info( f"s3_bucket={self.s3_bucket} objects_to_delete={objects_to_delete}" ) <NEW_LINE> if objects_to_delete: <NEW_LINE> <INDENT> object_list = [{"Key": obj_name} for obj_name in objects_to_delete] <NEW_LINE> self.s3_client.delete_objects( Bucket=self.s3_bucket, Delete={"Objects": object_list} ) <NEW_LINE> <DEDENT> <DEDENT> def setup(self): <NEW_LINE> <INDENT> existing_objects = self._get_existing_objects() <NEW_LINE> self._delete_objects(existing_objects) <NEW_LINE> <DEDENT> def generate(self): <NEW_LINE> <INDENT> options = { "start_date": self.start_date, "end_date": self.end_date, "aws_bucket_name": self.s3_bucket, "aws_prefix_name": self.report_prefix, "aws_report_name": self.report_name, } <NEW_LINE> if self.static_file: <NEW_LINE> <INDENT> static_file_data = Source.obtain_static_file_data( self.static_file, self.start_date, self.end_date ) <NEW_LINE> options["static_report_data"] = static_file_data <NEW_LINE> <DEDENT> aws_create_report(options)
Defining the AWS source class.
6259905d99cbb53fe6832514
class ReplaySimulator(object): <NEW_LINE> <INDENT> def __init__(self, n_visits, reward_history, item_col_name, visitor_col_name, reward_col_name, n_iterations=1, random_seed=1): <NEW_LINE> <INDENT> np.random.seed(random_seed) <NEW_LINE> self.reward_history = reward_history <NEW_LINE> self.item_col_name = item_col_name <NEW_LINE> self.visitor_col_name = visitor_col_name <NEW_LINE> self.reward_col_name = reward_col_name <NEW_LINE> self.n_visits = n_visits <NEW_LINE> self.n_iterations = n_iterations <NEW_LINE> self.items = self.reward_history[self.item_col_name].unique() <NEW_LINE> self.n_items = len(self.items) <NEW_LINE> self.visitors = self.reward_history[self.visitor_col_name].unique() <NEW_LINE> self.n_visitors = len(self.visitors) <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self.n_item_samples = np.zeros(self.n_items) <NEW_LINE> self.n_item_rewards = np.zeros(self.n_items) <NEW_LINE> <DEDENT> def replay(self): <NEW_LINE> <INDENT> results = [] <NEW_LINE> for iteration in tqdm(range(0, self.n_iterations)): <NEW_LINE> <INDENT> self.reset() <NEW_LINE> total_rewards = 0 <NEW_LINE> fraction_relevant = np.zeros(self.n_visits) <NEW_LINE> for visit in range(0, self.n_visits): <NEW_LINE> <INDENT> found_match = False <NEW_LINE> while not found_match: <NEW_LINE> <INDENT> visitor_idx = np.random.randint(self.n_visitors) <NEW_LINE> visitor_id = self.visitors[visitor_idx] <NEW_LINE> item_idx = self.select_item() <NEW_LINE> item_id = self.items[item_idx] <NEW_LINE> reward = self.reward_history.query( '{} == @item_id and {} == @visitor_id'.format(self.item_col_name, self.visitor_col_name))[self.reward_col_name] <NEW_LINE> found_match = reward.shape[0] > 0 <NEW_LINE> <DEDENT> reward_value = reward.iloc[0] <NEW_LINE> self.record_result(visit, item_idx, reward_value) <NEW_LINE> total_rewards += reward_value <NEW_LINE> fraction_relevant[visit] = total_rewards * 1. / (visit + 1) <NEW_LINE> result = {} <NEW_LINE> result['iteration'] = iteration <NEW_LINE> result['visit'] = visit <NEW_LINE> result['item_id'] = item_id <NEW_LINE> result['visitor_id'] = visitor_id <NEW_LINE> result['reward'] = reward_value <NEW_LINE> result['total_reward'] = total_rewards <NEW_LINE> result['fraction_relevant'] = total_rewards * 1. / (visit + 1) <NEW_LINE> results.append(result) <NEW_LINE> <DEDENT> <DEDENT> return results <NEW_LINE> <DEDENT> def select_item(self): <NEW_LINE> <INDENT> return np.random.randint(self.n_items) <NEW_LINE> <DEDENT> def record_result(self, visit, item_idx, reward): <NEW_LINE> <INDENT> self.n_item_samples[item_idx] += 1 <NEW_LINE> alpha = 1./self.n_item_samples[item_idx] <NEW_LINE> self.n_item_rewards[item_idx] += alpha * (reward - self.n_item_rewards[item_idx])
A class to provide base functionality for simulating the replayer method for online algorithms.
6259905d16aa5153ce401b17
class DeleteFromCartView(CartMixin, View): <NEW_LINE> <INDENT> def get(self, request, *args, **kwargs): <NEW_LINE> <INDENT> product_slug = kwargs.get('slug') <NEW_LINE> product = Product.objects.get(slug=product_slug) <NEW_LINE> cart_product = CartProduct.objects.get( user=self.cart.owner, cart=self.cart, product=product ) <NEW_LINE> self.cart.products.remove(cart_product) <NEW_LINE> cart_product.delete() <NEW_LINE> recalc_cart(self.cart) <NEW_LINE> messages.add_message(request, messages.INFO, "Товар успешно удалён") <NEW_LINE> return HttpResponseRedirect('/cart/')
Удаление товаров из корзины
6259905df548e778e596cbbd
class TestPropertyExclusive(BaseRuleTestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(TestPropertyExclusive, self).setUp() <NEW_LINE> self.collection.register(Exclusive()) <NEW_LINE> <DEDENT> def test_file_positive(self): <NEW_LINE> <INDENT> self.helper_file_positive() <NEW_LINE> <DEDENT> def test_file_negative(self): <NEW_LINE> <INDENT> self.helper_file_negative('fixtures/templates/bad/properties_exclusive.yaml', 1)
Test Exclusive Property Configuration
6259905d097d151d1a2c26a2
class CreateDomainRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.ListenerId = None <NEW_LINE> self.Domain = None <NEW_LINE> self.CertificateId = None <NEW_LINE> self.ClientCertificateId = None <NEW_LINE> self.PolyClientCertificateIds = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.ListenerId = params.get("ListenerId") <NEW_LINE> self.Domain = params.get("Domain") <NEW_LINE> self.CertificateId = params.get("CertificateId") <NEW_LINE> self.ClientCertificateId = params.get("ClientCertificateId") <NEW_LINE> self.PolyClientCertificateIds = params.get("PolyClientCertificateIds")
CreateDomain请求参数结构体
6259905d379a373c97d9a658
class packet_header(IntEnum): <NEW_LINE> <INDENT> FILE_TRANSFER_HEADER = 0x00 <NEW_LINE> FILE_TRANSFER_DATA = 55
headers to identify Packets
6259905dadb09d7d5dc0bb9e
class ApplicationDefaults: <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def list(): <NEW_LINE> <INDENT> return []
Enumeration of default application settings
6259905d498bea3a75a59117
class HydraulicCoolingCost2015(om.ExplicitComponent): <NEW_LINE> <INDENT> def setup(self): <NEW_LINE> <INDENT> self.add_input("hvac_mass", 0.0, units="kg") <NEW_LINE> self.add_input("hvac_mass_cost_coeff", 124.0, units="USD/kg") <NEW_LINE> self.add_output("hvac_cost", 0.0, units="USD") <NEW_LINE> <DEDENT> def compute(self, inputs, outputs): <NEW_LINE> <INDENT> hvac_mass = inputs["hvac_mass"] <NEW_LINE> hvac_mass_cost_coeff = inputs["hvac_mass_cost_coeff"] <NEW_LINE> outputs["hvac_cost"] = hvac_mass_cost_coeff * hvac_mass
Compute hydraulic cooling cost in the form of :math:`cost = k*mass`. Value of :math:`k` was NOT updated in 2015 and remains the same as original CSM, $124.0 USD/kg. Cost includes materials and manufacturing costs. Parameters ---------- hvac_mass : float, [kg] component mass hvac_mass_cost_coeff : float, [USD/kg] hydraulic and cooling system mass cost coeff Returns ------- hvac_cost : float, [USD] HVAC cost
6259905d3cc13d1c6d466d74
class Message: <NEW_LINE> <INDENT> def __init__(self, author, sentence): <NEW_LINE> <INDENT> self.author = author <NEW_LINE> self.sentence = sentence <NEW_LINE> <DEDENT> def compilated_message(self): <NEW_LINE> <INDENT> return [self.author, self.sentence]
This class represents model of massage in talkbox
6259905dbe8e80087fbc06b8
class ToolEditorDrill(ToolEditorImage): <NEW_LINE> <INDENT> def __init__(self, editor): <NEW_LINE> <INDENT> super(self.__class__, self).__init__(editor, 'drill.svg', 'dS', '') <NEW_LINE> <DEDENT> def quantityCuttingEdgeAngle(self, propertyToDisplay): <NEW_LINE> <INDENT> if propertyToDisplay: <NEW_LINE> <INDENT> return FreeCAD.Units.Quantity(self.editor.tool.CuttingEdgeAngle, FreeCAD.Units.Angle) <NEW_LINE> <DEDENT> return FreeCAD.Units.parseQuantity(self.form.value_a.text())
Tool parameter editor for drills.
6259905d4f6381625f199fbc
class BinaryOperation: <NEW_LINE> <INDENT> __ops = {'+': lambda x, y: Number(x.value + y.value), '-': lambda x, y: Number(x.value - y.value), '*': lambda x, y: Number(x.value * y.value), '/': lambda x, y: Number(x.value // y.value), '%': lambda x, y: Number(x.value % y.value), '==': lambda x, y: Number(x.value == y.value), '!=': lambda x, y: Number(x.value != y.value), '<': lambda x, y: Number(x.value < y.value), '>': lambda x, y: Number(x.value > y.value), '<=': lambda x, y: Number(x.value <= y.value), '>=': lambda x, y: Number(x.value >= y.value), '&&': lambda x, y: Number(x.value and y.value), '||': lambda x, y: Number(x.value or y.value), } <NEW_LINE> def __init__(self, lhs, op, rhs): <NEW_LINE> <INDENT> self.lhs = lhs <NEW_LINE> self.rhs = rhs <NEW_LINE> self.op = op <NEW_LINE> <DEDENT> def evaluate(self, scope): <NEW_LINE> <INDENT> return self.__ops[self.op](self.lhs.evaluate(scope), self.rhs.evaluate(scope))
BinaryOperation - представляет бинарную операцию над двумя выражениями. Результатом вычисления бинарной операции является объект Number. Поддерживаемые операции: “+”, “-”, “*”, “/”, “%”, “==”, “!=”, “<”, “>”, “<=”, “>=”, “&&”, “||”.
6259905d009cb60464d02b6a
class ArticleImagePipeline(ImagesPipeline): <NEW_LINE> <INDENT> def item_completed(self, results, item, info): <NEW_LINE> <INDENT> if "front_image_url" in item: <NEW_LINE> <INDENT> for ok, value in results: <NEW_LINE> <INDENT> image_file_path = value['path'] <NEW_LINE> <DEDENT> item['front_image_path'] = image_file_path <NEW_LINE> <DEDENT> return item
重写 ImagesPipeline 的 item_completed方法, 获取图片路径
6259905d7b25080760ed87fa
class BaricadrNotImplementedError(Exception): <NEW_LINE> <INDENT> pass
Raised when there are not endpoint associated with this function
6259905d16aa5153ce401b18