code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class Card: <NEW_LINE> <INDENT> def __init__(self, scale=1.0): <NEW_LINE> <INDENT> self.spr = None <NEW_LINE> self.index = None <NEW_LINE> self._scale = scale <NEW_LINE> <DEDENT> def create(self, string, attributes=None, sprites=None, file_path=None): <NEW_LINE> <INDENT> if attributes is None: <NEW_LINE> <INDENT> if self.spr is None: <NEW_LINE> <INDENT> self.spr = Sprite(sprites, 0, 0, svg_str_to_pixbuf(string)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.spr.set_image(svg_str_to_pixbuf(string)) <NEW_LINE> <DEDENT> self.index = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.shape = attributes[0] <NEW_LINE> self.color = attributes[1] <NEW_LINE> self.num = attributes[2] <NEW_LINE> self.fill = attributes[3] <NEW_LINE> self.index = self.shape * COLORS * NUMBER * FILLS + self.color * NUMBER * FILLS + self.num * FILLS + self.fill <NEW_LINE> if self.spr is None: <NEW_LINE> <INDENT> self.spr = Sprite(sprites, 0, 0, svg_str_to_pixbuf(string)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.spr.set_image(svg_str_to_pixbuf(string)) <NEW_LINE> <DEDENT> if file_path is not None: <NEW_LINE> <INDENT> self.spr.set_image(load_image(file_path, self._scale), i=1, dx=int(self._scale * CARD_WIDTH * .125), dy=int(self._scale * CARD_HEIGHT * .125)) <NEW_LINE> <DEDENT> <DEDENT> self.spr.set_label_attributes(self._scale * 24) <NEW_LINE> self.spr.set_label('') <NEW_LINE> <DEDENT> def show_card(self): <NEW_LINE> <INDENT> if self.spr is not None: <NEW_LINE> <INDENT> self.spr.set_layer(2000) <NEW_LINE> self.spr.draw() <NEW_LINE> <DEDENT> <DEDENT> def hide_card(self): <NEW_LINE> <INDENT> if self.spr is not None: <NEW_LINE> <INDENT> self.spr.hide() | Individual cards | 62598fc9bf627c535bcb1808 |
class StarterFlag(object): <NEW_LINE> <INDENT> pattern = "STARTER_FLAG.{timestamp}" <NEW_LINE> def __init__(self, filename=None): <NEW_LINE> <INDENT> if filename: <NEW_LINE> <INDENT> self.read(filename) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.filename = None <NEW_LINE> self.timestamp = None <NEW_LINE> self.dbid = None <NEW_LINE> <DEDENT> <DEDENT> def _timestamp_from_filename(self, filename): <NEW_LINE> <INDENT> tstr = os.path.basename(filename).replace( self.pattern.format(timestamp=""), "") <NEW_LINE> return timestamp_from_string(tstr) <NEW_LINE> <DEDENT> def read(self, filename): <NEW_LINE> <INDENT> self.filename = filename <NEW_LINE> self.timestamp = self._timestamp_from_filename(self.filename) <NEW_LINE> with open(self.filename, 'r') as fh: <NEW_LINE> <INDENT> self.dbid = fh.read().encode().decode() <NEW_LINE> <DEDENT> <DEDENT> def write(self, dirname, dbid, timestamp=None): <NEW_LINE> <INDENT> if not timestamp: <NEW_LINE> <INDENT> timestamp = generate_timestamp() <NEW_LINE> <DEDENT> self.timestamp = timestamp <NEW_LINE> self.dbid = dbid <NEW_LINE> self.filename = os.path.join(dirname, self.pattern.format(timestamp=self.timestamp)) <NEW_LINE> assert not os.path.exists(self.filename), ( "StartFlag {} already exists".format(self.filename)) <NEW_LINE> with open(self.filename, 'w') as fh: <NEW_LINE> <INDENT> fh.write(dbid) | Flag files indicating analysis start
| 62598fc9cc40096d6161a387 |
class SequenceField(BaseField): <NEW_LINE> <INDENT> _lazy = (operator.__getitem__, operator.__contains__, ) <NEW_LINE> def contains(self, operand): <NEW_LINE> <INDENT> return self.create_copy(operator.__contains__, operand) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return 'len' | Class used for sequences fields creations. It can be used to create:
strings
arrays
dictionaries | 62598fc9ff9c53063f51a9ac |
class GoodsInfo(SqlModel): <NEW_LINE> <INDENT> __tablename__ = "goods_info" <NEW_LINE> __connection_name__ = "default" <NEW_LINE> id = Column('id',Integer,primary_key=True,autoincrement=True,nullable=False) <NEW_LINE> code = Column('code',Integer,nullable=False,unique=True,index=True) <NEW_LINE> avatar_id = Column('avatar_id',BigInteger,nullable=False,default=0) <NEW_LINE> name = Column('name',String(16),nullable=False) <NEW_LINE> price = Column('price',Float,nullable=False) <NEW_LINE> type = Column('type',Integer,nullable=False,default=1,index=True) <NEW_LINE> feed_day = Column('feed_day',Integer,nullable=False,default=0) <NEW_LINE> brief = Column('brief',String(128),nullable=False,default='') <NEW_LINE> detail = Column('detail',String(512),nullable=False,default='') <NEW_LINE> number = Column('number',Integer,nullable=False,default=1) <NEW_LINE> status = Column('status',SmallInteger,nullable=False,default=0) <NEW_LINE> create_date = Column('create_date',DateTime,nullable=False,default=datetime.datetime.now,server_default=text('CURRENT_TIMESTAMP')) <NEW_LINE> update_time = Column('update_time',DateTime,nullable=False,default=datetime.datetime.now,server_default=text('CURRENT_TIMESTAMP')) | 商品信息 | 62598fc94428ac0f6e658886 |
class TestAdjustPIP(object): <NEW_LINE> <INDENT> def test_unpack(self): <NEW_LINE> <INDENT> controller = Controller(address='unix:abstract=abcde') <NEW_LINE> controller.establish_connection = Mock(return_value=None) <NEW_LINE> controller.connection = MockConnection(True) <NEW_LINE> with pytest.raises(ConnectionReturnError): <NEW_LINE> <INDENT> controller.adjust_pip(1, 2, 3, 4) <NEW_LINE> <DEDENT> <DEDENT> def test_normal_unpack(self): <NEW_LINE> <INDENT> controller = Controller(address='unix:abstract=abcdef') <NEW_LINE> controller.establish_connection = Mock(return_value=None) <NEW_LINE> controller.connection = MockConnection(False) <NEW_LINE> assert controller.adjust_pip(1, 2, 3, 4) == 1 | Test the adjust_pip method | 62598fc94c3428357761a61d |
class JSONFieldAnonymizer(FieldAnonymizer): <NEW_LINE> <INDENT> empty_values = [None, ''] <NEW_LINE> def get_numeric_encryption_key(self, encryption_key: str, value: Union[int, float] = None) -> int: <NEW_LINE> <INDENT> if value is None: <NEW_LINE> <INDENT> return numerize_key(encryption_key) <NEW_LINE> <DEDENT> return numerize_key(encryption_key) % 10 ** get_number_guess_len(value) <NEW_LINE> <DEDENT> def anonymize_json_value(self, value: Union[list, dict, bool, None, str, int, float], encryption_key: str, anonymize: bool = True) -> Union[list, dict, bool, None, str, int, float]: <NEW_LINE> <INDENT> if value is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> elif type(value) is str: <NEW_LINE> <INDENT> return translate_text(encryption_key, value, anonymize, JSON_SAFE_CHARS) <NEW_LINE> <DEDENT> elif type(value) is int: <NEW_LINE> <INDENT> return translate_number(encryption_key, value, anonymize) <NEW_LINE> <DEDENT> elif type(value) is float: <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> elif type(value) is dict: <NEW_LINE> <INDENT> return {key: self.anonymize_json_value(item, encryption_key, anonymize) for key, item in value.items()} <NEW_LINE> <DEDENT> elif type(value) is list: <NEW_LINE> <INDENT> return [self.anonymize_json_value(item, encryption_key, anonymize) for item in value] <NEW_LINE> <DEDENT> elif type(value) is bool and self.get_numeric_encryption_key(encryption_key) % 2 == 0: <NEW_LINE> <INDENT> return not value <NEW_LINE> <DEDENT> return value <NEW_LINE> <DEDENT> def get_encrypted_value(self, value, encryption_key: str): <NEW_LINE> <INDENT> if type(value) not in [dict, list, str]: <NEW_LINE> <INDENT> raise ValidationError("JSONFieldAnonymizer encountered unknown type of json. " "Only python dict and list are supported.") <NEW_LINE> <DEDENT> if type(value) == str: <NEW_LINE> <INDENT> return json.dumps(self.anonymize_json_value(json.loads(value), encryption_key)) <NEW_LINE> <DEDENT> return self.anonymize_json_value(value, encryption_key) <NEW_LINE> <DEDENT> def get_decrypted_value(self, value, encryption_key: str): <NEW_LINE> <INDENT> if type(value) not in [dict, list, str]: <NEW_LINE> <INDENT> raise ValidationError("JSONFieldAnonymizer encountered unknown type of json. " "Only python dict and list are supported.") <NEW_LINE> <DEDENT> if type(value) == str: <NEW_LINE> <INDENT> return json.dumps(self.anonymize_json_value(json.loads(value), encryption_key, anonymize=False)) <NEW_LINE> <DEDENT> return self.anonymize_json_value(value, encryption_key, anonymize=False) | Anonymization for JSONField. | 62598fc963b5f9789fe854d5 |
class ApplicationGatewayFirewallRuleGroup(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'rule_group_name': {'required': True}, 'rules': {'required': True}, } <NEW_LINE> _attribute_map = { 'rule_group_name': {'key': 'ruleGroupName', 'type': 'str'}, 'description': {'key': 'description', 'type': 'str'}, 'rules': {'key': 'rules', 'type': '[ApplicationGatewayFirewallRule]'}, } <NEW_LINE> def __init__( self, *, rule_group_name: str, rules: List["ApplicationGatewayFirewallRule"], description: Optional[str] = None, **kwargs ): <NEW_LINE> <INDENT> super(ApplicationGatewayFirewallRuleGroup, self).__init__(**kwargs) <NEW_LINE> self.rule_group_name = rule_group_name <NEW_LINE> self.description = description <NEW_LINE> self.rules = rules | A web application firewall rule group.
All required parameters must be populated in order to send to Azure.
:param rule_group_name: Required. The name of the web application firewall rule group.
:type rule_group_name: str
:param description: The description of the web application firewall rule group.
:type description: str
:param rules: Required. The rules of the web application firewall rule group.
:type rules: list[~azure.mgmt.network.v2020_06_01.models.ApplicationGatewayFirewallRule] | 62598fc99f28863672818a2c |
class Not(Boolean): <NEW_LINE> <INDENT> def __init__(self, condition): <NEW_LINE> <INDENT> if not isinstance(condition, Boolean): <NEW_LINE> <INDENT> raise SpecSyntaxError() <NEW_LINE> <DEDENT> self.condition = condition <NEW_LINE> <DEDENT> def eval(self, values): <NEW_LINE> <INDENT> return not self.condition.eval(values) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '<Not [%s]>' % self.condition <NEW_LINE> <DEDENT> @property <NEW_LINE> def js(self): <NEW_LINE> <INDENT> return 'd.Not(%s)' % self.condition.js <NEW_LINE> <DEDENT> def get_usage(self, name): <NEW_LINE> <INDENT> return self.condition.get_usage(name) | NOT operator | 62598fc9bf627c535bcb180a |
class Score(ndb.Model): <NEW_LINE> <INDENT> user = ndb.KeyProperty(required=True, kind='User') <NEW_LINE> opponent = ndb.KeyProperty(required=True, kind='User') <NEW_LINE> date = ndb.DateProperty(required=True) <NEW_LINE> board_state = ndb.StringProperty(required=True) <NEW_LINE> result = msgprop.EnumProperty(Result, required=True) <NEW_LINE> def to_form(self): <NEW_LINE> <INDENT> if self.result == Result.WIN: <NEW_LINE> <INDENT> result = "WIN" <NEW_LINE> <DEDENT> elif self.result == Result.TIE: <NEW_LINE> <INDENT> result = "TIE" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result = "LOSE" <NEW_LINE> <DEDENT> if not self.opponent: <NEW_LINE> <INDENT> return ScoreForm(user_name=self.user.get().name, result=result, date=str(self.date), board_state=self.board_state, opponent_name="computer") <NEW_LINE> <DEDENT> return ScoreForm(user_name=self.user.get().name, result=result, date=str(self.date), board_state=self.board_state, opponent_name=self.opponent.get().name) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_form(cls, message): <NEW_LINE> <INDENT> current_user = get_endpoints_current_user().key <NEW_LINE> opponent = User.query(User.name == message.opponent_name) <NEW_LINE> if message.result == 'WIN': <NEW_LINE> <INDENT> result = Result.WIN <NEW_LINE> <DEDENT> elif message.result == 'TIE': <NEW_LINE> <INDENT> result = Result.TIE <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result = Result.LOSE <NEW_LINE> <DEDENT> entity = cls(user=current_user, opponent=opponent, board_state=message.board_state, result=result, ) <NEW_LINE> entity.put() <NEW_LINE> return entity <NEW_LINE> <DEDENT> def user_score_to_int(self): <NEW_LINE> <INDENT> if self.result == Result.WIN: <NEW_LINE> <INDENT> result = 2 <NEW_LINE> <DEDENT> elif self.result == Result.TIE: <NEW_LINE> <INDENT> result = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result = 0 <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def opponent_score_to_int(self): <NEW_LINE> <INDENT> if self.result == Result.WIN: <NEW_LINE> <INDENT> result = 0 <NEW_LINE> <DEDENT> elif self.result == Result.TIE: <NEW_LINE> <INDENT> result = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result = 2 <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def query_current_user(cls): <NEW_LINE> <INDENT> current_user = get_endpoints_current_user() <NEW_LINE> return cls.query(cls.user == current_user) <NEW_LINE> <DEDENT> @property <NEW_LINE> def timestamp(self): <NEW_LINE> <INDENT> return self.date.strftime('%b %d, %Y %I:%M:%S %p') | Score object | 62598fc98a349b6b436865a0 |
class Matrix(Effect): <NEW_LINE> <INDENT> def __init__(self, screen, **kwargs): <NEW_LINE> <INDENT> super(Matrix, self).__init__(screen, **kwargs) <NEW_LINE> self._chars = [] <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self._chars = [_Trail(self._screen, x) for x in range(self._screen.width)] <NEW_LINE> <DEDENT> def _update(self, frame_no): <NEW_LINE> <INDENT> if frame_no % 2 == 0: <NEW_LINE> <INDENT> for char in self._chars: <NEW_LINE> <INDENT> char.update((self._stop_frame == 0) or ( self._stop_frame - frame_no > 100)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @property <NEW_LINE> def stop_frame(self): <NEW_LINE> <INDENT> return self._stop_frame | Matrix-like falling green letters. | 62598fc9adb09d7d5dc0a8db |
class RobertaForSequenceClassification(BertPreTrainedModel): <NEW_LINE> <INDENT> config_class = RobertaConfig <NEW_LINE> pretrained_model_archive_map = ROBERTA_PRETRAINED_MODEL_ARCHIVE_MAP <NEW_LINE> base_model_prefix = "roberta" <NEW_LINE> def __init__(self, config): <NEW_LINE> <INDENT> super(RobertaForSequenceClassification, self).__init__(config) <NEW_LINE> self.num_labels = config.num_labels <NEW_LINE> self.roberta = RobertaModel(config) <NEW_LINE> self.classifier = RobertaClassificationHead(config) <NEW_LINE> <DEDENT> def forward(self, input_ids, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, labels=None): <NEW_LINE> <INDENT> outputs = self.roberta(input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask) <NEW_LINE> sequence_output = outputs[0] <NEW_LINE> logits = self.classifier(sequence_output) <NEW_LINE> outputs = (logits,) + outputs[2:] <NEW_LINE> if labels is not None: <NEW_LINE> <INDENT> if self.num_labels == 1: <NEW_LINE> <INDENT> loss_fct = MSELoss() <NEW_LINE> loss = loss_fct(logits.view(-1), labels.view(-1)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> loss_fct = CrossEntropyLoss() <NEW_LINE> loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1)) <NEW_LINE> <DEDENT> outputs = (loss,) + outputs <NEW_LINE> <DEDENT> return outputs | **labels**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size,)``:
Labels for computing the sequence classification/regression loss.
Indices should be in ``[0, ..., config.num_labels]``.
If ``config.num_labels == 1`` a regression loss is computed (Mean-Square loss),
If ``config.num_labels > 1`` a classification loss is computed (Cross-Entropy).
Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs:
**loss**: (`optional`, returned when ``labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``:
Classification (or regression if config.num_labels==1) loss.
**logits**: ``torch.FloatTensor`` of shape ``(batch_size, config.num_labels)``
Classification (or regression if config.num_labels==1) scores (before SoftMax).
**hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)
list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)
of shape ``(batch_size, sequence_length, hidden_size)``:
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
**attentions**: (`optional`, returned when ``config.output_attentions=True``)
list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.
Examples::
tokenizer = RobertaTokenizer.from_pretrained('roberta-base')
model = RobertaForSequenceClassification.from_pretrained('roberta-base')
input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute")).unsqueeze(0) # Batch size 1
labels = torch.tensor([1]).unsqueeze(0) # Batch size 1
outputs = model(input_ids, labels=labels)
loss, logits = outputs[:2] | 62598fc9851cf427c66b8615 |
class getSquareMemberRelations_result(object): <NEW_LINE> <INDENT> thrift_spec = ( (0, TType.STRUCT, 'success', (GetSquareMemberRelationsResponse, GetSquareMemberRelationsResponse.thrift_spec), None, ), (1, TType.STRUCT, 'e', (SquareException, SquareException.thrift_spec), None, ), ) <NEW_LINE> def __init__(self, success=None, e=None,): <NEW_LINE> <INDENT> self.success = success <NEW_LINE> self.e = e <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: <NEW_LINE> <INDENT> iprot._fast_decode(self, iprot, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 0: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.success = GetSquareMemberRelationsResponse() <NEW_LINE> self.success.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.e = SquareException() <NEW_LINE> self.e.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot._fast_encode is not None and self.thrift_spec is not None: <NEW_LINE> <INDENT> oprot.trans.write(oprot._fast_encode(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('getSquareMemberRelations_result') <NEW_LINE> if self.success is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('success', TType.STRUCT, 0) <NEW_LINE> self.success.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.e is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('e', TType.STRUCT, 1) <NEW_LINE> self.e.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.items()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) | Attributes:
- success
- e | 62598fc93617ad0b5ee064a9 |
class rule_006(proposed_rule.Rule): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> proposed_rule.Rule.__init__(self, 'context_ref', '006') | This rule checks the semicolon is on the same line as the context selected name.
.. NOTE:: This rule has not been implemented yet.
**Violation**
.. code-block:: vhdl
context c1
;
context
c1
;
**Fix**
.. code-block:: vhdl
context c1;
context
c1; | 62598fc94c3428357761a61f |
class GuildEmbed(DiscordObject): <NEW_LINE> <INDENT> def __init__(self, enabled=False, channel_id=0): <NEW_LINE> <INDENT> self.enabled = enabled <NEW_LINE> self.channel_id = channel_id | Represents a guild embed
.. versionadded:: 0.2.0
Attributes:
enabled (:obj:`bool`): if the embed is enabled
channel_id (:obj:`int`): the embed channel id | 62598fc955399d3f0562687b |
class Uniform(Distribution): <NEW_LINE> <INDENT> def __init__(self, a=0.0, b=1.0): <NEW_LINE> <INDENT> self.a = a <NEW_LINE> self.b = b <NEW_LINE> params = { "loc" : a, "scale" : b - a } <NEW_LINE> if a > b: <NEW_LINE> <INDENT> raise Exception("b cannot be less than a") <NEW_LINE> <DEDENT> super().__init__(params, stats.uniform, False) <NEW_LINE> self.xlim = (a, b) | Defines a probability space for a uniform distribution.
Attributes:
a (float): lower bound for possible values
b (float): upper bound for possible values | 62598fc9fbf16365ca79441b |
class Device(models.Model): <NEW_LINE> <INDENT> __model_label__ = "device" <NEW_LINE> device = models.CharField( 'Device', max_length=200, null=True, blank=True) <NEW_LINE> pcsRow_fk = models.ForeignKey('PcsRow') <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return "%s: %s" % (self.device, self.pcsRow_fk) | The ICD 10 PCS bodypart models. | 62598fc9ad47b63b2c5a7bbc |
class ConstExpr(Expr): <NEW_LINE> <INDENT> def __init__(self, val): <NEW_LINE> <INDENT> self.val = asm.ConstWord(val) <NEW_LINE> <DEDENT> def emit_with_dest(self, context): <NEW_LINE> <INDENT> return ('', asm.DataLoc(asm.LocType.CONST, self.val)) <NEW_LINE> <DEDENT> def is_always_true(self): <NEW_LINE> <INDENT> return not self.val.is_zero() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return type(self) == type(other) and self.val == other.val <NEW_LINE> <DEDENT> def has_value(self, val): <NEW_LINE> <INDENT> return self.val == asm.ConstWord(val) | Expression that has a constant value | 62598fc94527f215b58ea232 |
class CreateFloatingIP(neutronV20.CreateCommand): <NEW_LINE> <INDENT> resource = 'floatingip' <NEW_LINE> def add_known_arguments(self, parser): <NEW_LINE> <INDENT> parser.add_argument( 'floating_network_id', metavar='FLOATING_NETWORK', help=_('Network name or ID to allocate floating IP from.')) <NEW_LINE> parser.add_argument( '--port-id', help=_('ID of the port to be associated with the floating IP.')) <NEW_LINE> parser.add_argument( '--port_id', help=argparse.SUPPRESS) <NEW_LINE> parser.add_argument( '--fixed-ip-address', help=_('IP address on the port (only required if port has ' 'multiple IPs).')) <NEW_LINE> parser.add_argument( '--fixed_ip_address', help=argparse.SUPPRESS) <NEW_LINE> <DEDENT> def args2body(self, parsed_args): <NEW_LINE> <INDENT> _network_id = neutronV20.find_resourceid_by_name_or_id( self.get_client(), 'network', parsed_args.floating_network_id) <NEW_LINE> body = {self.resource: {'floating_network_id': _network_id}} <NEW_LINE> if parsed_args.port_id: <NEW_LINE> <INDENT> body[self.resource].update({'port_id': parsed_args.port_id}) <NEW_LINE> <DEDENT> if parsed_args.tenant_id: <NEW_LINE> <INDENT> body[self.resource].update({'tenant_id': parsed_args.tenant_id}) <NEW_LINE> <DEDENT> if parsed_args.fixed_ip_address: <NEW_LINE> <INDENT> body[self.resource].update({'fixed_ip_address': parsed_args.fixed_ip_address}) <NEW_LINE> <DEDENT> return body | Create a floating IP for a given tenant. | 62598fc9be7bc26dc925200c |
class DataLogger(object): <NEW_LINE> <INDENT> CONFIG_FILENAME = os.path.join( rospkg.RosPack().get_path('assistance_arbitrator'), 'config/datalogger.yaml' ) <NEW_LINE> DATA_DIRECTORY = os.path.join(rospkg.RosPack().get_path('assistance_arbitrator'), 'data') <NEW_LINE> ROSBAG_CMD = [ 'rosbag', 'record', '--duration=10m', '--split', '-o', 'halloween', '-b', "0", '--chunksize=1024', '--lz4', '__name:=datalogger_record' ] <NEW_LINE> ROSBAG_KILL_CMD = ['rosnode', 'kill', 'datalogger_record'] <NEW_LINE> START_SERVICE_NAME = '~start' <NEW_LINE> STOP_SERVICE_NAME = '~stop' <NEW_LINE> SPLIT_SERVICE_NAME = '~split' <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.config = None <NEW_LINE> self._bag_process = None <NEW_LINE> self._start_service = rospy.Service(DataLogger.START_SERVICE_NAME, Empty, self._start_srv) <NEW_LINE> self._stop_service = rospy.Service(DataLogger.STOP_SERVICE_NAME, Empty, self._stop_srv) <NEW_LINE> self._split_service = rospy.Service(DataLogger.SPLIT_SERVICE_NAME, Empty, self._split_srv) <NEW_LINE> rospy.loginfo("datalogger node is ready...") <NEW_LINE> <DEDENT> def _start_srv(self, req): <NEW_LINE> <INDENT> self.start() <NEW_LINE> return EmptyResponse() <NEW_LINE> <DEDENT> def _stop_srv(self, req): <NEW_LINE> <INDENT> self.stop() <NEW_LINE> return EmptyResponse() <NEW_LINE> <DEDENT> def _split_srv(self, req): <NEW_LINE> <INDENT> self.split() <NEW_LINE> return EmptyResponse() <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> if self._bag_process is not None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> cmd = copy.copy(DataLogger.ROSBAG_CMD) <NEW_LINE> with open(DataLogger.CONFIG_FILENAME, 'r') as fd: <NEW_LINE> <INDENT> self.config = yaml.load(fd) <NEW_LINE> <DEDENT> if len(self.config['include_regex']) > 0: <NEW_LINE> <INDENT> included_topics = "|".join(self.config['include_regex']) <NEW_LINE> print(included_topics) <NEW_LINE> cmd.append('-e') <NEW_LINE> cmd.append('"{}"'.format(included_topics)) <NEW_LINE> <DEDENT> if len(self.config['node']) > 0: <NEW_LINE> <INDENT> cmd.append("--node={}".format(self.config['node'])) <NEW_LINE> <DEDENT> if len(self.config['exclude_regex']) > 0: <NEW_LINE> <INDENT> excluded_topics = "|".join(self.config['exclude_regex']) <NEW_LINE> print(excluded_topics) <NEW_LINE> cmd.append('-x') <NEW_LINE> cmd.append('"{}"'.format(excluded_topics)) <NEW_LINE> <DEDENT> print(cmd) <NEW_LINE> self._bag_process = subprocess.Popen( cmd, cwd=DataLogger.DATA_DIRECTORY, preexec_fn=os.setpgrp ) <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> if self._bag_process is not None: <NEW_LINE> <INDENT> subprocess.check_call(DataLogger.ROSBAG_KILL_CMD) <NEW_LINE> assert self._bag_process.wait() == 0, "Error in record process" <NEW_LINE> <DEDENT> self._bag_process = None <NEW_LINE> <DEDENT> def split(self): <NEW_LINE> <INDENT> self.stop() <NEW_LINE> self.start() | Logs data specified by the YAML file | 62598fc9adb09d7d5dc0a8dd |
@dataclass <NEW_LINE> class Annotation: <NEW_LINE> <INDENT> filename: str <NEW_LINE> label_index: int <NEW_LINE> label_enum: str <NEW_LINE> label_display: str <NEW_LINE> bbox: BBox <NEW_LINE> color: Color=BLACK <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return self.as_dict() <NEW_LINE> <DEDENT> def as_dict(self): <NEW_LINE> <INDENT> d = self.bbox.to_dict() <NEW_LINE> r,g,b = self.color.to_rgb_int() <NEW_LINE> d.update( { 'label_display': self.label_display, 'label_enum': self.label_enum, 'label_index': self.label_index, 'color_hex': self.color.to_rgb_hex_int(), 'r': r, 'g': g, 'b': b, 'filename': self.filename } ) <NEW_LINE> return d <NEW_LINE> <DEDENT> def to_yolo_str(self): <NEW_LINE> <INDENT> return f'{self.label_index} {self.bbox.cx_norm} {self.bbox.cy_norm} {self.bbox.w_norm} {self.bbox.h_norm}' <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_anno_series_row(cls, row): <NEW_LINE> <INDENT> bbox = BBox(row.x1, row.y1, row.x2, row.y2, row.dw, row.dh) <NEW_LINE> return cls(row.filename, row.label_index, row.label_enum, row.label_display, bbox, Color.from_rgb_hex_str(row.color_hex)) | Annotation data object
| 62598fc9851cf427c66b8617 |
class ShadowUsersManager(manager.Manager): <NEW_LINE> <INDENT> driver_namespace = 'keystone.identity.shadow_users' <NEW_LINE> _provides_api = 'shadow_users_api' <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> shadow_driver = CONF.shadow_users.driver <NEW_LINE> super(ShadowUsersManager, self).__init__(shadow_driver) | Default pivot point for the Shadow Users backend. | 62598fc9f9cc0f698b1c5484 |
class TestStatus: <NEW_LINE> <INDENT> def __init__(self, test_manager, returncode, stdout, stderr, directory, inputs, input_filenames): <NEW_LINE> <INDENT> self.test_manager = test_manager <NEW_LINE> self.returncode = returncode <NEW_LINE> self.stdout = stdout <NEW_LINE> self.stderr = stderr <NEW_LINE> self.directory = directory <NEW_LINE> self.inputs = inputs <NEW_LINE> self.input_filenames = input_filenames | A struct for holding run status of a test case. | 62598fc97b180e01f3e49202 |
class Decisions(PmmlBinding): <NEW_LINE> <INDENT> def toPFA(self, options, context): <NEW_LINE> <INDENT> raise NotImplementedError | Represents a <Decisions> tag and provides methods to convert to PFA. | 62598fc95fcc89381b2662ff |
@register <NEW_LINE> class Request(BaseSchema): <NEW_LINE> <INDENT> __props__ = { "seq": { "type": "integer", "description": "Sequence number (also known as message ID). For protocol messages of type 'request' this ID can be used to cancel the request." }, "type": { "type": "string", "enum": [ "request" ] }, "command": { "type": "string", "description": "The command to execute." }, "arguments": { "type": [ "array", "boolean", "integer", "null", "number", "object", "string" ], "description": "Object containing arguments for the command." } } <NEW_LINE> __refs__ = set() <NEW_LINE> __slots__ = list(__props__.keys()) + ['kwargs'] <NEW_LINE> def __init__(self, command, seq=-1, arguments=None, update_ids_from_dap=False, **kwargs): <NEW_LINE> <INDENT> self.type = 'request' <NEW_LINE> self.command = command <NEW_LINE> self.seq = seq <NEW_LINE> self.arguments = arguments <NEW_LINE> self.kwargs = kwargs <NEW_LINE> <DEDENT> def to_dict(self, update_ids_to_dap=False): <NEW_LINE> <INDENT> type = self.type <NEW_LINE> command = self.command <NEW_LINE> seq = self.seq <NEW_LINE> arguments = self.arguments <NEW_LINE> dct = { 'type': type, 'command': command, 'seq': seq, } <NEW_LINE> if arguments is not None: <NEW_LINE> <INDENT> dct['arguments'] = arguments <NEW_LINE> <DEDENT> dct.update(self.kwargs) <NEW_LINE> return dct | A client or debug adapter initiated request.
Note: automatically generated code. Do not edit manually. | 62598fc923849d37ff851417 |
class Keypads(Elements): <NEW_LINE> <INDENT> def __init__(self, elk): <NEW_LINE> <INDENT> super().__init__(elk, Keypad, Max.KEYPADS.value) <NEW_LINE> elk.add_handler("IC", self._ic_handler) <NEW_LINE> elk.add_handler("KA", self._ka_handler) <NEW_LINE> elk.add_handler("KC", self._kc_handler) <NEW_LINE> elk.add_handler("LW", self._lw_handler) <NEW_LINE> elk.add_handler("ST", self._st_handler) <NEW_LINE> <DEDENT> def sync(self): <NEW_LINE> <INDENT> self.elk.send(ka_encode()) <NEW_LINE> self.get_descriptions(TextDescriptions.KEYPAD.value) <NEW_LINE> <DEDENT> def _ic_handler(self, code, user, keypad): <NEW_LINE> <INDENT> keypad_ = self.elements[keypad] <NEW_LINE> keypad_.setattr("last_user_time", dt.datetime.now(dt.timezone.utc), False) <NEW_LINE> keypad_.setattr("code", code if user < 0 else "****", False) <NEW_LINE> keypad_.setattr("last_user", user, True) <NEW_LINE> <DEDENT> def _ka_handler(self, keypad_areas): <NEW_LINE> <INDENT> for keypad in self.elements: <NEW_LINE> <INDENT> if keypad_areas[keypad.index] >= 0: <NEW_LINE> <INDENT> keypad.setattr("area", keypad_areas[keypad.index], True) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _kc_handler(self, keypad, key): <NEW_LINE> <INDENT> self.elements[keypad].last_keypress = None <NEW_LINE> try: <NEW_LINE> <INDENT> name = KeypadKeys(key).name <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> name = "" <NEW_LINE> <DEDENT> self.elements[keypad].setattr("last_keypress", (name, key), True) <NEW_LINE> <DEDENT> def _lw_handler(self, keypad_temps, zone_temps): <NEW_LINE> <INDENT> for keypad in self.elements: <NEW_LINE> <INDENT> if keypad_temps[keypad.index] > -40: <NEW_LINE> <INDENT> keypad.setattr("temperature", keypad_temps[keypad.index], True) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _st_handler(self, group, device, temperature): <NEW_LINE> <INDENT> if group == 1: <NEW_LINE> <INDENT> self.elements[device].setattr("temperature", temperature, True) | Handling for multiple areas | 62598fc95fdd1c0f98e5e2f1 |
class JenkinsChangeQueueObject(JenkinsObject): <NEW_LINE> <INDENT> QUEUE_JOB_SUFFIX = '_change-queue' <NEW_LINE> TESTER_JOB_SUFFIX = '_change-queue-tester' <NEW_LINE> def queue_job_name(self, queue_name=None): <NEW_LINE> <INDENT> if queue_name is None: <NEW_LINE> <INDENT> queue_name = self.get_queue_name() <NEW_LINE> <DEDENT> return str(queue_name) + self.QUEUE_JOB_SUFFIX <NEW_LINE> <DEDENT> def tester_job_name(self, queue_name=None): <NEW_LINE> <INDENT> if queue_name is None: <NEW_LINE> <INDENT> queue_name = self.get_queue_name() <NEW_LINE> <DEDENT> return str(queue_name) + self.TESTER_JOB_SUFFIX <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def job_to_queue_name(cls, job_name): <NEW_LINE> <INDENT> if job_name.endswith(cls.QUEUE_JOB_SUFFIX): <NEW_LINE> <INDENT> return job_name[:-len(cls.QUEUE_JOB_SUFFIX)] <NEW_LINE> <DEDENT> if job_name.endswith(cls.TESTER_JOB_SUFFIX): <NEW_LINE> <INDENT> return job_name[:-len(cls.TESTER_JOB_SUFFIX)] <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def get_queue_name(self): <NEW_LINE> <INDENT> self.verify_in_jenkins() <NEW_LINE> return self.job_to_queue_name(self.get_job_name()) <NEW_LINE> <DEDENT> def get_queue_job_run_spec(self, queue_action, action_arg): <NEW_LINE> <INDENT> return JobRunSpec( job_name=self.queue_job_name(), params=dict(QUEUE_ACTION=queue_action, ACTION_ARG=action_arg), ) | Utility base class to objects that represent the change queue in Jenkins
| 62598fc9ff9c53063f51a9b2 |
class CreateRoleInputSet(InputSet): <NEW_LINE> <INDENT> def set_Role(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'Role', value) <NEW_LINE> <DEDENT> def set_ApplicationID(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'ApplicationID', value) <NEW_LINE> <DEDENT> def set_RESTAPIKey(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'RESTAPIKey', value) | An InputSet with methods appropriate for specifying the inputs to the CreateRole
Choreo. The InputSet object is used to specify input parameters when executing this Choreo. | 62598fc9d8ef3951e32c800e |
class EmailBackend(ModelBackend): <NEW_LINE> <INDENT> def authenticate(self, email=None, password=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> user = self.user_class.objects.get(email=email) <NEW_LINE> <DEDENT> except self.user_class.DoesNotExist: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if user.check_password(password): <NEW_LINE> <INDENT> return user <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def get_user(self, user_id): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.user_class.objects.get(pk=user_id) <NEW_LINE> <DEDENT> except self.user_class.DoesNotExist: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def user_class(self): <NEW_LINE> <INDENT> if not hasattr(self, '_user_class'): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> user_model = settings.CUSTOM_USER_MODEL <NEW_LINE> self._user_class = get_model(*user_model.split('.', 2)) <NEW_LINE> if not self._user_class: <NEW_LINE> <INDENT> raise ImproperlyConfigured( _('Could not get custom user model %s') % user_model) <NEW_LINE> <DEDENT> return self._user_class <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> return User <NEW_LINE> <DEDENT> <DEDENT> return self._user_class | Authenticate user against email,password credentials
The user class might be :
- django.contrib.auth.models.User (default)
- a custom User class inheriting from django.contrib.auth.models.User
A custom User class is declared through CUSTOM_USER_MODEL setting :
CUSTOM_USER_MODEL = 'yourapp.YourCustomUser' | 62598fc93617ad0b5ee064ad |
class TAction(ActionFlowable): <NEW_LINE> <INDENT> def __init__(self, bgs=[],F=[],f=None): <NEW_LINE> <INDENT> Flowable.__init__(self) <NEW_LINE> self.bgs = bgs <NEW_LINE> self.F = F <NEW_LINE> self.f = f <NEW_LINE> <DEDENT> def apply(self,doc,T=T): <NEW_LINE> <INDENT> T.frames = self.F <NEW_LINE> frame._frameBGs = self.bgs <NEW_LINE> doc.handle_currentFrame(self.f.id) <NEW_LINE> frame._frameBGs = self.bgs | a special Action flowable that sets stuff on the doc template T | 62598fc9091ae35668704f8f |
class HistDataProp(Data1DProp): <NEW_LINE> <INDENT> NAME = "HistData" <NEW_LINE> WIDGET_NAMES = [*Data1DProp.WIDGET_NAMES, 'hist_color_box'] <NEW_LINE> def hist_color_box(self): <NEW_LINE> <INDENT> hist_color_box = GW.ColorBox() <NEW_LINE> hist_color_box.setToolTip("Color to be used for this histogram") <NEW_LINE> self.options.applying.connect(hist_color_box.set_default_color) <NEW_LINE> return('Color', hist_color_box) | Provides the definition of the :class:`~HistDataProp` plot property.
This property contains boxes for setting the label; X-axis data and color
for an individual histogram. | 62598fc94a966d76dd5ef23c |
class PostView(TemplateView): <NEW_LINE> <INDENT> template_name = 'blog/post.html' <NEW_LINE> def get(self, request, *args, **kwargs): <NEW_LINE> <INDENT> context = self.get_context_data(**kwargs) <NEW_LINE> blog_id = kwargs.get('id', None) <NEW_LINE> try: <NEW_LINE> <INDENT> post = Post.objects.get(id=blog_id) <NEW_LINE> <DEDENT> except Post.DoesNotExist: <NEW_LINE> <INDENT> raise Http404 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> context['post'] = post <NEW_LINE> <DEDENT> return self.render_to_response(context) | Просмотр поста | 62598fc9656771135c4899d6 |
class Flatten(Layer): <NEW_LINE> <INDENT> def __init__(self, include_batch_dim=False, **kwargs): <NEW_LINE> <INDENT> super(Flatten, self).__init__(**kwargs) <NEW_LINE> self.include_batch_dim = include_batch_dim <NEW_LINE> <DEDENT> def output_shape(self, input_shape): <NEW_LINE> <INDENT> batch_size, input_shape = input_shape[0], input_shape[1:] <NEW_LINE> if not all(input_shape): <NEW_LINE> <INDENT> raise KError('The shape of the input to "Flatten" is not fully defined. Please do not use "None" for "shape" argument of "Input" layers.') <NEW_LINE> <DEDENT> if self.include_batch_dim: <NEW_LINE> <INDENT> if batch_size is None: <NEW_LINE> <INDENT> raise KError('The batch size to "Flatten" is not determined. Please specify "batch_size" argument of "Input" layers.') <NEW_LINE> <DEDENT> return (np.prod(input_shape),) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return (batch_size, np.prod(input_shape)) <NEW_LINE> <DEDENT> <DEDENT> def output(self, x): <NEW_LINE> <INDENT> if self.include_batch_dim: <NEW_LINE> <INDENT> return B.reshape(x, [-1]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return B.reshape(x, [-1, B.prod(B.shape(x)[1:])]) | Flatten the input tensor into 1D. Behaves like numpy.reshape().
- input_shape: nD, `(nb_samples, x, y, ...)`
- output_shape: 2D, `(nb_samples, Prod(x,y,...))` | 62598fc9377c676e912f6f29 |
class Point: <NEW_LINE> <INDENT> def __init__(self, x, y): <NEW_LINE> <INDENT> self.x = x <NEW_LINE> self.y = y <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "({x}, {y})".format(x = self.x, y = self.y) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Time({x}, {y})".format(x = self.x, y = self.y) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.x == other.x and self.y == other.y <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other <NEW_LINE> <DEDENT> def __add__(self, other): <NEW_LINE> <INDENT> return Point(self.x + other.x, self.y + other.y) <NEW_LINE> <DEDENT> def __sub__(self, other): <NEW_LINE> <INDENT> return Point(self.x - other.x, self.y - other.y) <NEW_LINE> <DEDENT> def __mul__(self, other): <NEW_LINE> <INDENT> return self.x * other.x + self.y * other.y <NEW_LINE> <DEDENT> def cross(self, other): <NEW_LINE> <INDENT> return self.x * other.y - self.y * other.x <NEW_LINE> <DEDENT> def length(self): <NEW_LINE> <INDENT> return math.sqrt(self.x * self.x + self.y * self.y) | Klasa reprezentująca punkty na płaszczyźnie. | 62598fc960cbc95b063646a4 |
class Port(object): <NEW_LINE> <INDENT> def __init__(self, name, remote_id, *args, **kwargs): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.remote_id = remote_id <NEW_LINE> self.others_list = args <NEW_LINE> self.others_dict = kwargs <NEW_LINE> self.hosts = {} | A minimal data object for containing port information.
This is made as a class in order to make it easier to extend upon it. | 62598fc9167d2b6e312b72de |
class IUndislikeEvent(IObjectEvent): <NEW_LINE> <INDENT> pass | Interface for the Undislike event | 62598fc9be7bc26dc925200e |
class InvalidFileFormat(OSError): <NEW_LINE> <INDENT> pass | A Invalid File Format Error occurred | 62598fc93346ee7daa3377fb |
class BigquerydatatransferProjectsDataSourcesCheckValidCredsRequest(_messages.Message): <NEW_LINE> <INDENT> checkValidCredsRequest = _messages.MessageField('CheckValidCredsRequest', 1) <NEW_LINE> name = _messages.StringField(2, required=True) | A BigquerydatatransferProjectsDataSourcesCheckValidCredsRequest object.
Fields:
checkValidCredsRequest: A CheckValidCredsRequest resource to be passed as
the request body.
name: The data source in the form:
`projects/{project_id}/dataSources/{data_source_id}` | 62598fc97cff6e4e811b5d8f |
class BikeShop(): <NEW_LINE> <INDENT> def __init__(self, name): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.inventory = () <NEW_LINE> self.profit = 0 <NEW_LINE> <DEDENT> def sell_bike(self, inventory_index, retail_margin): <NEW_LINE> <INDENT> del self.inventory_index[inventory_index] <NEW_LINE> self.profit += retail_margin * self.profit <NEW_LINE> <DEDENT> def return_profit(self): <NEW_LINE> <INDENT> return self.profit | the shop class | 62598fc9d486a94d0ba2c33a |
class GQAQuestionType(TypedDict): <NEW_LINE> <INDENT> structural: Optional[str] <NEW_LINE> semantic: Optional[str] <NEW_LINE> detailed: Optional[str] | Class wrapper for GQA question types.
Attributes:
-----------
`structural`: Question structural type, e.g. query (open), verify (yes/no).
`semantic`: Question subject's type, e.g. 'attribute' for questions about
color or material.
`detailed`: Question complete type specification, out of 20+ subtypes,
e.g. twoSame.
References:
-----------
https://cs.stanford.edu/people/dorarad/gqa/download.html | 62598fc9ec188e330fdf8bfe |
class sortedProductReiterable(object) : <NEW_LINE> <INDENT> def __init__(self, reiterable, repeat) : <NEW_LINE> <INDENT> self.repeat = repeat <NEW_LINE> self.reiterable = reiterable <NEW_LINE> <DEDENT> def reiter(self, status) : <NEW_LINE> <INDENT> return sortedProductReiterator(self, status) <NEW_LINE> <DEDENT> def initialStatus(self) : <NEW_LINE> <INDENT> if self.repeat > 0 : <NEW_LINE> <INDENT> return (False,) <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def __iter__(self) : <NEW_LINE> <INDENT> return self.reiter(self.initialStatus()) | this class produces "canonical representatives" for all the (unsorted) multisets of a given Reiterable.
It produces all sequences (i1,...,ik) of reiterator values with i1 <= i2 <= ... <= i3. | 62598fc94527f215b58ea237 |
class mLine(LineAny, Mutable): <NEW_LINE> <INDENT> __slots__ = () | A mutable Line | 62598fc9be7bc26dc925200f |
class RootDocumentCategoryList(ListView): <NEW_LINE> <INDENT> context_object_name = 'root_categories' <NEW_LINE> template_name = 'documents/root_categories.html' <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> return DocumentCategory.objects.filter(parent=None).prefetch_related( 'children', 'documents', 'children__documents') | Shows a listing of all root :class:`~.models.DocumentCategory`.
They are passed in with the ``root_categories`` context variable.
The default template is ``documents/root_categories.html``. | 62598fc9099cdd3c63675596 |
class LoginView(FormView): <NEW_LINE> <INDENT> template_name = "users/login.html" <NEW_LINE> form_class = BaseLoginForm <NEW_LINE> def form_valid(self, form): <NEW_LINE> <INDENT> login(self.request, form.get_user()) <NEW_LINE> self.request.session.cycle_key() <NEW_LINE> return super(LoginView, self).form_valid(form) | Login method for the users | 62598fc97c178a314d78d809 |
class PoissonNLLLoss(_Loss): <NEW_LINE> <INDENT> def __init__(self, log_input=True, full=False, size_average=True, eps=1e-8, reduce=True): <NEW_LINE> <INDENT> super(PoissonNLLLoss, self).__init__(size_average, reduce) <NEW_LINE> self.log_input = log_input <NEW_LINE> self.full = full <NEW_LINE> self.eps = eps <NEW_LINE> <DEDENT> def forward(self, log_input, target): <NEW_LINE> <INDENT> return F.poisson_nll_loss(log_input, target, self.log_input, self.full, self.size_average, self.eps, self.reduce) | Negative log likelihood loss with Poisson distribution of target.
The loss can be described as:
.. math::
\text{target} \sim \mathrm{Poisson}(\text{input})
\text{loss}(\text{input}, \text{target}) = \text{input} - \text{target} * \log(\text{input})
+ \log(\text{target!})
The last term can be omitted or approximated with Stirling formula. The
approximation is used for target values more than 1. For targets less or
equal to 1 zeros are added to the loss.
Args:
log_input (bool, optional): if ``True`` the loss is computed as
:math:`\exp(\text{input}) - \text{target}*\text{input}`, if ``False`` the loss is
:math:`\text{input} - \text{target}*\log(\text{input}+\text{eps})`.
full (bool, optional): whether to compute full loss, i. e. to add the
Stirling approximation term
.. math::
\text{target}*\log(\text{target}) - \text{target} + 0.5 * \log(2\pi\text{target}).
size_average (bool, optional): By default, the losses are averaged
over each loss element in the batch. Note that for some losses, there
multiple elements per sample. If the field :attr:`size_average` is set to
``False``, the losses are instead summed for each minibatch. Ignored
when reduce is ``False``. Default: ``True``
eps (float, optional): Small value to avoid evaluation of :math:`\log(0)` when
:attr:`log_input == False`. Default: 1e-8
reduce (bool, optional): By default, the losses are averaged
over observations for each minibatch, or summed, depending on
size_average. When reduce is ``False``, returns a loss per input/target
element instead and ignores `size_average`. Default: ``True``
Examples::
>>> loss = nn.PoissonNLLLoss()
>>> log_input = torch.randn(5, 2, requires_grad=True)
>>> target = torch.randn(5, 2)
>>> output = loss(log_input, target)
>>> output.backward() | 62598fc9ad47b63b2c5a7bc4 |
class NameServerView(base_view.BaseView): <NEW_LINE> <INDENT> _resource_name = 'nameserver' <NEW_LINE> _collection_name = 'nameservers' <NEW_LINE> def _get_base_href(self, parents=None): <NEW_LINE> <INDENT> assert len(parents) == 1 <NEW_LINE> href = "%s/v2/zones/%s/nameservers" % (self.base_uri, parents[0]) <NEW_LINE> return href.rstrip('?') <NEW_LINE> <DEDENT> def show_basic(self, context, request, nameserver): <NEW_LINE> <INDENT> return { "id": nameserver["id"], "name": nameserver["name"] } | Model a NameServer API response as a python dictionary | 62598fc9283ffb24f3cf3bef |
@Chat.register('update') <NEW_LINE> class ChatUpdate(BaseAPIEndpoint): <NEW_LINE> <INDENT> endpoint = 'chat.update' <NEW_LINE> required_args = { 'channel', 'text', 'ts', } <NEW_LINE> optional_args = { 'as_user', 'attachments', 'link_names', 'parse', } <NEW_LINE> options = { 'include_token': True, } <NEW_LINE> scopes = { 'all': set(), 'bot': { 'chat:write:bot', }, 'user': { 'chat:write:user', }, } <NEW_LINE> def __call__(self, channel, text, ts, as_user=None, attachments=None, link_names=None, parse=None, ): <NEW_LINE> <INDENT> optional_kwargs = {} <NEW_LINE> if as_user is not None: <NEW_LINE> <INDENT> optional_kwargs['as_user'] = as_user <NEW_LINE> <DEDENT> if attachments is not None: <NEW_LINE> <INDENT> optional_kwargs['attachments'] = attachments <NEW_LINE> <DEDENT> if link_names is not None: <NEW_LINE> <INDENT> optional_kwargs['link_names'] = link_names <NEW_LINE> <DEDENT> if parse is not None: <NEW_LINE> <INDENT> optional_kwargs['parse'] = parse <NEW_LINE> <DEDENT> return BaseAPIEndpoint.__call__(self, channel=channel, text=text, ts=ts, **optional_kwargs ) | This method updates a message in a channel. Though related to chat.postMessage, some parameters of chat.update are handled differently.
.. code-block:: json
{
"ok": true,
"channel": "C024BE91L",
"ts": "1401383885.000061",
"text": "Updated Text"
}
The response includes the text, channel and timestamp properties of the
updated message so clients can keep their local copies of the message in sync.
Bot users
To use chat.update with a bot user token, you'll need to think of your bot user as a user, and pass as_user set to true while editing a message created by that same bot user.
Interactive messages with buttons
If you're posting message with buttons, you may use chat.update to continue updating ongoing state changes around a message. Provide the ts field the message you're updating and follow the bot user instructions above to update message text, remove or add attachments and actions.
For more information see https://api.slack.com/methods/update | 62598fc97b180e01f3e49205 |
class Player(pygame.sprite.Sprite): <NEW_LINE> <INDENT> def __init__(self, x, y): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.image = pygame.Surface([10, 10]) <NEW_LINE> self.image.fill(WHITE) <NEW_LINE> self.rect = self.image.get_rect() <NEW_LINE> self.rect.y = y <NEW_LINE> self.rect.x = x <NEW_LINE> self.start_y = y <NEW_LINE> self.start_x = x <NEW_LINE> self.reward = 0 <NEW_LINE> self.parti_y = div_y <NEW_LINE> self.parti_x = div_x <NEW_LINE> self.change_x = 0 <NEW_LINE> self.change_y = 0 <NEW_LINE> self.walls = None <NEW_LINE> self.state = math.floor(self.parti_y*(self.rect.y/SCREEN_HEIGHT))*self.parti_x+math.ceil(self.parti_x*(self.rect.x/SCREEN_WIDTH)) <NEW_LINE> self.sanity = 0 <NEW_LINE> <DEDENT> def changespeed(self, x, y): <NEW_LINE> <INDENT> if self.change_x >= 3 and x > 0: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> elif self.change_x <= -3 and x < 0: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.change_x += x <NEW_LINE> if self.change_x > 3: <NEW_LINE> <INDENT> self.change_x = 3 <NEW_LINE> <DEDENT> elif self.change_x < -3: <NEW_LINE> <INDENT> self.change_x = -3 <NEW_LINE> <DEDENT> <DEDENT> if self.change_y >= 3 and y > 0: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> elif self.change_y <= -3 and y < 0: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.change_y += y <NEW_LINE> if self.change_y > 3: <NEW_LINE> <INDENT> self.change_y =3 <NEW_LINE> <DEDENT> elif self.change_y < -3: <NEW_LINE> <INDENT> self.change_y =-3 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.rect.x += self.change_x <NEW_LINE> block_hit_list = pygame.sprite.spritecollide(self, self.walls, False) <NEW_LINE> for block in block_hit_list: <NEW_LINE> <INDENT> self.rect.y = self.start_y <NEW_LINE> self.rect.x = self.start_x <NEW_LINE> self.reward = 50 <NEW_LINE> self.sanity = 1 <NEW_LINE> <DEDENT> self.rect.y += self.change_y <NEW_LINE> block_hit_list = pygame.sprite.spritecollide(self, self.walls, False) <NEW_LINE> for block in block_hit_list: <NEW_LINE> <INDENT> self.rect.y = self.start_y <NEW_LINE> self.rect.x = self.start_x <NEW_LINE> self.reward = 50 <NEW_LINE> self.sanity = 1 <NEW_LINE> <DEDENT> self.state = math.floor(self.parti_y*(self.rect.y/SCREEN_HEIGHT))*self.parti_x+math.ceil(self.parti_x*(self.rect.x/SCREEN_WIDTH)) <NEW_LINE> if self.state != 2 and self.sanity != 1: <NEW_LINE> <INDENT> self.reward = 5 <NEW_LINE> <DEDENT> if self.state == 2: <NEW_LINE> <INDENT> self.reward = -500 <NEW_LINE> self.rect.y = self.start_y <NEW_LINE> self.rect.x = self.start_x <NEW_LINE> <DEDENT> self.sanity = 0 | This class represents the bar at the bottom that the player
controls. | 62598fc9a219f33f346c6b73 |
class ContentTypeFilter(SimpleListFilter): <NEW_LINE> <INDENT> title = _('Content Type') <NEW_LINE> parameter_name = 'ctype' <NEW_LINE> def lookups(self, request, model_admin): <NEW_LINE> <INDENT> lookup_list = [ (None, _('Site')), ] <NEW_LINE> others = model_admin.model.objects.exclude(content_type=site_ctype()) .order_by().values_list('content_type', flat=True).distinct() <NEW_LINE> for ctype_id in others: <NEW_LINE> <INDENT> ctype = ContentType.objects.get(pk=ctype_id) <NEW_LINE> lookup_list.append((str(ctype_id), str(ctype).title())) <NEW_LINE> <DEDENT> lookup_list.append(('all', _('All'))) <NEW_LINE> return lookup_list <NEW_LINE> <DEDENT> def choices(self, cl): <NEW_LINE> <INDENT> for lookup, title in self.lookup_choices: <NEW_LINE> <INDENT> yield { 'selected': self.value() == lookup, 'query_string': cl.get_query_string({ self.parameter_name: lookup, }, []), 'display': title, } <NEW_LINE> <DEDENT> <DEDENT> def queryset(self, request, queryset): <NEW_LINE> <INDENT> val = self.value() <NEW_LINE> if val == None: <NEW_LINE> <INDENT> return queryset.filter(content_type=site_ctype()) <NEW_LINE> <DEDENT> elif val == 'all': <NEW_LINE> <INDENT> return queryset <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return queryset.filter(content_type=ContentType.objects.get(pk=val)) | Filter on related content type, defaulting to sites.Site instead of
'all'. Assumes a foreignkey to contenttypes.ContentType called
content_type exists on the model. | 62598fc94527f215b58ea23a |
class ExceptionProblemReporterNoExpiration(transitfeed.ProblemReporter): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> accumulator = transitfeed.ExceptionProblemAccumulator(raise_warnings=True) <NEW_LINE> transitfeed.ProblemReporter.__init__(self, accumulator) <NEW_LINE> <DEDENT> def expiration_date(self, expiration, expiration_origin_file, context=None): <NEW_LINE> <INDENT> pass | Ignores feed expiration problems.
Use TestFailureProblemReporter in new code because it fails more cleanly, is
easier to extend and does more thorough checking. | 62598fc9bf627c535bcb1814 |
class Link(Kmlable): <NEW_LINE> <INDENT> def __init__(self, href=" ", refreshmode=None, refreshinterval=None, viewrefreshmode=None, viewrefreshtime=None, viewboundscale=None, viewformat=None, httpquery=None): <NEW_LINE> <INDENT> super(Link, self).__init__() <NEW_LINE> self._kml["href"] = href <NEW_LINE> self._kml["refreshMode"] = refreshmode <NEW_LINE> self._kml["refreshInterval"] = refreshinterval <NEW_LINE> self._kml["viewRefreshMode"] = viewrefreshmode <NEW_LINE> self._kml["viewRefreshTime"] = viewrefreshtime <NEW_LINE> self._kml["viewBoundScale"] = viewboundscale <NEW_LINE> self._kml["viewFormat"] = viewformat <NEW_LINE> self._kml["httpQuery"] = httpquery <NEW_LINE> <DEDENT> @property <NEW_LINE> def href(self): <NEW_LINE> <INDENT> return self._kml['href'] <NEW_LINE> <DEDENT> @href.setter <NEW_LINE> def href(self, href): <NEW_LINE> <INDENT> self._kml['href'] = href <NEW_LINE> <DEDENT> @property <NEW_LINE> def refreshmode(self): <NEW_LINE> <INDENT> return self._kml['refreshMode'] <NEW_LINE> <DEDENT> @refreshmode.setter <NEW_LINE> def refreshmode(self, refreshmode): <NEW_LINE> <INDENT> self._kml['refreshMode'] = refreshmode <NEW_LINE> <DEDENT> @property <NEW_LINE> def refreshinterval(self): <NEW_LINE> <INDENT> return self._kml['refreshInterval'] <NEW_LINE> <DEDENT> @refreshinterval.setter <NEW_LINE> def refreshinterval(self, refreshinterval): <NEW_LINE> <INDENT> self._kml['refreshInterval'] = refreshinterval <NEW_LINE> <DEDENT> @property <NEW_LINE> def viewrefreshmode(self): <NEW_LINE> <INDENT> return self._kml['viewRefreshMode'] <NEW_LINE> <DEDENT> @viewrefreshmode.setter <NEW_LINE> def viewrefreshmode(self, viewrefreshmode): <NEW_LINE> <INDENT> self._kml['viewRefreshMode'] = viewrefreshmode <NEW_LINE> <DEDENT> @property <NEW_LINE> def viewrefreshtime(self): <NEW_LINE> <INDENT> return self._kml['viewRefreshTime'] <NEW_LINE> <DEDENT> @viewrefreshtime.setter <NEW_LINE> def viewrefreshtime(self, viewrefreshtime): <NEW_LINE> <INDENT> self._kml['viewRefreshTime'] = viewrefreshtime <NEW_LINE> <DEDENT> @property <NEW_LINE> def viewboundscale(self): <NEW_LINE> <INDENT> return self._kml['viewBoundScale'] <NEW_LINE> <DEDENT> @viewboundscale.setter <NEW_LINE> def viewboundscale(self, viewboundscale): <NEW_LINE> <INDENT> self._kml['viewBoundScale'] = viewboundscale <NEW_LINE> <DEDENT> @property <NEW_LINE> def viewformat(self): <NEW_LINE> <INDENT> return self._kml['viewFormat'] <NEW_LINE> <DEDENT> @viewformat.setter <NEW_LINE> def viewformat(self, viewformat): <NEW_LINE> <INDENT> self._kml['viewFormat'] = viewformat <NEW_LINE> <DEDENT> @property <NEW_LINE> def httpquery(self): <NEW_LINE> <INDENT> return self._kml['httpQuery'] <NEW_LINE> <DEDENT> @httpquery.setter <NEW_LINE> def httpquery(self, httpquery): <NEW_LINE> <INDENT> self._kml['httpQuery'] = httpquery | Defines an image associated with an Icon style or overlay.
Keyword Arguments:
href (string) -- target url (default None)
refreshmode (string) -- one of [RefreshMode] constants (default None)
refreshinterval (float) -- time between refreshes (default None)
viewrefreshmode (string) -- one of [ViewRefreshMode] constants(default None)
viewrefreshtime (float) -- time to refresh after camera stop (default None)
viewboundscale (float) -- extent to request (default None)
viewformat (string) -- query string format (default None)
httpquery (string) -- extra info for query string (default None)
Properties:
Same as arguments. | 62598fc960cbc95b063646a8 |
class NestedTransaction(Transaction): <NEW_LINE> <INDENT> __slots__ = ("_savepoint",) <NEW_LINE> def __init__(self, connection, parent): <NEW_LINE> <INDENT> super().__init__(connection, parent) <NEW_LINE> self._savepoint = None <NEW_LINE> <DEDENT> async def _do_rollback(self): <NEW_LINE> <INDENT> assert self._savepoint is not None, "Broken transaction logic" <NEW_LINE> if self._is_active: <NEW_LINE> <INDENT> await self._connection._rollback_to_savepoint_impl( self._savepoint, self._parent ) <NEW_LINE> <DEDENT> <DEDENT> async def _do_commit(self): <NEW_LINE> <INDENT> assert self._savepoint is not None, "Broken transaction logic" <NEW_LINE> if self._is_active: <NEW_LINE> <INDENT> await self._connection._release_savepoint_impl( self._savepoint, self._parent ) | Represent a 'nested', or SAVEPOINT transaction.
A new NestedTransaction object may be procured
using the SAConnection.begin_nested() method.
The interface is the same as that of Transaction class. | 62598fc93346ee7daa3377fd |
class AttributeTreatmentEncoder(json.JSONEncoder): <NEW_LINE> <INDENT> def default(self, obj): <NEW_LINE> <INDENT> if isinstance(obj, AttributeTreatment): <NEW_LINE> <INDENT> rep = dict() <NEW_LINE> rep['treatment_type'] = 'attribute_treatment' <NEW_LINE> rep['attribute'] = AttributeEncoder().default(obj.attribute) <NEW_LINE> return rep <NEW_LINE> <DEDENT> return super().default(obj) | A JSONEncoder for the {AttributeTreatment} class. | 62598fc9d8ef3951e32c8011 |
class TestLDAPUserAttributeRead(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 testLDAPUserAttributeRead(self): <NEW_LINE> <INDENT> model = swagger_client.models.ldap_user_attribute_read.LDAPUserAttributeRead() | LDAPUserAttributeRead unit test stubs | 62598fc950812a4eaa620d9a |
class ValidatorMixin(object): <NEW_LINE> <INDENT> def validate(self, data, use_defaults=True): <NEW_LINE> <INDENT> for error in self.iter_errors(data, use_defaults=use_defaults): <NEW_LINE> <INDENT> raise error <NEW_LINE> <DEDENT> <DEDENT> def iter_errors(self, data, path=None, use_defaults=True): <NEW_LINE> <INDENT> for chunk in self.iter_decode(data, path, use_defaults=use_defaults): <NEW_LINE> <INDENT> if isinstance(chunk, XMLSchemaValidationError): <NEW_LINE> <INDENT> yield chunk <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def is_valid(self, data, use_defaults=True): <NEW_LINE> <INDENT> error = next(self.iter_errors(data, use_defaults=use_defaults), None) <NEW_LINE> return error is None <NEW_LINE> <DEDENT> def decode(self, data, *args, **kwargs): <NEW_LINE> <INDENT> validation = kwargs.pop('validation', 'strict') <NEW_LINE> for chunk in self.iter_decode(data, validation=validation, *args, **kwargs): <NEW_LINE> <INDENT> if isinstance(chunk, XMLSchemaValidationError) and validation == 'strict': <NEW_LINE> <INDENT> raise chunk <NEW_LINE> <DEDENT> return chunk <NEW_LINE> <DEDENT> <DEDENT> to_dict = decode <NEW_LINE> def encode(self, data, *args, **kwargs): <NEW_LINE> <INDENT> validation = kwargs.pop('validation', 'strict') <NEW_LINE> for chunk in self.iter_encode(data, validation=validation, *args, **kwargs): <NEW_LINE> <INDENT> if isinstance(chunk, XMLSchemaValidationError) and validation == 'strict': <NEW_LINE> <INDENT> raise chunk <NEW_LINE> <DEDENT> return chunk <NEW_LINE> <DEDENT> <DEDENT> to_etree = encode <NEW_LINE> def iter_decode(self, data, path=None, validation='lax', process_namespaces=True, namespaces=None, use_defaults=True, decimal_type=None, converter=None, dict_class=None, list_class=None): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def iter_encode(self, data, path=None, validation='lax', namespaces=None, indent=None, element_class=None, converter=None): <NEW_LINE> <INDENT> raise NotImplementedError | Mixin for implementing XML Schema validators. A derived class must implement the
methods `iter_decode` and `iter_encode`. | 62598fc94a966d76dd5ef242 |
class SymbolARRAYDECL(Symbol): <NEW_LINE> <INDENT> def __init__(self, symbol): <NEW_LINE> <INDENT> Symbol.__init__(self, symbol._mangled, 'ARRAYDECL') <NEW_LINE> self._type = symbol._type <NEW_LINE> self.size = symbol.total_size <NEW_LINE> self.entry = symbol <NEW_LINE> self.bounds = symbol.bounds | Defines an Array declaration
| 62598fc9656771135c4899dc |
class UpdateRequestMessage(UpdateMessage): <NEW_LINE> <INDENT> @property <NEW_LINE> def summary(self) -> str: <NEW_LINE> <INDENT> status = self.topic.split('.')[-1] <NEW_LINE> if status in ('unpush', 'obsolete', 'revoke'): <NEW_LINE> <INDENT> status = status + (status[-1] == 'e' and 'd' or 'ed') <NEW_LINE> return f"{self.agent} {status} {self.update.alias}" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return f"{self.agent} submitted {self.update.alias} to {status}" | Sent when an update's request is changed. | 62598fc95fcc89381b266303 |
class Gemv(Op): <NEW_LINE> <INDENT> def __init__(self, inplace): <NEW_LINE> <INDENT> self.inplace = inplace <NEW_LINE> if inplace: <NEW_LINE> <INDENT> self.destroy_map = {0: [0]} <NEW_LINE> <DEDENT> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return type(self) == type(other) and self.inplace == other.inplace <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> if self.inplace: <NEW_LINE> <INDENT> return '%s{inplace}' % self.__class__.__name__ <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return '%s{no_inplace}' % self.__class__.__name__ <NEW_LINE> <DEDENT> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash(type(self)) ^ hash(self.inplace) <NEW_LINE> <DEDENT> def make_node(self, y, alpha, A, x, beta): <NEW_LINE> <INDENT> y = T.as_tensor_variable(y) <NEW_LINE> x = T.as_tensor_variable(x) <NEW_LINE> A = T.as_tensor_variable(A) <NEW_LINE> alpha = T.as_tensor_variable(alpha) <NEW_LINE> beta = T.as_tensor_variable(beta) <NEW_LINE> if y.dtype != A.dtype or y.dtype != x.dtype: <NEW_LINE> <INDENT> raise TypeError('Gemv requires matching dtypes', (y.dtype, A.dtype, x.dtype)) <NEW_LINE> <DEDENT> if A.ndim != 2: <NEW_LINE> <INDENT> raise TypeError('gemv requires matrix for A', A.type) <NEW_LINE> <DEDENT> if x.ndim != 1: <NEW_LINE> <INDENT> raise TypeError('gemv requires vector for x', x.type) <NEW_LINE> <DEDENT> if y.ndim != 1: <NEW_LINE> <INDENT> raise TypeError('gemv requires vector for y', y.type) <NEW_LINE> <DEDENT> if y.broadcastable[0] != A.broadcastable[0]: <NEW_LINE> <INDENT> raise TypeError('broadcastable mismatch between y and A', (y.type, A.type)) <NEW_LINE> <DEDENT> return Apply(self, [y, alpha, A, x, beta], [y.type()]) <NEW_LINE> <DEDENT> def perform(self, node, inputs, out_storage): <NEW_LINE> <INDENT> y, alpha, A, x, beta = inputs <NEW_LINE> if (have_fblas and y.shape[0] != 0 and x.shape[0] != 0 and y.dtype in _blas_gemv_fns): <NEW_LINE> <INDENT> gemv = _blas_gemv_fns[y.dtype] <NEW_LINE> if (A.shape[0] != y.shape[0] or A.shape[1] != x.shape[0]): <NEW_LINE> <INDENT> raise ValueError('Incompatible shapes for gemv ' '(beta * y + alpha * dot(A, x)). y: %s, A: %s, x: %s ' % (y.shape, A.shape, x.shape)) <NEW_LINE> <DEDENT> out_storage[0][0] = gemv(alpha, A.T, x, beta, y, overwrite_y=self.inplace, trans=True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> out = numpy.dot(A, x) <NEW_LINE> if alpha != 1: <NEW_LINE> <INDENT> out *= alpha <NEW_LINE> <DEDENT> if beta != 1: <NEW_LINE> <INDENT> out += beta * y <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> out += y <NEW_LINE> <DEDENT> out_storage[0][0] = numpy.asarray(out, dtype=y.dtype) | expression is beta * y + alpha * A x
A is matrix
x, y are vectors
alpha, beta are scalars
output is a vector that can be inplace on y | 62598fc9dc8b845886d53928 |
class Tag(base_model.BaseModel): <NEW_LINE> <INDENT> name = ndb.StringProperty(required=True) <NEW_LINE> hidden = ndb.BooleanProperty(required=True) <NEW_LINE> protect = ndb.BooleanProperty(required=True) <NEW_LINE> color = ndb.StringProperty(choices=_TAG_COLORS, required=True) <NEW_LINE> description = ndb.StringProperty() <NEW_LINE> @classmethod <NEW_LINE> def create( cls, user_email, name, hidden, protect, color, description=None): <NEW_LINE> <INDENT> tag = cls( name=name, hidden=hidden, protect=protect, color=color, description=description) <NEW_LINE> if not name: <NEW_LINE> <INDENT> raise datastore_errors.BadValueError('The tag name must not be empty.') <NEW_LINE> <DEDENT> tag.put() <NEW_LINE> logging.info('Creating a new tag with name %r.', name) <NEW_LINE> tag.stream_to_bq(user_email, 'Created a new tag with name %r.' % name) <NEW_LINE> return tag <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get(cls, name): <NEW_LINE> <INDENT> return cls.query(cls.name == name).get() <NEW_LINE> <DEDENT> def update(self, user_email, **kwargs): <NEW_LINE> <INDENT> if not kwargs['name']: <NEW_LINE> <INDENT> raise datastore_errors.BadValueError('The tag name must not be empty.') <NEW_LINE> <DEDENT> if kwargs['name'] != self.name: <NEW_LINE> <INDENT> logging.info( 'Renaming the tag with name %r to %r.', self.name, kwargs['name']) <NEW_LINE> <DEDENT> self.populate(**kwargs) <NEW_LINE> self.put() <NEW_LINE> logging.info( 'Updating a tag with urlsafe key %r and name %r.', self.key.urlsafe(), self.name) <NEW_LINE> self.stream_to_bq( user_email, 'Updated a tag with name %r.' % self.name) <NEW_LINE> <DEDENT> def _pre_put_hook(self): <NEW_LINE> <INDENT> tag_key = Tag.query(Tag.name == self.name).get(keys_only=True) <NEW_LINE> if tag_key and tag_key != self.key: <NEW_LINE> <INDENT> raise datastore_errors.BadValueError( 'A Tag entity with name %r already exists.' % self.name) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def _pre_delete_hook(cls, key): <NEW_LINE> <INDENT> logging.info( 'Destroying the tag with urlsafe key %r and name %r.', key.urlsafe(), key.get().name) <NEW_LINE> for model in _MODELS_WITH_TAGS: <NEW_LINE> <INDENT> deferred.defer(_delete_tags, model, key.get()) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def list(cls, page_size=10, page_index=1, include_hidden_tags=False, cursor=None): <NEW_LINE> <INDENT> query_object = cls.query() <NEW_LINE> if not include_hidden_tags: <NEW_LINE> <INDENT> query_object = query_object.filter(cls.hidden == False) <NEW_LINE> <DEDENT> return query_object.fetch_page( page_size=page_size, start_cursor=cursor, offset=(page_index - 1) * page_size), int( math.ceil(query_object.count() / page_size)) | Datastore model representing a tag.
Attributes:
name: str, a unique name for the tag.
hidden: bool, whether a tag is hidden in the frontend UI.
protect: bool, whether a tag is protected from user manipulation.
color: str, the UI color of the tag in human-readable format.
description: Optional[str], a description for the tag. | 62598fc9099cdd3c63675598 |
class AppengineAppsModulesListRequest(_messages.Message): <NEW_LINE> <INDENT> name = _messages.StringField(1, required=True) <NEW_LINE> pageSize = _messages.IntegerField(2, variant=_messages.Variant.INT32) <NEW_LINE> pageToken = _messages.StringField(3) | A AppengineAppsModulesListRequest object.
Fields:
name: A string attribute.
pageSize: A integer attribute.
pageToken: A string attribute. | 62598fc95fdd1c0f98e5e2f9 |
class LocalHost: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.deviceid = "localhost" <NEW_LINE> <DEDENT> def shell_cmd(self, cmd="", timeout=15): <NEW_LINE> <INDENT> return shell_command(cmd, timeout) <NEW_LINE> <DEDENT> def check_process(self, process_name): <NEW_LINE> <INDENT> exit_code, ret = shell_command(APP_QUERY_STR % process_name) <NEW_LINE> return len(ret) <NEW_LINE> <DEDENT> def launch_stub(self, stub_app, stub_port="8000", debug_opt=""): <NEW_LINE> <INDENT> cmdline = "%s --port:%s %s" % (stub_app, stub_port, debug_opt) <NEW_LINE> exit_code, ret = self.shell_cmd(cmdline) <NEW_LINE> time.sleep(2) <NEW_LINE> <DEDENT> def check_widget_process(self, wgt_name): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def shell_cmd_ext(self, cmd="", timeout=None, boutput=False, stdout_file=None, stderr_file=None): <NEW_LINE> <INDENT> return shell_command_ext(cmd, timeout, boutput, stdout_file, stderr_file) <NEW_LINE> <DEDENT> def get_device_ids(self): <NEW_LINE> <INDENT> return ['localhost'] <NEW_LINE> <DEDENT> def get_device_info(self): <NEW_LINE> <INDENT> device_info = {} <NEW_LINE> device_info["device_id"] = self.deviceid <NEW_LINE> device_info["resolution"] = "N/A" <NEW_LINE> device_info["screen_size"] = "N/A" <NEW_LINE> device_info["device_model"] = "N/A" <NEW_LINE> device_info["device_name"] = "N/A" <NEW_LINE> device_info["os_version"] = "N/A" <NEW_LINE> device_info["build_id"] = "N/A" <NEW_LINE> return device_info <NEW_LINE> <DEDENT> def get_server_url(self, remote_port="8000"): <NEW_LINE> <INDENT> url_forward = "http://%s:%s" % (HOST_NS, remote_port) <NEW_LINE> return url_forward <NEW_LINE> <DEDENT> def install_package(self, pkgpath): <NEW_LINE> <INDENT> cmd = "rpm -ivh %s" % pkgpath <NEW_LINE> exit_code, ret = shell_command(cmd) <NEW_LINE> return ret <NEW_LINE> <DEDENT> def get_installed_package(self): <NEW_LINE> <INDENT> cmd = "rpm -qa | grep tct" <NEW_LINE> exit_code, ret = shell_command(cmd) <NEW_LINE> return ret <NEW_LINE> <DEDENT> def download_file(self, remote_path, local_path): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def upload_file(self, remote_path, local_path): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def get_launcher_opt(self, test_launcher, test_suite, test_set, fuzzy_match, auto_iu): <NEW_LINE> <INDENT> test_opt = {} <NEW_LINE> test_opt["suite_name"] = test_suite <NEW_LINE> test_opt["launcher"] = test_launcher <NEW_LINE> test_opt["test_app_id"] = test_launcher <NEW_LINE> return test_opt <NEW_LINE> <DEDENT> def launch_app(self, wgt_name): <NEW_LINE> <INDENT> exit_code, ret = shell_command(wgt_name + '&') <NEW_LINE> return True <NEW_LINE> <DEDENT> def kill_app(self, wgt_name): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def start_debug(self, dlogfile): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def stop_debug(self): <NEW_LINE> <INDENT> pass | Implementation for transfer data
between Host and Tizen PC | 62598fc93346ee7daa3377fe |
class Options: <NEW_LINE> <INDENT> def __init__(self) -> None: <NEW_LINE> <INDENT> self._config() <NEW_LINE> self.parse(sys.argv) <NEW_LINE> <DEDENT> def get_columns(self) -> str: <NEW_LINE> <INDENT> return self._columns <NEW_LINE> <DEDENT> def get_hosts(self) -> List[str]: <NEW_LINE> <INDENT> return self._hosts <NEW_LINE> <DEDENT> def get_terminal(self) -> 'Terminal': <NEW_LINE> <INDENT> return self._terminal <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _config() -> None: <NEW_LINE> <INDENT> if "TMUX" in os.environ: <NEW_LINE> <INDENT> del os.environ['TMUX'] <NEW_LINE> <DEDENT> <DEDENT> def parse(self, args: List[str]) -> None: <NEW_LINE> <INDENT> self._columns = '100' <NEW_LINE> invis_flag = False <NEW_LINE> while len(args) > 1: <NEW_LINE> <INDENT> if not args[1].startswith('-'): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if args[1] == '-i': <NEW_LINE> <INDENT> invis_flag = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> xterm = command_mod.Command( 'xterm', args=args[1:], errors='stop' ) <NEW_LINE> subtask_mod.Exec(xterm.get_cmdline()).run() <NEW_LINE> <DEDENT> args = args[1:] <NEW_LINE> <DEDENT> terminals = { 'cinnamon': GnomeTerminal, 'gnome': GnomeTerminal, 'kde': Konsole, 'mate': MateTerminal, 'xfce': XfceTerminal, } <NEW_LINE> if invis_flag: <NEW_LINE> <INDENT> desktop = 'invisible' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> desktop = desktop_mod.Desktop.detect() <NEW_LINE> <DEDENT> self._terminal = terminals.get(desktop, Xterm)(self) <NEW_LINE> if len(args) == 1: <NEW_LINE> <INDENT> self._hosts = [socket.gethostname().split('.')[0].lower()] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._hosts = args[1:] | Options class | 62598fc950812a4eaa620d9b |
class Comment(models.Model): <NEW_LINE> <INDENT> user = models.ForeignKey(to=User, on_delete=models.CASCADE, to_field='user', related_name='comments', verbose_name='用户') <NEW_LINE> topic_id = models.ForeignKey( to=Topic, on_delete=models.CASCADE, related_name='comments', verbose_name='话题') <NEW_LINE> reply_obj = models.ForeignKey(to='self', on_delete=models.CASCADE, verbose_name='回复对象', null=True, related_name='reply') <NEW_LINE> content = HTMLField(verbose_name='评论内容') <NEW_LINE> adoption = models.BooleanField(verbose_name='采纳', default=False, null=False) <NEW_LINE> status = models.BooleanField(verbose_name='审核状态', default=True) <NEW_LINE> delete_status = models.BooleanField(verbose_name='删除状态', default=False) <NEW_LINE> ip = models.CharField(verbose_name='游客ip', max_length=48, null=True) <NEW_LINE> time = models.DateTimeField(verbose_name='评论时间', auto_now_add=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return f'user:{self.user.user} topic:{self.topic_id.title[:10]} status:{self.status}' | 评论模型
| 62598fc963b5f9789fe854e3 |
class Solution1: <NEW_LINE> <INDENT> def sortedArrayToBST(self, nums: List[int]) -> TreeNode: <NEW_LINE> <INDENT> if not nums: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> def helper(nums,left,right): <NEW_LINE> <INDENT> if left > right: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> mid = (left + right) // 2 <NEW_LINE> root = TreeNode(nums[mid]) <NEW_LINE> if left == right: <NEW_LINE> <INDENT> return root <NEW_LINE> <DEDENT> root.left = helper(nums, left, mid-1) <NEW_LINE> root.right = helper(nums, mid+1, right) <NEW_LINE> return root <NEW_LINE> <DEDENT> left, right = 0, len(nums)-1 <NEW_LINE> return helper(nums, left, right) | Time complexity : O(n)
Space complexity : O(n) | 62598fc9ec188e330fdf8c04 |
class battleSetupTest(unittest.TestCase): <NEW_LINE> <INDENT> def testRandomBattle(self): <NEW_LINE> <INDENT> from battle_engine import _battleSetup <NEW_LINE> from monsters.monster import Monster <NEW_LINE> import constants <NEW_LINE> player = MagicMock() <NEW_LINE> space = MagicMock() <NEW_LINE> player.getLocation = MagicMock(return_value = space) <NEW_LINE> space.getRegion = MagicMock(return_value = constants.RegionType.ERIADOR) <NEW_LINE> space.getBattleBonusDifficulty = MagicMock(return_value = 1.5) <NEW_LINE> context = constants.BattleEngineContext.RANDOM <NEW_LINE> result = _battleSetup(player, context) <NEW_LINE> errorMsg = "battleBonusDifficulty was not returned correctly." <NEW_LINE> self.assertEqual(result[0], 1.5, errorMsg) <NEW_LINE> errorMsg = "List of monster objects was not generated correctly." <NEW_LINE> for object in result[1]: <NEW_LINE> <INDENT> self.assertTrue(isinstance(object, Monster), errorMsg) <NEW_LINE> <DEDENT> <DEDENT> def testStoryBattle(self): <NEW_LINE> <INDENT> from battle_engine import _battleSetup <NEW_LINE> import constants <NEW_LINE> player = MagicMock() <NEW_LINE> space = MagicMock() <NEW_LINE> player.getLocation = MagicMock(return_value = space) <NEW_LINE> space.getRegion = MagicMock(return_value = constants.RegionType.ERIADOR) <NEW_LINE> space.getBattleBonusDifficulty = MagicMock(return_value = 1.5) <NEW_LINE> context = constants.BattleEngineContext.STORY <NEW_LINE> result = _battleSetup(player, context) <NEW_LINE> errorMsg = "battleBonusDifficulty was not returned correctly." <NEW_LINE> self.assertEqual(result, 1.5, errorMsg) | Tests _battleSetup helper function in battle_engine.py. | 62598fc9dc8b845886d5392a |
class CoverageReport(Command): <NEW_LINE> <INDENT> description = 'report results of coverage analysis' <NEW_LINE> user_options = [] <NEW_LINE> def initialize_options(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def finalize_options(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> import subprocess <NEW_LINE> subprocess.call(['python-coverage', 'report', '-m']) | Report results of coverage analysis. | 62598fc93d592f4c4edbb221 |
class WikiVersion(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=128, blank=False) <NEW_LINE> author = models.ForeignKey(User, blank=False) <NEW_LINE> date = models.DateTimeField(auto_now_add=True) <NEW_LINE> text = models.TextField() <NEW_LINE> comments = models.ManyToManyField(Comment, blank=True, null=True) <NEW_LINE> edit_reason = models.CharField(max_length=256, blank=True) <NEW_LINE> wiki = models.ForeignKey('Wiki', null=True, blank=True) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return '%s' % self.name | Versión de un artículo de documentación. El
funcionamiento es igual que es de las versiones
en los Titles. | 62598fc9be7bc26dc9252012 |
class Out: <NEW_LINE> <INDENT> def __init__(self, stream=sys.stdout, indent=0): <NEW_LINE> <INDENT> self._stream = stream <NEW_LINE> self._indent = indent <NEW_LINE> <DEDENT> def __call__(self, s): <NEW_LINE> <INDENT> self._stream.write('%s%s\n' % (' ' * 4 * self._indent, s)) <NEW_LINE> <DEDENT> def indent(self): <NEW_LINE> <INDENT> return Out(self._stream, self._indent + 1) | Indents text and writes it to a file.
Useful for generated code. | 62598fc926068e7796d4cccb |
class ExperimentIntroduction(Page): <NEW_LINE> <INDENT> pass | Page introducing the entire experiment.
Assumes this is the first test. | 62598fc9283ffb24f3cf3bf4 |
class Js(models.Model): <NEW_LINE> <INDENT> XN = models.CharField('学年', max_length=18) <NEW_LINE> XQ = models.CharField('学期', max_length=40) <NEW_LINE> JSBH = models.CharField('教室编号', max_length=10) <NEW_LINE> XQJ = models.CharField('星期几', max_length=40) <NEW_LINE> SJD = models.IntegerField('时间点', help_text='1表示第1节课开始,3表示第三节开始') <NEW_LINE> DSZ = models.CharField('单双周', max_length=6) <NEW_LINE> QSZ = models.IntegerField('起始周') <NEW_LINE> JSZ = models.IntegerField('结束周') <NEW_LINE> SKCD = models.IntegerField('上课长度', help_text='2表示2节,3表示3节') <NEW_LINE> XKKH = models.CharField('选课课号', max_length=100) <NEW_LINE> JSZGH = models.CharField('教师职工号', max_length=20) <NEW_LINE> BZ = models.CharField('备注', max_length=400) <NEW_LINE> PK = models.CharField('课表来源', max_length=4) <NEW_LINE> GUID = models.CharField(max_length=50, primary_key=True) <NEW_LINE> JSMC = models.CharField('教室名称', max_length=40) <NEW_LINE> UPD = models.DateField('更新时间', max_length=7) <NEW_LINE> KCZWMC = models.CharField('课程中文名', max_length=460) <NEW_LINE> KCYWMC = models.CharField('课程英文名', max_length=460) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.JSZGH <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = '教学场地/教师表' <NEW_LINE> verbose_name_plural = '教学场地/教师表' <NEW_LINE> db_table = 'DSJ_JW_KB_JXCD_JS' <NEW_LINE> app_label = 'scheduler' <NEW_LINE> permissions = ( ("is_teacher", "教师权限"), ) | 教学场地/教师课程表 | 62598fc9d8ef3951e32c8013 |
class Touch(PythonBatchCommandBase): <NEW_LINE> <INDENT> def __init__(self, path: os.PathLike, **kwargs) -> None: <NEW_LINE> <INDENT> super().__init__(**kwargs) <NEW_LINE> self.path = path <NEW_LINE> <DEDENT> def repr_own_args(self, all_args: List[str]) -> None: <NEW_LINE> <INDENT> all_args.append(self.unnamed__init__param(self.path)) <NEW_LINE> <DEDENT> def progress_msg_self(self): <NEW_LINE> <INDENT> return f"""{self.__class__.__name__} to '{self.path}'""" <NEW_LINE> <DEDENT> def __call__(self, *args, **kwargs): <NEW_LINE> <INDENT> PythonBatchCommandBase.__call__(self, *args, **kwargs) <NEW_LINE> resolved_path = utils.ExpandAndResolvePath(self.path) <NEW_LINE> if resolved_path.is_dir(): <NEW_LINE> <INDENT> os.utime(resolved_path) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> with MakeDir(resolved_path.parent, report_own_progress=False) as md: <NEW_LINE> <INDENT> md() <NEW_LINE> with open(resolved_path, 'a') as tfd: <NEW_LINE> <INDENT> os.utime(resolved_path, None) | Create an empty file if it does not already exist or update modification time to now if file exist | 62598fc9656771135c4899e0 |
class MusicServiceItem(MetadataDictBase): <NEW_LINE> <INDENT> _valid_fields = {} <NEW_LINE> _types = {} <NEW_LINE> def __init__(self, item_id, desc, resources, uri, metadata_dict, music_service=None): <NEW_LINE> <INDENT> _LOG.debug('%s.__init__ with item_id=%s, desc=%s, resources=%s, ' 'uri=%s, metadata_dict=..., music_service=%s', self.__class__.__name__, item_id, desc, resources, uri, music_service) <NEW_LINE> super(MusicServiceItem, self).__init__(metadata_dict) <NEW_LINE> self.item_id = item_id <NEW_LINE> self.desc = desc <NEW_LINE> self.resources = resources <NEW_LINE> self.uri = uri <NEW_LINE> self.music_service = music_service <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_music_service(cls, music_service, content_dict): <NEW_LINE> <INDENT> quoted_id = quote_url(content_dict['id'].encode('utf-8')) <NEW_LINE> item_id = '0fffffff{}'.format(quoted_id) <NEW_LINE> is_track = cls == get_class('MediaMetadataTrack') <NEW_LINE> uri = form_uri(item_id, music_service, is_track) <NEW_LINE> resources = [DidlResource(uri=uri, protocol_info="DUMMY")] <NEW_LINE> desc = music_service.desc <NEW_LINE> return cls(item_id, desc, resources, uri, content_dict, music_service=music_service) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> title = self.metadata.get('title') <NEW_LINE> str_ = '<{} title="{}">' <NEW_LINE> return str_.format(self.__class__.__name__, title) <NEW_LINE> <DEDENT> def to_element(self, include_namespaces=False): <NEW_LINE> <INDENT> didl_item = DidlItem( title="DUMMY", parent_id="DUMMY", item_id=self.item_id, desc=self.desc, resources=self.resources ) <NEW_LINE> return didl_item.to_element(include_namespaces=include_namespaces) | A base class for all music service items | 62598fc9fbf16365ca794429 |
class FloatRange(click.types.FloatParamType): <NEW_LINE> <INDENT> name = 'float range' <NEW_LINE> def __init__(self, min=None, max=None, clamp=False): <NEW_LINE> <INDENT> self.min = min <NEW_LINE> self.max = max <NEW_LINE> self.clamp = clamp <NEW_LINE> <DEDENT> def convert(self, value, param, ctx): <NEW_LINE> <INDENT> rv = click.types.FloatParamType.convert(self, value, param, ctx) <NEW_LINE> if self.clamp: <NEW_LINE> <INDENT> if self.min is not None and rv < self.min: <NEW_LINE> <INDENT> return self.min <NEW_LINE> <DEDENT> if self.max is not None and rv > self.max: <NEW_LINE> <INDENT> return self.max <NEW_LINE> <DEDENT> <DEDENT> if self.min is not None and rv < self.min or self.max is not None and rv > self.max: <NEW_LINE> <INDENT> if self.min is None: <NEW_LINE> <INDENT> self.fail('%s is bigger than the maximum valid value ' '%s.' % (rv, self.max), param, ctx) <NEW_LINE> <DEDENT> elif self.max is None: <NEW_LINE> <INDENT> self.fail('%s is smaller than the minimum valid value ' '%s.' % (rv, self.min), param, ctx) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.fail('%s is not in the valid range of %s to %s.' % (rv, self.min, self.max), param, ctx) <NEW_LINE> <DEDENT> <DEDENT> return rv <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'FloatRange(%r, %r)' % (self.min, self.max) | A parameter that works similar to :data:`click.FLOAT` but restricts
the value to fit into a range. The default behavior is to fail if the
value falls outside the range, but it can also be silently clamped
between the two edges. | 62598fc9d486a94d0ba2c342 |
class Array(DeclNode): <NEW_LINE> <INDENT> def __init__(self, n, child): <NEW_LINE> <INDENT> self.n = n <NEW_LINE> self.child = child <NEW_LINE> super().__init__() | Represents an array of a type.
n (int) - size of the array | 62598fc9ab23a570cc2d4f26 |
@attributes( [ Attribute(name="type", default_value=STAR), Attribute(name="subtype", default_value=STAR), Attribute(name="parameters", default_factory=dict), Attribute(name="quality", default_value=1.0), ], apply_with_cmp=False, ) <NEW_LINE> class MediaRange(object): <NEW_LINE> <INDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, self.__class__): <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> return all( getattr(self, attribute.name) == getattr(other, attribute.name) for attribute in self.characteristic_attributes ) <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, self.__class__): <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> return not self == other <NEW_LINE> <DEDENT> def __lt__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, self.__class__): <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> if self.quality < other.quality: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif self.quality > other.quality: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if self.type != other.type: <NEW_LINE> <INDENT> return self.type is STAR <NEW_LINE> <DEDENT> if self.subtype != other.subtype: <NEW_LINE> <INDENT> return self.subtype is STAR <NEW_LINE> <DEDENT> return viewkeys(self.parameters) < viewkeys(other.parameters) <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> values = tuple( getattr(self, attr.name) for attr in self.characteristic_attributes if attr.name != "parameters" ) <NEW_LINE> return hash(values + tuple(self.parameters.items())) | A media range.
Open ranges (e.g. ``text/*`` or ``*/*``\ ) are represented by
:attr:`type` and / or :attr:`subtype` being ``None``\ . | 62598fc9ec188e330fdf8c06 |
class FirePoint(pyggel.particle.BehaviorPoint): <NEW_LINE> <INDENT> def __init__(self, emitter): <NEW_LINE> <INDENT> pyggel.particle.BehaviorPoint.__init__(self, emitter) <NEW_LINE> self.particle_lifespan = 20 <NEW_LINE> self.point_size = 10 <NEW_LINE> self.max_particles = 105 <NEW_LINE> <DEDENT> def get_dimensions(self): <NEW_LINE> <INDENT> return 2, 6, 2 <NEW_LINE> <DEDENT> def emitter_update(self): <NEW_LINE> <INDENT> for i in xrange(5): <NEW_LINE> <INDENT> self.emitter.particle_type(self.emitter, self) <NEW_LINE> <DEDENT> <DEDENT> def register_particle(self, part): <NEW_LINE> <INDENT> dx = randfloat(-.04, .04) <NEW_LINE> dy = randfloat(.08, .125) <NEW_LINE> dz = randfloat(-.04, .04) <NEW_LINE> part.extra_data["dir"] = (dx, dy, dz) <NEW_LINE> part.colorize = (randfloat(.75,1), randfloat(0,.75), 0, .5) <NEW_LINE> x, y, z = self.emitter.pos <NEW_LINE> part.pos = x + dx * randfloat(1, 3), y, z + dz * randfloat(1, 3) <NEW_LINE> part.colorize = random.choice(((1, 0, 0, 1), (1, .25, 0, 1), (1, 1, 0, 1))) <NEW_LINE> <DEDENT> def particle_update(self, part): <NEW_LINE> <INDENT> pyggel.particle.BehaviorPoint.particle_update(self, part) <NEW_LINE> r, g, b, a = part.colorize <NEW_LINE> g += .01 <NEW_LINE> a -= 0.5/20 <NEW_LINE> part.colorize = r, g, b, a <NEW_LINE> x, y, z = part.pos <NEW_LINE> a, b, c = part.extra_data["dir"] <NEW_LINE> x += a <NEW_LINE> y += b <NEW_LINE> z += c <NEW_LINE> b -= .0025 <NEW_LINE> part.extra_data["dir"] = a, b, c <NEW_LINE> part.pos = x, y, z | This behavior uses the point particles... | 62598fc9167d2b6e312b72e8 |
class UpdateMageCharacter(BaseUpdateCharacterView): <NEW_LINE> <INDENT> template_name = 'characters/create_mage.html' <NEW_LINE> form_class = CreateMageForm <NEW_LINE> model = MageCharacter <NEW_LINE> success_url = 'characters:list' <NEW_LINE> inlines = [MageMeritInline, MageSpecialtyInline, RoteInline] <NEW_LINE> def specialties(self): <NEW_LINE> <INDENT> return MageSpecialty.objects.filter(character=self.get_object()).order_by('skill') <NEW_LINE> <DEDENT> def merits(self): <NEW_LINE> <INDENT> return MageMerit.objects.filter(character=self.get_object()) <NEW_LINE> <DEDENT> def rotes(self): <NEW_LINE> <INDENT> return Rote.objects.filter(character=self.get_object()) | Update a MageCharacter. | 62598fc9dc8b845886d5392c |
class StaticMethod(object): <NEW_LINE> <INDENT> def __init__(self, func): <NEW_LINE> <INDENT> self.func = func <NEW_LINE> <DEDENT> def __get__(self, obj, cls): <NEW_LINE> <INDENT> return self.func | A re-implementation of staticmethod because in python2 you can't have custom attributes on staticmethod.
Useless in python3 | 62598fc926068e7796d4cccd |
class Momentum(object): <NEW_LINE> <INDENT> def __init__(self, learning_rate=0.01, momentum_coeff=0.9): <NEW_LINE> <INDENT> self.learning_rate = learning_rate <NEW_LINE> self.momentum_coeff = momentum_coeff <NEW_LINE> self.velocities = {} <NEW_LINE> <DEDENT> def receive(self, x): <NEW_LINE> <INDENT> values = compute.compute_values(x) <NEW_LINE> gradients = compute.compute_gradients(x, values) <NEW_LINE> for param in self.velocities: <NEW_LINE> <INDENT> self.velocities[param] *= self.momentum_coeff <NEW_LINE> <DEDENT> for param in gradients: <NEW_LINE> <INDENT> if isinstance(param, expr.parameter): <NEW_LINE> <INDENT> if param not in self.velocities: <NEW_LINE> <INDENT> self.velocities[param] = numpy.zeros_like(param.value) <NEW_LINE> <DEDENT> self.velocities[param] -= self.learning_rate * gradients[param] <NEW_LINE> <DEDENT> <DEDENT> for param in self.velocities: <NEW_LINE> <INDENT> param.value += self.velocities[param] <NEW_LINE> <DEDENT> return values[x] | Stochastic gradient descent with momentum. | 62598fc9f9cc0f698b1c548b |
class NSNitroNserrNormalVsNoneListenpol(NSNitroLbErrors): <NEW_LINE> <INDENT> pass | Nitro error code 1355
The vserver already has None Listen Policy | 62598fc9ff9c53063f51a9be |
class PurchasePlanAutoGenerated(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'name': {'required': True}, 'publisher': {'required': True}, 'product': {'required': True}, } <NEW_LINE> _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'publisher': {'key': 'publisher', 'type': 'str'}, 'product': {'key': 'product', 'type': 'str'}, 'promotion_code': {'key': 'promotionCode', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, name: str, publisher: str, product: str, promotion_code: Optional[str] = None, **kwargs ): <NEW_LINE> <INDENT> super(PurchasePlanAutoGenerated, self).__init__(**kwargs) <NEW_LINE> self.name = name <NEW_LINE> self.publisher = publisher <NEW_LINE> self.product = product <NEW_LINE> self.promotion_code = promotion_code | Used for establishing the purchase context of any 3rd Party artifact through MarketPlace.
All required parameters must be populated in order to send to Azure.
:ivar name: Required. The plan ID.
:vartype name: str
:ivar publisher: Required. The publisher ID.
:vartype publisher: str
:ivar product: Required. Specifies the product of the image from the marketplace. This is the
same value as Offer under the imageReference element.
:vartype product: str
:ivar promotion_code: The Offer Promotion Code.
:vartype promotion_code: str | 62598fc963b5f9789fe854e7 |
class TestDeclarativeCommandExtension: <NEW_LINE> <INDENT> @pytest.fixture <NEW_LINE> def config_file(self, tmpdir): <NEW_LINE> <INDENT> config_file = pathlib.Path(str(tmpdir)) / "config.ini" <NEW_LINE> config_file.write_text("[repobee]") <NEW_LINE> return config_file <NEW_LINE> <DEDENT> def test_add_required_option_to_config_show( self, capsys, tmpdir, config_file ): <NEW_LINE> <INDENT> class ConfigShowExt(plug.Plugin, plug.cli.CommandExtension): <NEW_LINE> <INDENT> __settings__ = plug.cli.command_extension_settings( actions=[plug.cli.CoreCommand.config.show] ) <NEW_LINE> silly_new_option = plug.cli.option(help="your name", required=True) <NEW_LINE> <DEDENT> with pytest.raises(SystemExit): <NEW_LINE> <INDENT> repobee.run( "config show".split(), config_file=config_file, plugins=[ConfigShowExt], ) <NEW_LINE> <DEDENT> assert ( "the following arguments are required: --silly-new-option" in capsys.readouterr().err ) <NEW_LINE> <DEDENT> def test_raises_when_command_and_command_extension_are_subclassed_together( self, ): <NEW_LINE> <INDENT> with pytest.raises(plug.PlugError) as exc_info: <NEW_LINE> <INDENT> class Ext( plug.Plugin, plug.cli.Command, plug.cli.CommandExtension ): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> assert ( "A plugin cannot be both a Command and a CommandExtension" in str(exc_info.value) ) <NEW_LINE> <DEDENT> def test_requires_settings(self): <NEW_LINE> <INDENT> with pytest.raises(plug.PlugError) as exc_info: <NEW_LINE> <INDENT> class Ext(plug.Plugin, plug.cli.CommandExtension): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> assert "CommandExtension must have a '__settings__' attribute" in str( exc_info.value ) <NEW_LINE> <DEDENT> def test_requires_non_empty_actions_list(self): <NEW_LINE> <INDENT> with pytest.raises(ValueError) as exc_info: <NEW_LINE> <INDENT> class Ext(plug.Plugin, plug.cli.CommandExtension): <NEW_LINE> <INDENT> __settings__ = plug.cli.command_extension_settings(actions=[]) <NEW_LINE> <DEDENT> <DEDENT> assert "argument 'actions' must be a non-empty list" in str( exc_info.value ) | Test creating command extensions to existing commands. | 62598fc9656771135c4899e2 |
class NotFoundError(HoardException): <NEW_LINE> <INDENT> pass | The related entity could not be found.
:param args[0]: the identity provided by the caller.
:param args[1]: the type of related entity. | 62598fc9283ffb24f3cf3bf7 |
class intSet(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.vals = [] <NEW_LINE> <DEDENT> def insert(self, e): <NEW_LINE> <INDENT> if not e in self.vals: <NEW_LINE> <INDENT> self.vals.append(e) <NEW_LINE> <DEDENT> <DEDENT> def member(self, e): <NEW_LINE> <INDENT> return e in self.vals <NEW_LINE> <DEDENT> def remove(self, e): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.vals.remove(e) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise ValueError(str(e) + ' not found') <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> self.vals.sort() <NEW_LINE> return '{' + ','.join([str(e) for e in self.vals]) + '}' <NEW_LINE> <DEDENT> def interset(self,other): <NEW_LINE> <INDENT> assert type(self)==type(other) <NEW_LINE> newset=[] <NEW_LINE> for e in self.vals: <NEW_LINE> <INDENT> if e in other.vals: <NEW_LINE> <INDENT> newset.append(e) <NEW_LINE> <DEDENT> <DEDENT> return newset <NEW_LINE> <DEDENT> def len(self): <NEW_LINE> <INDENT> num=0 <NEW_LINE> for e in self.vals: <NEW_LINE> <INDENT> num+=1 <NEW_LINE> <DEDENT> return num | An intSet is a set of integers
The value is represented by a list of ints, self.vals.
Each int in the set occurs in self.vals exactly once. | 62598fc997e22403b383b277 |
class PairedDataset(Dataset): <NEW_LINE> <INDENT> def __init__(self, datasets, n_elements, max_iters, same=True, pair_based_transforms=None): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.datasets = datasets <NEW_LINE> self.n_datasets = len(self.datasets) <NEW_LINE> self.n_data = [len(dataset) for dataset in self.datasets] <NEW_LINE> self.n_elements = n_elements <NEW_LINE> self.max_iters = max_iters <NEW_LINE> self.pair_based_transforms = pair_based_transforms <NEW_LINE> if same: <NEW_LINE> <INDENT> if isinstance(self.n_elements, int): <NEW_LINE> <INDENT> datasets_indices = [random.randrange(self.n_datasets) for _ in range(self.max_iters)] <NEW_LINE> self.indices = [[(dataset_idx, data_idx) for data_idx in random.choices(range(self.n_data[dataset_idx]), k=self.n_elements)] for dataset_idx in datasets_indices] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("When 'same=true', 'n_element' should be an integer.") <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if isinstance(self.n_elements, list): <NEW_LINE> <INDENT> self.indices = [[(dataset_idx, data_idx) for i, dataset_idx in enumerate( random.sample(range(self.n_datasets), k=len(self.n_elements))) for data_idx in random.sample(range(self.n_data[dataset_idx]), k=self.n_elements[i])] for i_iter in range(self.max_iters)] <NEW_LINE> <DEDENT> elif self.n_elements > self.n_datasets: <NEW_LINE> <INDENT> raise ValueError("When 'same=False', 'n_element' should be no more than n_datasets") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.indices = [[(dataset_idx, random.randrange(self.n_data[dataset_idx])) for dataset_idx in random.sample(range(self.n_datasets), k=n_elements)] for i in range(max_iters)] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return self.max_iters <NEW_LINE> <DEDENT> def __getitem__(self, idx): <NEW_LINE> <INDENT> sample = [self.datasets[dataset_idx][data_idx] for dataset_idx, data_idx in self.indices[idx]] <NEW_LINE> if self.pair_based_transforms is not None: <NEW_LINE> <INDENT> for transform, args in self.pair_based_transforms: <NEW_LINE> <INDENT> sample = transform(sample, **args) <NEW_LINE> <DEDENT> <DEDENT> return sample | Make pairs of data from dataset
When 'same=True',
a pair contains data from same datasets,
and the choice of datasets for each pair is random.
e.g. [[ds1_3, ds1_2], [ds3_1, ds3_2], [ds2_1, ds2_2], ...]
When 'same=False',
a pair contains data from different datasets,
if 'n_elements' <= # of datasets, then we randomly choose a subset of datasets,
then randomly choose a sample from each dataset in the subset
e.g. [[ds1_3, ds2_1, ds3_1], [ds4_1, ds2_3, ds3_2], ...]
if 'n_element' is a list of int, say [C_1, C_2, C_3, ..., C_k], we first
randomly choose k(k < # of datasets) datasets, then draw C_1, C_2, ..., C_k samples
from each dataset respectively.
Note the total number of elements will be (C_1 + C_2 + ... + C_k).
Args:
datasets:
source datasets, expect a list of Dataset
n_elements:
number of elements in a pair
max_iters:
number of pairs to be sampled
same:
whether data samples in a pair are from the same dataset or not,
see a detailed explanation above.
pair_based_transforms:
some transformation performed on a pair basis, expect a list of functions,
each function takes a pair sample and return a transformed one. | 62598fc9ec188e330fdf8c08 |
class BaseModel: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.db = init_connection() <NEW_LINE> <DEDENT> def get_email(self, email): <NEW_LINE> <INDENT> query = """SELECT email FROM app_users WHERE email=%s""" <NEW_LINE> cursor = self.db.cursor() <NEW_LINE> cursor.execute(query, (email,)) <NEW_LINE> result = cursor.fetchone() <NEW_LINE> return result <NEW_LINE> <DEDENT> def get_user(self, email): <NEW_LINE> <INDENT> query = """SELECT * FROM app_users WHERE email=%s""" <NEW_LINE> cursor = self.db.cursor() <NEW_LINE> cursor.execute(query, (email,)) <NEW_LINE> result = cursor.fetchone() <NEW_LINE> return result <NEW_LINE> <DEDENT> def delete_user(self, email): <NEW_LINE> <INDENT> user = self.get_user(email) <NEW_LINE> if user: <NEW_LINE> <INDENT> query = """ DELETE FROM app_users WHERE email=%s""" <NEW_LINE> curr = self.db.cursor() <NEW_LINE> curr.execute(query, (email,)) <NEW_LINE> curr.commit() <NEW_LINE> return email <NEW_LINE> <DEDENT> <DEDENT> def post_data(self, query, data): <NEW_LINE> <INDENT> curr = self.db.cursor() <NEW_LINE> curr.execute(query, data) <NEW_LINE> self.db.commit() <NEW_LINE> return data <NEW_LINE> <DEDENT> def get_data(self, query): <NEW_LINE> <INDENT> curr = self.db.cursor(cursor_factory=RealDictCursor) <NEW_LINE> curr.execute(query) <NEW_LINE> result = curr.fetchall() <NEW_LINE> return result <NEW_LINE> <DEDENT> def delete_data(self, query, meetup_id): <NEW_LINE> <INDENT> curr = self.db.cursor() <NEW_LINE> curr.execute(query, meetup_id) <NEW_LINE> self.db.commit() <NEW_LINE> return True | Base model to initiate db | 62598fc93d592f4c4edbb225 |
class TestResult: <NEW_LINE> <INDENT> def __init__(self, status=None, duration=None, tv_ip=None, tv_mac=None): <NEW_LINE> <INDENT> if status is None: <NEW_LINE> <INDENT> self._status = TEST_STATUS.blocked <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._status = TEST_STATUS(status) <NEW_LINE> <DEDENT> self.duration = duration <NEW_LINE> self.tv_ip = tv_ip <NEW_LINE> self.tv_mac = tv_mac <NEW_LINE> self.tv_chassis = None <NEW_LINE> self.tv_software = None <NEW_LINE> self.detailed_result = None <NEW_LINE> self.crashes = [] <NEW_LINE> self.__logs = [] <NEW_LINE> <DEDENT> @property <NEW_LINE> def status(self): <NEW_LINE> <INDENT> return self._status <NEW_LINE> <DEDENT> @property <NEW_LINE> def logs(self): <NEW_LINE> <INDENT> return self.__logs <NEW_LINE> <DEDENT> @logs.setter <NEW_LINE> def logs(self, val): <NEW_LINE> <INDENT> self.__logs = list(val) <NEW_LINE> <DEDENT> @status.setter <NEW_LINE> def status(self, value): <NEW_LINE> <INDENT> if value is None: <NEW_LINE> <INDENT> self._status = TEST_STATUS.blocked <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._status = TEST_STATUS(value) <NEW_LINE> <DEDENT> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> r = { 'status': self.status.value, 'duration': self.duration and str(self.duration), 'tv_ip': self.tv_ip, 'tv_mac': self.tv_mac, 'tv_chassis': self.tv_chassis, 'tv_software': self.tv_software, 'detailed_result': self.detailed_result, 'crashes': self.crashes, 'logs': self.logs, } <NEW_LINE> return r | Controller for generating detailed test run results | 62598fc9a8370b77170f074d |
class SizeUnitType (pyxb.binding.datatypes.string, pyxb.binding.basis.enumeration_mixin): <NEW_LINE> <INDENT> _ExpandedName = pyxb.namespace.ExpandedName(Namespace, 'SizeUnitType') <NEW_LINE> _XSDLocation = pyxb.utils.utility.Location('MapsPlatformDescriptor.xsd', 145, 2) <NEW_LINE> _Documentation = None | An atomic simple type. | 62598fc9be7bc26dc9252014 |
class List(core_models.TimeStampedModel): <NEW_LINE> <INDENT> name = models.CharField(max_length=80) <NEW_LINE> user = models.ForeignKey( "users.User", related_name="lists", on_delete=models.CASCADE ) <NEW_LINE> rooms = models.ManyToManyField("rooms.Room", related_name="lists", blank=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def count_rooms(self): <NEW_LINE> <INDENT> return self.rooms.count() <NEW_LINE> <DEDENT> count_rooms.short_description = "number of rooms" | List Model Definition | 62598fc98a349b6b436865b2 |
class BaseTypeDriver(api.TypeDriver): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.physnet_mtus = utils.parse_mappings( cfg.CONF.ml2.physical_network_mtus ) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> self.physnet_mtus = [] <NEW_LINE> <DEDENT> <DEDENT> def get_mtu(self, physical_network=None): <NEW_LINE> <INDENT> return cfg.CONF.ml2.segment_mtu | BaseTypeDriver for functions common to Segment and flat. | 62598fc9cc40096d6161a391 |
class UserSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = get_user_model() <NEW_LINE> fields = ('email', 'password', 'name') <NEW_LINE> extra_kwargs = {'password': {'write_only': True, 'min_length': 5}} <NEW_LINE> <DEDENT> def create(self, validated_data): <NEW_LINE> <INDENT> return get_user_model().objects.create_user(**validated_data) <NEW_LINE> <DEDENT> def update(self, instance, validated_data): <NEW_LINE> <INDENT> password = validated_data.pop('password', None) <NEW_LINE> user = super().update(instance, validated_data) <NEW_LINE> if password: <NEW_LINE> <INDENT> user.set_password(password) <NEW_LINE> user.save() <NEW_LINE> <DEDENT> return user | Serializer for the users object | 62598fc9f9cc0f698b1c548c |
class Microphone: <NEW_LINE> <INDENT> def __init__(self, usb_port, coord): <NEW_LINE> <INDENT> self.usb_port = usb_port <NEW_LINE> self.coord = coord <NEW_LINE> self.angle = coord.get_angle() <NEW_LINE> self.serial = '' <NEW_LINE> self.buffer = [] <NEW_LINE> self.dt = 0 <NEW_LINE> <DEDENT> def set_buffer(self, test_list): <NEW_LINE> <INDENT> self.buffer = test_list <NEW_LINE> <DEDENT> def read(self): <NEW_LINE> <INDENT> return false <NEW_LINE> <DEDENT> def write(self, intensity, duration, buzzer_id): <NEW_LINE> <INDENT> message = str(intensity) + ',' + str(duration) + ',' + str(buzzer_id) <NEW_LINE> self.serial.write(message) <NEW_LINE> <DEDENT> def hasNext(self): <NEW_LINE> <INDENT> return len(self.buffer) != 0 <NEW_LINE> <DEDENT> def next(self): <NEW_LINE> <INDENT> if not self.hasNext(): <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> temp = self.buffer[0] <NEW_LINE> del self.buffer[0] <NEW_LINE> return temp <NEW_LINE> <DEDENT> def get_angle(self): <NEW_LINE> <INDENT> return self.angle <NEW_LINE> <DEDENT> def get_coord(self): <NEW_LINE> <INDENT> return self.get_coord | Contains a buffer that has all the 64 byte info. The buffer will read off
all the data that the arduino recorded. | 62598fc94a966d76dd5ef24a |
class Tigertail(object): <NEW_LINE> <INDENT> USB_VID = 0x18d1 <NEW_LINE> USB_PID = 0x5027 <NEW_LINE> READ_EP_OFFSET = 0x81 <NEW_LINE> WRITE_EP_OFFSET = 0x1 <NEW_LINE> def __init__(self, serial): <NEW_LINE> <INDENT> devices = usb.core.find(idVendor=self.USB_VID, idProduct=self.USB_PID, find_all=True) <NEW_LINE> if not devices: <NEW_LINE> <INDENT> raise TigertailError('Unable to find Tigertail.') <NEW_LINE> <DEDENT> if serial: <NEW_LINE> <INDENT> for device in devices: <NEW_LINE> <INDENT> if usb.util.get_string(device, device.iSerialNumber) == str(serial): <NEW_LINE> <INDENT> self._device = device <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise TigertailError( 'Unable to find Tigertail with serial number {}.'.format(serial)) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self._device = devices.next() <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self._device.set_configuration() <NEW_LINE> <DEDENT> except usb.core.USBError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> config = self._device.get_active_configuration() <NEW_LINE> interface = usb.util.find_descriptor(config, bInterfaceNumber=0) <NEW_LINE> if not interface: <NEW_LINE> <INDENT> raise TigertailError('Tigertail interface not found.') <NEW_LINE> <DEDENT> if self._device.is_kernel_driver_active(interface.bInterfaceNumber): <NEW_LINE> <INDENT> self._device.detach_kernel_driver(interface.bInterfaceNumber) <NEW_LINE> <DEDENT> read_endpoint_number = interface.bInterfaceNumber + self.READ_EP_OFFSET <NEW_LINE> self._read_endpoint = usb.util.find_descriptor( interface, bEndpointAddress=read_endpoint_number) <NEW_LINE> write_endpoint_number = interface.bInterfaceNumber + self.WRITE_EP_OFFSET <NEW_LINE> self._write_endpoint = usb.util.find_descriptor( interface, bEndpointAddress=write_endpoint_number) <NEW_LINE> <DEDENT> def off(self): <NEW_LINE> <INDENT> self._mux('off') <NEW_LINE> <DEDENT> def sel_a(self): <NEW_LINE> <INDENT> self._mux('A') <NEW_LINE> <DEDENT> def sel_b(self): <NEW_LINE> <INDENT> self._mux('B') <NEW_LINE> <DEDENT> def _mux(self, option): <NEW_LINE> <INDENT> self._write_endpoint.write('mux {}\r\n'.format(option)) | Class representing a Google Tigertail device.
Args:
serial: A string that's the serial number of the Tigertail device. | 62598fc9fbf16365ca79442d |
class JsonRetrieveMixin(RetrieveModelMixin): <NEW_LINE> <INDENT> def retrieve(self, request, *args, **kwargs): <NEW_LINE> <INDENT> response = super(JsonRetrieveMixin, self).retrieve(request, *args, **kwargs) <NEW_LINE> logger.debug('JsonRetrieveMixin:retrieve:' + str(type(response.data))) <NEW_LINE> return make_response(response) | Retrieve a model instance.
override retrieve method
return whth error_code:success | 62598fc97c178a314d78d813 |
class MonitoringInvalidValueTypeError(MonitoringError): <NEW_LINE> <INDENT> def __init__(self, metric, value): <NEW_LINE> <INDENT> self.metric = metric <NEW_LINE> self.value = value <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return 'Metric "%s" was given invalid value "%s" (%s).' % ( self.metric, self.value, type(self.value)) | Raised when sending a metric value is not a valid type. | 62598fc9dc8b845886d53930 |
class SubscriptionPlotting(object): <NEW_LINE> <INDENT> openapi_types = { 'enabled': 'bool', 'theme': 'str' } <NEW_LINE> attribute_map = { 'enabled': 'enabled', 'theme': 'theme' } <NEW_LINE> def __init__(self, enabled=None, theme=None, local_vars_configuration=None): <NEW_LINE> <INDENT> if local_vars_configuration is None: <NEW_LINE> <INDENT> local_vars_configuration = Configuration() <NEW_LINE> <DEDENT> self.local_vars_configuration = local_vars_configuration <NEW_LINE> self._enabled = None <NEW_LINE> self._theme = None <NEW_LINE> self.discriminator = None <NEW_LINE> if enabled is not None: <NEW_LINE> <INDENT> self.enabled = enabled <NEW_LINE> <DEDENT> if theme is not None: <NEW_LINE> <INDENT> self.theme = theme <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def enabled(self): <NEW_LINE> <INDENT> return self._enabled <NEW_LINE> <DEDENT> @enabled.setter <NEW_LINE> def enabled(self, enabled): <NEW_LINE> <INDENT> self._enabled = enabled <NEW_LINE> <DEDENT> @property <NEW_LINE> def theme(self): <NEW_LINE> <INDENT> return self._theme <NEW_LINE> <DEDENT> @theme.setter <NEW_LINE> def theme(self, theme): <NEW_LINE> <INDENT> allowed_values = ["light", "dark"] <NEW_LINE> if self.local_vars_configuration.client_side_validation and theme not in allowed_values: <NEW_LINE> <INDENT> raise ValueError( "Invalid value for `theme` ({0}), must be one of {1}" .format(theme, allowed_values) ) <NEW_LINE> <DEDENT> self._theme = theme <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, SubscriptionPlotting): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.to_dict() == other.to_dict() <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, SubscriptionPlotting): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.to_dict() != other.to_dict() | NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually. | 62598fc98a349b6b436865b4 |
@pytest.mark.usefixtures <NEW_LINE> class TestSpiderFootThreadPool(unittest.TestCase): <NEW_LINE> <INDENT> def test_threadPool(self): <NEW_LINE> <INDENT> threads = 10 <NEW_LINE> def callback(x, *args, **kwargs): <NEW_LINE> <INDENT> return (x, args, list(kwargs.items())[0]) <NEW_LINE> <DEDENT> iterable = ["a", "b", "c"] <NEW_LINE> args = ("arg1",) <NEW_LINE> kwargs = {"kwarg1": "kwarg1"} <NEW_LINE> expectedOutput = [ ("a", ("arg1",), ("kwarg1", "kwarg1")), ("b", ("arg1",), ("kwarg1", "kwarg1")), ("c", ("arg1",), ("kwarg1", "kwarg1")) ] <NEW_LINE> with SpiderFootThreadPool(threads) as pool: <NEW_LINE> <INDENT> map_results = sorted( list(pool.map( callback, iterable, *args, saveResult=True, **kwargs )), key=lambda x: x[0] ) <NEW_LINE> <DEDENT> self.assertEqual(map_results, expectedOutput) <NEW_LINE> with SpiderFootThreadPool(threads) as pool: <NEW_LINE> <INDENT> pool.start() <NEW_LINE> for i in iterable: <NEW_LINE> <INDENT> pool.submit(callback, *((i,) + args), saveResult=True, **kwargs) <NEW_LINE> <DEDENT> submit_results = sorted( list(pool.shutdown()["default"]), key=lambda x: x[0] ) <NEW_LINE> <DEDENT> self.assertEqual(submit_results, expectedOutput) <NEW_LINE> threads = 1 <NEW_LINE> iterable2 = ["d", "e", "f"] <NEW_LINE> expectedOutput2 = [ ("d", ("arg1",), ("kwarg1", "kwarg1")), ("e", ("arg1",), ("kwarg1", "kwarg1")), ("f", ("arg1",), ("kwarg1", "kwarg1")) ] <NEW_LINE> pool = SpiderFootThreadPool(threads) <NEW_LINE> pool.start() <NEW_LINE> for i in iterable2: <NEW_LINE> <INDENT> pool.submit(callback, *((i,) + args), taskName="submitTest", saveResult=True, **kwargs) <NEW_LINE> <DEDENT> map_results = sorted( list(pool.map( callback, iterable, *args, taskName="mapTest", saveResult=True, **kwargs )), key=lambda x: x[0] ) <NEW_LINE> submit_results = sorted( list(pool.shutdown()["submitTest"]), key=lambda x: x[0] ) <NEW_LINE> self.assertEqual(map_results, expectedOutput) <NEW_LINE> self.assertEqual(submit_results, expectedOutput2) | Test SpiderFoot | 62598fc95fdd1c0f98e5e301 |
class TestPillarSharingBreadcrumb(BaseBreadcrumbTestCase, SharingBaseTestCase): <NEW_LINE> <INDENT> pillar_type = 'product' <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> super(TestPillarSharingBreadcrumb, self).setUp() <NEW_LINE> login_person(self.driver) <NEW_LINE> <DEDENT> def test_sharing_breadcrumb(self): <NEW_LINE> <INDENT> crumbs = [self.pillar.displayname, 'Sharing'] <NEW_LINE> self.assertBreadcrumbTexts( expected=crumbs, obj=self.pillar, view_name="+sharing") <NEW_LINE> <DEDENT> def test_sharing_details_breadcrumbs(self): <NEW_LINE> <INDENT> grantee = self.makeArtifactGrantee() <NEW_LINE> expected_crumbs = [ self.pillar.displayname, 'Sharing', 'Sharing details for %s' % grantee.displayname, ] <NEW_LINE> url = 'https://launchpad.dev/%s/+sharing/%s' % ( self.pillar.name, grantee.name) <NEW_LINE> crumbs = [c.text for c in self.getBreadcrumbsForUrl(url)] <NEW_LINE> self.assertEqual(expected_crumbs, crumbs) | Test breadcrumbs for the sharing views. | 62598fc9283ffb24f3cf3bfa |
class f_gen(rv_continuous): <NEW_LINE> <INDENT> def _rvs(self, dfn, dfd): <NEW_LINE> <INDENT> return self._random_state.f(dfn, dfd, self._size) <NEW_LINE> <DEDENT> def _pdf(self, x, dfn, dfd): <NEW_LINE> <INDENT> return np.exp(self._logpdf(x, dfn, dfd)) <NEW_LINE> <DEDENT> def _logpdf(self, x, dfn, dfd): <NEW_LINE> <INDENT> n = 1.0 * dfn <NEW_LINE> m = 1.0 * dfd <NEW_LINE> lPx = m/2 * np.log(m) + n/2 * np.log(n) + sc.xlogy(n/2 - 1, x) <NEW_LINE> lPx -= ((n+m)/2) * np.log(m + n*x) + sc.betaln(n/2, m/2) <NEW_LINE> return lPx <NEW_LINE> <DEDENT> def _cdf(self, x, dfn, dfd): <NEW_LINE> <INDENT> return sc.fdtr(dfn, dfd, x) <NEW_LINE> <DEDENT> def _sf(self, x, dfn, dfd): <NEW_LINE> <INDENT> return sc.fdtrc(dfn, dfd, x) <NEW_LINE> <DEDENT> def _ppf(self, q, dfn, dfd): <NEW_LINE> <INDENT> return sc.fdtri(dfn, dfd, q) <NEW_LINE> <DEDENT> def _stats(self, dfn, dfd): <NEW_LINE> <INDENT> v1, v2 = 1. * dfn, 1. * dfd <NEW_LINE> v2_2, v2_4, v2_6, v2_8 = v2 - 2., v2 - 4., v2 - 6., v2 - 8. <NEW_LINE> mu = _lazywhere( v2 > 2, (v2, v2_2), lambda v2, v2_2: v2 / v2_2, np.inf) <NEW_LINE> mu2 = _lazywhere( v2 > 4, (v1, v2, v2_2, v2_4), lambda v1, v2, v2_2, v2_4: 2 * v2 * v2 * (v1 + v2_2) / (v1 * v2_2**2 * v2_4), np.inf) <NEW_LINE> g1 = _lazywhere( v2 > 6, (v1, v2_2, v2_4, v2_6), lambda v1, v2_2, v2_4, v2_6: (2 * v1 + v2_2) / v2_6 * np.sqrt(v2_4 / (v1 * (v1 + v2_2))), np.nan) <NEW_LINE> g1 *= np.sqrt(8.) <NEW_LINE> g2 = _lazywhere( v2 > 8, (g1, v2_6, v2_8), lambda g1, v2_6, v2_8: (8 + g1 * g1 * v2_6) / v2_8, np.nan) <NEW_LINE> g2 *= 3. / 2. <NEW_LINE> return mu, mu2, g1, g2 | An F continuous random variable.
%(before_notes)s
Notes
-----
The probability density function for `f` is:
.. math::
f(x, df_1, df_2) = \frac{df_2^{df_2/2} df_1^{df_1/2} x^{df_1 / 2-1}}
{(df_2+df_1 x)^{(df_1+df_2)/2}
B(df_1/2, df_2/2)}
for :math:`x > 0`.
`f` takes ``dfn`` and ``dfd`` as shape parameters.
%(after_notes)s
%(example)s | 62598fc9f9cc0f698b1c548d |
class Messages(list): <NEW_LINE> <INDENT> def __init__(self, msg_list=None, max_history=None): <NEW_LINE> <INDENT> if msg_list: <NEW_LINE> <INDENT> super(Messages, self).__init__(msg_list) <NEW_LINE> <DEDENT> self.max_history = max_history <NEW_LINE> <DEDENT> def append(self, msg): <NEW_LINE> <INDENT> if isinstance(self.max_history, int) and self.max_history > 0: <NEW_LINE> <INDENT> del self[:-self.max_history + 1] <NEW_LINE> <DEDENT> return super(Messages, self).append(msg) <NEW_LINE> <DEDENT> def search(self, keywords=None, **attributes): <NEW_LINE> <INDENT> def match(msg): <NEW_LINE> <INDENT> if not match_text(msg.text, keywords): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if not match_attributes(msg, **attributes): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> return Messages(filter(match, self), max_history=self.max_history) | 多条消息的合集,可用于记录或搜索 | 62598fc971ff763f4b5e7af5 |
class ContrackAccuracy(tf.keras.metrics.Mean): <NEW_LINE> <INDENT> def __init__(self, section_name, dtype=None): <NEW_LINE> <INDENT> self.encodings = Env.get().encodings <NEW_LINE> self.section_name = section_name <NEW_LINE> super(ContrackAccuracy, self).__init__( name=f'{section_name}/accuracy', dtype=dtype) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_config(cls, config): <NEW_LINE> <INDENT> return ContrackAccuracy(config['section_name']) <NEW_LINE> <DEDENT> def get_config(self): <NEW_LINE> <INDENT> return {'section_name': self.section_name} <NEW_LINE> <DEDENT> def update_state(self, y_true, logits, sample_weight = None): <NEW_LINE> <INDENT> y_true, logits = _get_named_slices( self.encodings.as_prediction_encoding(y_true), self.encodings.as_prediction_encoding(logits), self.section_name) <NEW_LINE> y_pred = tf.cast(logits > 0.0, tf.float32) <NEW_LINE> matches = tf.reduce_max(tf.cast(y_true == y_pred, tf.float32), -1) <NEW_LINE> super(ContrackAccuracy, self).update_state(matches, sample_weight) | Computes zero-one accuracy on a given slice of the result vector. | 62598fc9377c676e912f6f31 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.