code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class CashInpostResponse(object): <NEW_LINE> <INDENT> def __init__(self, auth_id_response=None, response_code=None, receiver_transaction_id=None): <NEW_LINE> <INDENT> self.swagger_types = { 'auth_id_response': 'str', 'response_code': 'str', 'receiver_transaction_id': 'str' } <NEW_LINE> self.attribute_map = { 'auth_id_response': 'authIdResponse', 'response_code': 'responseCode', 'receiver_transaction_id': 'receiverTransactionId' } <NEW_LINE> self._auth_id_response = auth_id_response <NEW_LINE> self._response_code = response_code <NEW_LINE> self._receiver_transaction_id = receiver_transaction_id <NEW_LINE> <DEDENT> @property <NEW_LINE> def auth_id_response(self): <NEW_LINE> <INDENT> return self._auth_id_response <NEW_LINE> <DEDENT> @auth_id_response.setter <NEW_LINE> def auth_id_response(self, auth_id_response): <NEW_LINE> <INDENT> self._auth_id_response = auth_id_response <NEW_LINE> <DEDENT> @property <NEW_LINE> def response_code(self): <NEW_LINE> <INDENT> return self._response_code <NEW_LINE> <DEDENT> @response_code.setter <NEW_LINE> def response_code(self, response_code): <NEW_LINE> <INDENT> if response_code is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `response_code`, must not be `None`") <NEW_LINE> <DEDENT> self._response_code = response_code <NEW_LINE> <DEDENT> @property <NEW_LINE> def receiver_transaction_id(self): <NEW_LINE> <INDENT> return self._receiver_transaction_id <NEW_LINE> <DEDENT> @receiver_transaction_id.setter <NEW_LINE> def receiver_transaction_id(self, receiver_transaction_id): <NEW_LINE> <INDENT> self._receiver_transaction_id = receiver_transaction_id <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return 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, CashInpostResponse): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 62598fa70c0af96317c5628b |
class Tangente(PlanePage): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> PlanePage.__init__(self, u'Gráfica de la tangente<br><br>α(x)=(x,tan x)') <NEW_LINE> npuntos = 100 <NEW_LINE> delta = .2 <NEW_LINE> def Tan(t): <NEW_LINE> <INDENT> return Vec3(t, tan(t), 0) <NEW_LINE> <DEDENT> def Derivada(t): <NEW_LINE> <INDENT> return Vec3(1, 1 / cos(t) ** 2, 0) <NEW_LINE> <DEDENT> rango = [ (-pi, -pi / 2 - delta, npuntos), (-pi / 2 + delta, pi / 2 - delta, npuntos), (pi / 2 + delta, pi, npuntos) ] <NEW_LINE> curva1 = Curve3D(Tan, rango, width=2).setBoundingBox((-5, 5), (-5, 5)) <NEW_LINE> self.addChild(curva1) <NEW_LINE> self.addChild(Line([(-pi / 2, -5, 0), (-pi / 2, 5, 0)], color=(1, .5, .5))) <NEW_LINE> self.addChild(Line([(pi / 2, -5, 0), (pi / 2, 5, 0)], color=(1, .5, .5))) <NEW_LINE> tangente = curva1.attachField("tangente", Derivada) <NEW_LINE> tangente.add_tail(radius=0.08) <NEW_LINE> self.setupAnimations([tangente]) | La función tangente establece un <b>difeomorfismo</b> entre un segmento
abierto y la totalidad de los números reales. La gráfica de un periodo
es una curva infinitamente diferenciable que admite dos asíntotas:
una a la izquierda y otra a la derecha. Una <b>asíntota</b> de una curva es
una recta a la cual la curva se acerca tanto como se quiera, sin
cortarla y teniendo a la recta como límite de la posición de sus
tangentes cuando la norma de <b>(x, tan x)</b> tiende a infinito. | 62598fa701c39578d7f12c88 |
class MatchList(Match): <NEW_LINE> <INDENT> def __init__(self, doc, pos=None): <NEW_LINE> <INDENT> self._orig = doc <NEW_LINE> self._doc = [] <NEW_LINE> for ele in doc: <NEW_LINE> <INDENT> if isinstance(ele, list): <NEW_LINE> <INDENT> self._doc.append(MatchList(ele)) <NEW_LINE> <DEDENT> elif isinstance(ele, dict): <NEW_LINE> <INDENT> self._doc.append(MatchDoc(ele)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._doc.append(ele) <NEW_LINE> <DEDENT> <DEDENT> self._pos = pos <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return iter(self._doc) <NEW_LINE> <DEDENT> def traverse(self, first, *rest): <NEW_LINE> <INDENT> if not rest: <NEW_LINE> <INDENT> return self, first <NEW_LINE> <DEDENT> return self[first].traverse(*rest) <NEW_LINE> <DEDENT> def match(self, key, op, value): <NEW_LINE> <INDENT> if key == '$': <NEW_LINE> <INDENT> for i, item in enumerate(self._doc): <NEW_LINE> <INDENT> if self.match(i, op, value): <NEW_LINE> <INDENT> if self._pos is None: <NEW_LINE> <INDENT> self._pos = i <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return None <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> m = super(MatchList, self).match(key, op, value) <NEW_LINE> if m: return m <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> for ele in self: <NEW_LINE> <INDENT> if (isinstance(ele, Match) and ele.match(key, op, value)): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __eq__(self, o): <NEW_LINE> <INDENT> return isinstance(o, MatchList) and self._doc == o._doc <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash(self._doc) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'M<%r>%r' % (self._pos, self._doc) <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if key == '$': <NEW_LINE> <INDENT> if self._pos is None: <NEW_LINE> <INDENT> return self._doc[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self._doc[self._pos] <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return self._doc[int(key)] <NEW_LINE> <DEDENT> <DEDENT> except IndexError: <NEW_LINE> <INDENT> raise KeyError(key) <NEW_LINE> <DEDENT> <DEDENT> def __setitem__(self, key, value): <NEW_LINE> <INDENT> if key == '$': <NEW_LINE> <INDENT> key = self._pos <NEW_LINE> <DEDENT> if isinstance(self._doc, list): <NEW_LINE> <INDENT> key = int(key) <NEW_LINE> <DEDENT> self._doc[key] = value <NEW_LINE> self._orig[key] = value <NEW_LINE> <DEDENT> def __delitem__(self, key): <NEW_LINE> <INDENT> if key == '$': <NEW_LINE> <INDENT> key = self._pos <NEW_LINE> <DEDENT> del self._doc[int(key)] <NEW_LINE> del self._orig[int(key)] <NEW_LINE> <DEDENT> def setdefault(self, key, default): <NEW_LINE> <INDENT> if key == '$': <NEW_LINE> <INDENT> key = self._pos <NEW_LINE> <DEDENT> if key <= len(self._orig): <NEW_LINE> <INDENT> return self._orig[key] <NEW_LINE> <DEDENT> while key >= len(self._orig): <NEW_LINE> <INDENT> self._doc.append(None) <NEW_LINE> self._orig.append(None) <NEW_LINE> <DEDENT> self._doc[key] = default <NEW_LINE> self._orig[key] = default | A List that is part of a document matching a query.
A ``MatchDoc`` might contain lists within itself,
all those lists will be wrapped in a ``MatchList``
so their content can be traversed, tested against the filter
and updated according to the query being executed. | 62598fa7cc0a2c111447af18 |
class CinderEncryptedVolumeType(resource.Resource): <NEW_LINE> <INDENT> support_status = support.SupportStatus(version='5.0.0') <NEW_LINE> default_client_name = 'cinder' <NEW_LINE> entity = 'volume_encryption_types' <NEW_LINE> required_service_extension = 'encryption' <NEW_LINE> PROPERTIES = ( PROVIDER, CONTROL_LOCATION, CIPHER, KEY_SIZE, VOLUME_TYPE ) = ( 'provider', 'control_location', 'cipher', 'key_size', 'volume_type' ) <NEW_LINE> properties_schema = { PROVIDER: properties.Schema( properties.Schema.STRING, _('The class that provides encryption support. ' 'For example, nova.volume.encryptors.luks.LuksEncryptor.'), required=True, update_allowed=True ), CONTROL_LOCATION: properties.Schema( properties.Schema.STRING, _('Notional service where encryption is performed ' 'For example, front-end. For Nova.'), constraints=[ constraints.AllowedValues(['front-end', 'back-end']) ], default='front-end', update_allowed=True ), CIPHER: properties.Schema( properties.Schema.STRING, _('The encryption algorithm or mode. ' 'For example, aes-xts-plain64.'), constraints=[ constraints.AllowedValues( ['aes-xts-plain64', 'aes-cbc-essiv'] ) ], default=None, update_allowed=True ), KEY_SIZE: properties.Schema( properties.Schema.INTEGER, _('Size of encryption key, in bits. ' 'For example, 128 or 256.'), default=None, update_allowed=True ), VOLUME_TYPE: properties.Schema( properties.Schema.STRING, _('Name or id of volume type (OS::Cinder::VolumeType).'), required=True, constraints=[constraints.CustomConstraint('cinder.vtype')] ), } <NEW_LINE> def _get_vol_type_id(self, volume_type): <NEW_LINE> <INDENT> id = self.client_plugin().get_volume_type(volume_type) <NEW_LINE> return id <NEW_LINE> <DEDENT> def handle_create(self): <NEW_LINE> <INDENT> body = { 'provider': self.properties[self.PROVIDER], 'cipher': self.properties[self.CIPHER], 'key_size': self.properties[self.KEY_SIZE], 'control_location': self.properties[self.CONTROL_LOCATION] } <NEW_LINE> vol_type_id = self._get_vol_type_id(self.properties[self.VOLUME_TYPE]) <NEW_LINE> encrypted_vol_type = self.client().volume_encryption_types.create( volume_type=vol_type_id, specs=body ) <NEW_LINE> self.resource_id_set(encrypted_vol_type.volume_type_id) <NEW_LINE> <DEDENT> def handle_update(self, json_snippet, tmpl_diff, prop_diff): <NEW_LINE> <INDENT> if prop_diff: <NEW_LINE> <INDENT> self.client().volume_encryption_types.update( volume_type=self.resource_id, specs=prop_diff ) | A resource for encrypting a cinder volume type.
A Volume Encryption Type is a collection of settings used to conduct
encryption for a specific volume type.
Note that default cinder security policy usage of this resource
is limited to being used by administrators only. | 62598fa721bff66bcd722b6f |
class ppTSLastChange( ppTicketSetExtension ): <NEW_LINE> <INDENT> def __init__(self,ticketset,ticketsetdata): <NEW_LINE> <INDENT> self.__ts = ticketsetdata <NEW_LINE> <DEDENT> def extend(self): <NEW_LINE> <INDENT> timemax = to_datetime( 0, utc ) <NEW_LINE> timenow = to_datetime( datetime.datetime.now(utc) ) <NEW_LINE> for k in self.__ts: <NEW_LINE> <INDENT> v = self.__ts[ k ] <NEW_LINE> ticketdt = to_datetime( v.getfielddef( 'changetime', timenow ) ) <NEW_LINE> if ticketdt > timemax: <NEW_LINE> <INDENT> timemax = ticketdt <NEW_LINE> if timemax == timenow: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return timemax | Get the Last Ticket Changetime | 62598fa74428ac0f6e65842b |
class ParseProgress(OperationProgress): <NEW_LINE> <INDENT> def __init__(self, current, total): <NEW_LINE> <INDENT> OperationProgress.__init__(self, current, total, "Recipe parsing") | Recipe parsing progress | 62598fa756ac1b37e63020f5 |
class QSqlIndex(QSqlRecord): <NEW_LINE> <INDENT> def append(self, QSqlField, bool=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def cursorName(self): <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> def isDescending(self, p_int): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def name(self): <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> def setCursorName(self, p_str): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def setDescending(self, p_int, bool): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def setName(self, p_str): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __init__(self, *__args): <NEW_LINE> <INDENT> pass | QSqlIndex(cursorName: str = '', name: str = '')
QSqlIndex(QSqlIndex) | 62598fa71b99ca400228f4b4 |
class UserViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = User.objects.order_by('date_joined') <NEW_LINE> serializer_class = UserSerializer <NEW_LINE> http_method_names = ['get', 'post', 'put', 'delete'] <NEW_LINE> def get_serializer_class(self): <NEW_LINE> <INDENT> serializer_class = self.serializer_class <NEW_LINE> if self.request.method == 'PUT': <NEW_LINE> <INDENT> serializer_class = UserUpdateSerializer <NEW_LINE> <DEDENT> return serializer_class <NEW_LINE> <DEDENT> def get_authenticators(self): <NEW_LINE> <INDENT> if self.request.method == 'POST': <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> return super().get_authenticators() <NEW_LINE> <DEDENT> def get_permissions(self): <NEW_LINE> <INDENT> if self.request.method == 'POST': <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> return super().get_permissions() | This viewset automatically provides `list` and `detail` actions. | 62598fa70c0af96317c5628c |
class VehicleTurningLeft(BaseVehicleTurning): <NEW_LINE> <INDENT> def __init__(self, world, ego_vehicles, config, randomize=False, debug_mode=False, criteria_enable=True, timeout=60): <NEW_LINE> <INDENT> self._subtype = 'left' <NEW_LINE> super(VehicleTurningLeft, self).__init__( world, ego_vehicles, config, randomize, debug_mode, criteria_enable, timeout, "VehicleTurningLeft") | Version of the VehicleTurning scenario where
the adversary is placed at the left side after the junction | 62598fa70a50d4780f7052e6 |
class ZmqSender(ZmqClient): <NEW_LINE> <INDENT> def __init__(self, *, host=None, port=None, address=None, bind=False, timeout=-1, serializer=None, callback=None, **kwargs): <NEW_LINE> <INDENT> super().__init__( address=address, host=host, port=port, bind=bind, serializer=serializer, timeout=timeout, callback=callback, **kwargs, ) <NEW_LINE> <DEDENT> def send(self, msg): <NEW_LINE> <INDENT> response = self.request(msg) <NEW_LINE> if response != b'ack': <NEW_LINE> <INDENT> raise ValueError('ZmqSender did not receive ack on the other end', 'Was something wrong?') | Uses REQ / REP to send and receive data,
i.e. a client that only expects b'ack'
by default connects | 62598fa799fddb7c1ca62d6d |
class TransactionsID(models.Model): <NEW_LINE> <INDENT> coin_type = models.CharField(max_length=50,verbose_name="币种") <NEW_LINE> transaction_id = models.CharField(max_length=255, verbose_name="交易ID") <NEW_LINE> used = models.BooleanField(verbose_name="是否处理",default=False) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = "交易ID" <NEW_LINE> verbose_name_plural = verbose_name <NEW_LINE> db_table = "transaction_id" <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.transaction_id | 交易ID记录表,用户保存交易ID:币种,ID | 62598fa757b8e32f525080a0 |
class SendPaymentForm(TLObject): <NEW_LINE> <INDENT> __slots__ = ["msg_id", "credentials", "requested_info_id", "shipping_option_id"] <NEW_LINE> ID = 0x2b8879b3 <NEW_LINE> QUALNAME = "functions.payments.SendPaymentForm" <NEW_LINE> def __init__(self, *, msg_id: int, credentials, requested_info_id: str = None, shipping_option_id: str = None): <NEW_LINE> <INDENT> self.msg_id = msg_id <NEW_LINE> self.requested_info_id = requested_info_id <NEW_LINE> self.shipping_option_id = shipping_option_id <NEW_LINE> self.credentials = credentials <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def read(b: BytesIO, *args) -> "SendPaymentForm": <NEW_LINE> <INDENT> flags = Int.read(b) <NEW_LINE> msg_id = Int.read(b) <NEW_LINE> requested_info_id = String.read(b) if flags & (1 << 0) else None <NEW_LINE> shipping_option_id = String.read(b) if flags & (1 << 1) else None <NEW_LINE> credentials = TLObject.read(b) <NEW_LINE> return SendPaymentForm(msg_id=msg_id, credentials=credentials, requested_info_id=requested_info_id, shipping_option_id=shipping_option_id) <NEW_LINE> <DEDENT> def write(self) -> bytes: <NEW_LINE> <INDENT> b = BytesIO() <NEW_LINE> b.write(Int(self.ID, False)) <NEW_LINE> flags = 0 <NEW_LINE> flags |= (1 << 0) if self.requested_info_id is not None else 0 <NEW_LINE> flags |= (1 << 1) if self.shipping_option_id is not None else 0 <NEW_LINE> b.write(Int(flags)) <NEW_LINE> b.write(Int(self.msg_id)) <NEW_LINE> if self.requested_info_id is not None: <NEW_LINE> <INDENT> b.write(String(self.requested_info_id)) <NEW_LINE> <DEDENT> if self.shipping_option_id is not None: <NEW_LINE> <INDENT> b.write(String(self.shipping_option_id)) <NEW_LINE> <DEDENT> b.write(self.credentials.write()) <NEW_LINE> return b.getvalue() | Attributes:
LAYER: ``112``
Attributes:
ID: ``0x2b8879b3``
Parameters:
msg_id: ``int`` ``32-bit``
credentials: Either :obj:`InputPaymentCredentialsSaved <pyrogram.api.types.InputPaymentCredentialsSaved>`, :obj:`InputPaymentCredentials <pyrogram.api.types.InputPaymentCredentials>`, :obj:`InputPaymentCredentialsApplePay <pyrogram.api.types.InputPaymentCredentialsApplePay>` or :obj:`InputPaymentCredentialsAndroidPay <pyrogram.api.types.InputPaymentCredentialsAndroidPay>`
requested_info_id (optional): ``str``
shipping_option_id (optional): ``str``
Returns:
Either :obj:`payments.PaymentResult <pyrogram.api.types.payments.PaymentResult>` or :obj:`payments.PaymentVerificationNeeded <pyrogram.api.types.payments.PaymentVerificationNeeded>` | 62598fa785dfad0860cbf9f9 |
class GreaterOperator(BinaryOperator): <NEW_LINE> <INDENT> def __init__(self, field, value): <NEW_LINE> <INDENT> super(GreaterOperator, self).__init__(">", field, value) | Builds a greater-than filter based on the supplied field-value pair as
described
https://docs.puppet.com/puppetdb/4.1/api/query/v4/ast.html#greater-than.
In order to create the following query:
[">", "catalog_timestamp", "2016-06-01 00:00:00"]
The following code can be used.
GreaterOperator('catalog_timestamp', datetime.datetime(2016, 06, 01))
:param field: The PuppetDB endpoint query field. See endpoint
documentation for valid values.
:type field: any
:param value: Matches if the field is greater than this value.
:type value: Number, timestamp or array | 62598fa7e1aae11d1e7ce7a8 |
class JsButton(NavButton): <NEW_LINE> <INDENT> def __init__(self, title, style = 'js', tab_name = None, **kw): <NEW_LINE> <INDENT> NavButton.__init__(self, title, '#', style = style, tab_name = tab_name, **kw) <NEW_LINE> <DEDENT> def build(self, *a, **kw): <NEW_LINE> <INDENT> if self.tab_name: <NEW_LINE> <INDENT> self.path = '#' + self.tab_name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.path = 'javascript:void(0)' <NEW_LINE> <DEDENT> <DEDENT> def is_selected(self): <NEW_LINE> <INDENT> return False | A button which fires a JS event and thus has no path and cannot
be in the 'selected' state | 62598fa7a8ecb03325871119 |
class AaaLdap(ManagedObject): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> ManagedObject.__init__(self, "AaaLdap") <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def class_id(): <NEW_LINE> <INDENT> return "aaaLdap" <NEW_LINE> <DEDENT> ADMIN_STATE = "AdminState" <NEW_LINE> ATTRIBUTE = "Attribute" <NEW_LINE> BASEDN = "Basedn" <NEW_LINE> BIND_DN = "BindDn" <NEW_LINE> BIND_METHOD = "BindMethod" <NEW_LINE> DN = "Dn" <NEW_LINE> DNS_DOMAIN_SOURCE = "DnsDomainSource" <NEW_LINE> DNS_SEARCH_DOMAIN = "DnsSearchDomain" <NEW_LINE> DNS_SEARCH_FOREST = "DnsSearchForest" <NEW_LINE> DOMAIN = "Domain" <NEW_LINE> ENCRYPTION = "Encryption" <NEW_LINE> FILTER = "Filter" <NEW_LINE> GROUP_ATTRIBUTE = "GroupAttribute" <NEW_LINE> GROUP_AUTH = "GroupAuth" <NEW_LINE> GROUP_NESTED_SEARCH = "GroupNestedSearch" <NEW_LINE> LDAP_SERVER1 = "LdapServer1" <NEW_LINE> LDAP_SERVER2 = "LdapServer2" <NEW_LINE> LDAP_SERVER3 = "LdapServer3" <NEW_LINE> LDAP_SERVER4 = "LdapServer4" <NEW_LINE> LDAP_SERVER5 = "LdapServer5" <NEW_LINE> LDAP_SERVER6 = "LdapServer6" <NEW_LINE> LDAP_SERVER_PORT1 = "LdapServerPort1" <NEW_LINE> LDAP_SERVER_PORT2 = "LdapServerPort2" <NEW_LINE> LDAP_SERVER_PORT3 = "LdapServerPort3" <NEW_LINE> LDAP_SERVER_PORT4 = "LdapServerPort4" <NEW_LINE> LDAP_SERVER_PORT5 = "LdapServerPort5" <NEW_LINE> LDAP_SERVER_PORT6 = "LdapServerPort6" <NEW_LINE> LOCATE_DIRECTORY_USING_DNS = "LocateDirectoryUsingDNS" <NEW_LINE> PASSWORD = "Password" <NEW_LINE> RN = "Rn" <NEW_LINE> STATUS = "Status" <NEW_LINE> TIMEOUT = "Timeout" <NEW_LINE> CONST_BIND_METHOD_ANONYMOUS = "anonymous" <NEW_LINE> CONST_BIND_METHOD_CONFIGURED_CREDENTIALS = "configured-credentials" <NEW_LINE> CONST_BIND_METHOD_LOGIN_CREDENTIALS = "login-credentials" <NEW_LINE> CONST_DNS_DOMAIN_SOURCE_CONFIGURED_DOMAIN = "configured-domain" <NEW_LINE> CONST_DNS_DOMAIN_SOURCE_EXTRACTED_CONFIGURED_DOMAIN = "extracted-configured-domain" <NEW_LINE> CONST_DNS_DOMAIN_SOURCE_EXTRACTED_DOMAIN = "extracted-domain" <NEW_LINE> CONST_LOCATE_DIRECTORY_USING_DNS_NO = "no" <NEW_LINE> CONST_LOCATE_DIRECTORY_USING_DNS_YES = "yes" | This class contains the relevant properties and constant supported by this MO. | 62598fa7bd1bec0571e15048 |
class Solution: <NEW_LINE> <INDENT> def subdomainVisits(self, cpdomains): <NEW_LINE> <INDENT> d = {} <NEW_LINE> ret = [] <NEW_LINE> for ele in cpdomains: <NEW_LINE> <INDENT> e = ele.split() <NEW_LINE> visits = int(e[0]) <NEW_LINE> url = e[1] <NEW_LINE> url_list = url.split('.') <NEW_LINE> tmp = "" <NEW_LINE> for i in range(len(url_list)-1, -1, -1): <NEW_LINE> <INDENT> if tmp == "": <NEW_LINE> <INDENT> tmp = url_list[i] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tmp = url_list[i] + "." + tmp <NEW_LINE> <DEDENT> if tmp not in d: <NEW_LINE> <INDENT> d[tmp] = visits <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> d[tmp] += visits <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> for k in d: <NEW_LINE> <INDENT> ret.append(str(d[k]) + " " + k) <NEW_LINE> <DEDENT> return ret | @param cpdomains: a list cpdomains of count-paired domains
@return: a list of count-paired domains | 62598fa7442bda511e95c35f |
class NewItemForm(formencode.Schema): <NEW_LINE> <INDENT> allow_extra_fields = True <NEW_LINE> filter_extra_fields = True <NEW_LINE> brand = formencode.validators.String(not_empty=True) <NEW_LINE> model = formencode.validators.String(not_empty=True) <NEW_LINE> description = formencode.validators.String(not_empty=True) <NEW_LINE> section_id = formencode.validators.String(not_empty=True) <NEW_LINE> unit_id = formencode.validators.Int(not_empty=True) <NEW_LINE> price = formencode.validators.Number(not_empty=True) | Проверка данных формы создания нового объекта | 62598fa716aa5153ce40040c |
class UTF8Recoder: <NEW_LINE> <INDENT> def __init__(self, f, encoding): <NEW_LINE> <INDENT> self.reader = codecs.getreader(encoding)(f) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __next__(self): <NEW_LINE> <INDENT> return self.reader.next().encode("utf-8") | Iterator that reads an encoded stream and reencodes the input to UTF-8
http://docs.python.org/library/csv.html | 62598fa78da39b475be030ec |
class Trefethen(Benchmark): <NEW_LINE> <INDENT> def __init__(self, dimensions=2): <NEW_LINE> <INDENT> Benchmark.__init__(self, dimensions) <NEW_LINE> self.bounds = zip([-10.0] * self.dimensions, [10.0] * self.dimensions) <NEW_LINE> self.custom_bounds = [(-5, 5), (-5, 5)] <NEW_LINE> self.global_optimum = [-0.02440307923, 0.2106124261] <NEW_LINE> self.fglob = -3.3068686474 <NEW_LINE> <DEDENT> def evaluator(self, x, *args): <NEW_LINE> <INDENT> self.fun_evals += 1 <NEW_LINE> F = exp(sin(50*x[0])) + sin(60*exp(x[1])) + sin(70*sin(x[0])) + sin(sin(80*x[1])) - sin(10*(x[0]+x[1])) + 1.0/4*(x[0]**2 + x[1]**2) <NEW_LINE> return F | Trefethen test objective function.
This class defines the Trefethen global optimization problem. This
is a multimodal minimization problem defined as follows:
.. math::
f_{\text{Trefethen}}(\mathbf{x}) = 0.25 x_{1}^{2} + 0.25 x_{2}^{2} + e^{\sin\left(50 x_{1}\right)} - \sin\left(10 x_{1} + 10 x_{2}\right) + \sin\left(60 e^{x_{2}}\right) + \sin\left[70 \sin\left(x_{1}\right)\right] + \sin\left[\sin\left(80 x_{2}\right)\right]
Here, :math:`n` represents the number of dimensions and :math:`x_i \in [-10, 10]` for :math:`i=1,2`.
.. figure:: figures/Trefethen.png
:alt: Trefethen function
:align: center
**Two-dimensional Trefethen function**
*Global optimum*: :math:`f(x_i) = -3.3068686474` for :math:`\mathbf{x} = [-0.02440307923, 0.2106124261]` | 62598fa72c8b7c6e89bd36d0 |
class SeleniumStaleElementError(SeleniumError): <NEW_LINE> <INDENT> pass | Requested element no longer exists
| 62598fa776e4537e8c3ef4b7 |
class Piece(object): <NEW_LINE> <INDENT> KING = 0 <NEW_LINE> QUEEN = 1 <NEW_LINE> BISHOP = 2 <NEW_LINE> KNIGHT = 3 <NEW_LINE> ROOK = 4 <NEW_LINE> PAWN = 5 <NEW_LINE> def __init__(self, owner, type): <NEW_LINE> <INDENT> self._owner = owner <NEW_LINE> self._set_type(type) <NEW_LINE> <DEDENT> def get_player(self): <NEW_LINE> <INDENT> return self._owner <NEW_LINE> <DEDENT> def get_type(self): <NEW_LINE> <INDENT> return self._type <NEW_LINE> <DEDENT> def _set_type(self, type ): <NEW_LINE> <INDENT> if type in [ Piece.KING, Piece.QUEEN, Piece.BISHOP, Piece.KNIGHT, Piece.ROOK, Piece.PAWN ]: <NEW_LINE> <INDENT> self._type = type <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("Invalid piece type") <NEW_LINE> <DEDENT> <DEDENT> owner = property( get_player ) <NEW_LINE> type = property( get_type ) | This class models one single chess piece. | 62598fa760cbc95b06364256 |
class GenerateCEOReportStart(ModelView): <NEW_LINE> <INDENT> __name__ = 'ceo.report.generate.start' <NEW_LINE> start_date = fields.DateTime('Start Date', required=True) <NEW_LINE> end_date = fields.DateTime('End Date', required=True) <NEW_LINE> @staticmethod <NEW_LINE> def default_start_date(): <NEW_LINE> <INDENT> return datetime.combine( date.today() - relativedelta(days=1), time.min ) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def default_end_date(): <NEW_LINE> <INDENT> return datetime.combine( date.today() - relativedelta(days=1), time.max ) | Generate CEO Report | 62598fa767a9b606de545ed6 |
class ServiceTagsOperations(object): <NEW_LINE> <INDENT> models = _models <NEW_LINE> def __init__(self, client, config, serializer, deserializer): <NEW_LINE> <INDENT> self._client = client <NEW_LINE> self._serialize = serializer <NEW_LINE> self._deserialize = deserializer <NEW_LINE> self._config = config <NEW_LINE> <DEDENT> def list( self, location, **kwargs ): <NEW_LINE> <INDENT> cls = kwargs.pop('cls', None) <NEW_LINE> error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } <NEW_LINE> error_map.update(kwargs.pop('error_map', {})) <NEW_LINE> api_version = "2020-11-01" <NEW_LINE> accept = "application/json" <NEW_LINE> url = self.list.metadata['url'] <NEW_LINE> path_format_arguments = { 'location': self._serialize.url("location", location, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } <NEW_LINE> url = self._client.format_url(url, **path_format_arguments) <NEW_LINE> query_parameters = {} <NEW_LINE> query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') <NEW_LINE> header_parameters = {} <NEW_LINE> header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') <NEW_LINE> request = self._client.get(url, query_parameters, header_parameters) <NEW_LINE> pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) <NEW_LINE> response = pipeline_response.http_response <NEW_LINE> if response.status_code not in [200]: <NEW_LINE> <INDENT> map_error(status_code=response.status_code, response=response, error_map=error_map) <NEW_LINE> raise HttpResponseError(response=response, error_format=ARMErrorFormat) <NEW_LINE> <DEDENT> deserialized = self._deserialize('ServiceTagsListResult', pipeline_response) <NEW_LINE> if cls: <NEW_LINE> <INDENT> return cls(pipeline_response, deserialized, {}) <NEW_LINE> <DEDENT> return deserialized <NEW_LINE> <DEDENT> list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/serviceTags'} | ServiceTagsOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.network.v2020_11_01.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer. | 62598fa7a8370b77170f02e5 |
class ClusterLevel(object): <NEW_LINE> <INDENT> def __init__(self, level_name: int = None, no_elements: int = 1, intra_class_correlation = 1, **kwargs): <NEW_LINE> <INDENT> self.level_name = level_name <NEW_LINE> self.no_elements = no_elements <NEW_LINE> self.intra_class_correlation = intra_class_correlation <NEW_LINE> if kwargs.get('source'): <NEW_LINE> <INDENT> self.from_dict(kwargs['source']) <NEW_LINE> <DEDENT> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def from_dict(self, source): <NEW_LINE> <INDENT> if source.get('levelName'): <NEW_LINE> <INDENT> self.level_name = source['levelName'] <NEW_LINE> <DEDENT> if source.get('noElements'): <NEW_LINE> <INDENT> self.no_elements = source['noElements'] <NEW_LINE> <DEDENT> if source.get('intraClassCorellation'): <NEW_LINE> <INDENT> self.intra_class_correlation = source['intraClassCorellation'] | Class describing cluster levels | 62598fa71f5feb6acb162b2c |
class EnablingModesComponent(ModesComponent): <NEW_LINE> <INDENT> def __init__(self, component = None, enabled_color = 'DefaultButton.On', disabled_color = 'DefaultButton.Off', *a, **k): <NEW_LINE> <INDENT> super(EnablingModesComponent, self).__init__(*a, **k) <NEW_LINE> component.set_enabled(False) <NEW_LINE> self.add_mode('disabled', None, disabled_color) <NEW_LINE> self.add_mode('enabled', component, enabled_color) <NEW_LINE> self.selected_mode = 'disabled' | Adds the two modes 'enabled' and 'disabled'. The provided component will be
enabled while the 'enabled' mode is active. | 62598fa730bbd722464698fd |
class _Var(object): <NEW_LINE> <INDENT> def __init__(self, y): <NEW_LINE> <INDENT> self.y = y <NEW_LINE> self.nobs, self.nvars = y.shape <NEW_LINE> <DEDENT> def fit(self, nlags): <NEW_LINE> <INDENT> self.nlags = nlags <NEW_LINE> nvars = self.nvars <NEW_LINE> lmat = lagmat(self.y, nlags, trim='both', original='in') <NEW_LINE> self.yred = lmat[:,:nvars] <NEW_LINE> self.xred = lmat[:,nvars:] <NEW_LINE> res = np.linalg.lstsq(self.xred, self.yred, rcond=-1) <NEW_LINE> self.estresults = res <NEW_LINE> self.arlhs = res[0].reshape(nlags, nvars, nvars) <NEW_LINE> self.arhat = ar2full(self.arlhs) <NEW_LINE> self.rss = res[1] <NEW_LINE> self.xredrank = res[2] <NEW_LINE> <DEDENT> def predict(self): <NEW_LINE> <INDENT> if not hasattr(self, 'yhat'): <NEW_LINE> <INDENT> self.yhat = varfilter(self.y, self.arhat) <NEW_LINE> <DEDENT> return self.yhat <NEW_LINE> <DEDENT> def covmat(self): <NEW_LINE> <INDENT> self.paramcov = (self.rss[None,None,:] * np.linalg.inv(np.dot(self.xred.T, self.xred))[:,:,None]) <NEW_LINE> <DEDENT> def forecast(self, horiz=1, u=None): <NEW_LINE> <INDENT> if u is None: <NEW_LINE> <INDENT> u = np.zeros((horiz, self.nvars)) <NEW_LINE> <DEDENT> return vargenerate(self.arhat, u, initvalues=self.y) | obsolete VAR class, use tsa.VAR instead, for internal use only
Examples
--------
>>> v = Var(ar2s)
>>> v.fit(1)
>>> v.arhat
array([[[ 1. , 0. ],
[ 0. , 1. ]],
[[-0.77784898, 0.01726193],
[ 0.10733009, -0.78665335]]]) | 62598fa73539df3088ecc1bf |
class LeftRightError(Exception): <NEW_LINE> <INDENT> def __str__(self): <NEW_LINE> <INDENT> return 'Error occurred while communicating with rpkid: handle=%s code=%s text=%s' % ( self.args[0].self_handle, self.args[0].error_code, self.args[0].error_text) | Class for wrapping report_error_elt errors from Zookeeper.call_rpkid().
It expects a single argument, which is the associated report_error_elt instance. | 62598fa744b2445a339b68f4 |
class FlowInstance(InstanceResource): <NEW_LINE> <INDENT> class Status(object): <NEW_LINE> <INDENT> DRAFT = "draft" <NEW_LINE> PUBLISHED = "published" <NEW_LINE> <DEDENT> def __init__(self, version, payload, sid=None): <NEW_LINE> <INDENT> super(FlowInstance, self).__init__(version) <NEW_LINE> self._properties = { 'sid': payload.get('sid'), 'account_sid': payload.get('account_sid'), 'friendly_name': payload.get('friendly_name'), 'definition': payload.get('definition'), 'status': payload.get('status'), 'revision': deserialize.integer(payload.get('revision')), 'commit_message': payload.get('commit_message'), 'valid': payload.get('valid'), 'errors': payload.get('errors'), 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), 'url': payload.get('url'), 'links': payload.get('links'), } <NEW_LINE> self._context = None <NEW_LINE> self._solution = {'sid': sid or self._properties['sid'], } <NEW_LINE> <DEDENT> @property <NEW_LINE> def _proxy(self): <NEW_LINE> <INDENT> if self._context is None: <NEW_LINE> <INDENT> self._context = FlowContext(self._version, sid=self._solution['sid'], ) <NEW_LINE> <DEDENT> return self._context <NEW_LINE> <DEDENT> @property <NEW_LINE> def sid(self): <NEW_LINE> <INDENT> return self._properties['sid'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def account_sid(self): <NEW_LINE> <INDENT> return self._properties['account_sid'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def friendly_name(self): <NEW_LINE> <INDENT> return self._properties['friendly_name'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def definition(self): <NEW_LINE> <INDENT> return self._properties['definition'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def status(self): <NEW_LINE> <INDENT> return self._properties['status'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def revision(self): <NEW_LINE> <INDENT> return self._properties['revision'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def commit_message(self): <NEW_LINE> <INDENT> return self._properties['commit_message'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def valid(self): <NEW_LINE> <INDENT> return self._properties['valid'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def errors(self): <NEW_LINE> <INDENT> return self._properties['errors'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def date_created(self): <NEW_LINE> <INDENT> return self._properties['date_created'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def date_updated(self): <NEW_LINE> <INDENT> return self._properties['date_updated'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def url(self): <NEW_LINE> <INDENT> return self._properties['url'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def links(self): <NEW_LINE> <INDENT> return self._properties['links'] <NEW_LINE> <DEDENT> def update(self, status, friendly_name=values.unset, definition=values.unset, commit_message=values.unset): <NEW_LINE> <INDENT> return self._proxy.update( status, friendly_name=friendly_name, definition=definition, commit_message=commit_message, ) <NEW_LINE> <DEDENT> def fetch(self): <NEW_LINE> <INDENT> return self._proxy.fetch() <NEW_LINE> <DEDENT> def delete(self): <NEW_LINE> <INDENT> return self._proxy.delete() <NEW_LINE> <DEDENT> @property <NEW_LINE> def revisions(self): <NEW_LINE> <INDENT> return self._proxy.revisions <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) <NEW_LINE> return '<Twilio.Studio.V2.FlowInstance {}>'.format(context) | PLEASE NOTE that this class contains beta products that are subject to
change. Use them with caution. | 62598fa721bff66bcd722b71 |
class ApiException(Exception): <NEW_LINE> <INDENT> INVALID_REPLY = -1 <NEW_LINE> INVALID_VALUE = -2 <NEW_LINE> FAILED_AUTH = -32602 <NEW_LINE> def __init__(self, code, msg, data): <NEW_LINE> <INDENT> self.code = code <NEW_LINE> self.msg = msg <NEW_LINE> self.data = data <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "{}: {}: {}".format(self.code, self.msg, self.data) | Raised when bad reply from server or error msg in the reply. | 62598fa78c0ade5d55dc3616 |
class EmailRequest(Message): <NEW_LINE> <INDENT> email = StringField(1, required=True) | ProtoRPC message definition to represent an email | 62598fa756ac1b37e63020f7 |
class PartyTable: <NEW_LINE> <INDENT> parties = {} <NEW_LINE> next_id = len(parties) + 1 <NEW_LINE> def get_single_party_by_name(self, name): <NEW_LINE> <INDENT> for party in self.parties.values(): <NEW_LINE> <INDENT> if party['name'] == name: <NEW_LINE> <INDENT> return party <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def add_party(self, party_data): <NEW_LINE> <INDENT> new_party = Party( self.next_id, party_data['name'], party_data['hq_address'], party_data['logo_url'] ) <NEW_LINE> self.parties[self.next_id] = new_party.party_data <NEW_LINE> return self.parties[self.next_id] <NEW_LINE> <DEDENT> def update_party(self, id, party_data): <NEW_LINE> <INDENT> party = self.parties.get(id) <NEW_LINE> party['name'] = party_data['name'] <NEW_LINE> party['hq_address'] = party_data['hq_address'] <NEW_LINE> party['logo_url'] = party_data['logo_url'] <NEW_LINE> self.parties[id] = party <NEW_LINE> return self.parties[id] <NEW_LINE> <DEDENT> def delete_party(self, id): <NEW_LINE> <INDENT> party = self.parties.get(id) <NEW_LINE> if party: <NEW_LINE> <INDENT> del self.parties[id] <NEW_LINE> return True <NEW_LINE> <DEDENT> return False | acts as a table for storing parties and their related information | 62598fa70c0af96317c5628e |
class ExtractAndCleanDownloads510k(luigi.Task): <NEW_LINE> <INDENT> def requires(self): <NEW_LINE> <INDENT> return Download_510K() <NEW_LINE> <DEDENT> def output(self): <NEW_LINE> <INDENT> return luigi.LocalTarget(join(BASE_DIR, '510k/extracted')) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> output_dir = self.output().path <NEW_LINE> common.shell_cmd('mkdir -p %s', output_dir) <NEW_LINE> input_dir = self.input().path <NEW_LINE> download_util.extract_and_clean(input_dir, 'ISO-8859-1', 'UTF-8', 'txt') | Unzip each of the download files and remove all the non-UTF8 characters.
Unzip -p streams the data directly to iconv which then writes to disk. | 62598fa70a50d4780f7052e8 |
class LessonFinder(object): <NEW_LINE> <INDENT> LESSON_FILE_EXTENSION = '.les' <NEW_LINE> def __init__(self, lessons_dir): <NEW_LINE> <INDENT> self.lessons_dir = lessons_dir <NEW_LINE> self.lesson_file_name_list = [] <NEW_LINE> <DEDENT> def find_lessons(self): <NEW_LINE> <INDENT> lesson_list = [] <NEW_LINE> file_names = self.get_file_list() <NEW_LINE> for name in sorted(file_names): <NEW_LINE> <INDENT> raw_name, extension = os.path.splitext(name) <NEW_LINE> lesson_file_path = os.path.join(self.lessons_dir, name) <NEW_LINE> lesson = container.Lesson(raw_name, self.get_nice_name(raw_name), lesson_file_path) <NEW_LINE> lesson_list.append(lesson) <NEW_LINE> <DEDENT> return lesson_list <NEW_LINE> <DEDENT> def get_file_list(self): <NEW_LINE> <INDENT> if not self.lesson_file_name_list: <NEW_LINE> <INDENT> file_names = os.listdir(self.lessons_dir) <NEW_LINE> for name in file_names: <NEW_LINE> <INDENT> raw_name, extension = os.path.splitext(name) <NEW_LINE> if not extension == self.LESSON_FILE_EXTENSION: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> self.lesson_file_name_list.append(name) <NEW_LINE> <DEDENT> <DEDENT> return self.lesson_file_name_list <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_nice_name(lesson_name): <NEW_LINE> <INDENT> lesson_name_words = lesson_name.split("_") <NEW_LINE> lesson_name_caps_list = [n.capitalize() for n in lesson_name_words] <NEW_LINE> return " ".join(lesson_name_caps_list) | Assists in finding lessons. | 62598fa73cc13d1c6d465677 |
class ProcessorMixin(object): <NEW_LINE> <INDENT> def process(self, iprot, oprot): <NEW_LINE> <INDENT> name, type, seqid = iprot.readMessageBegin() <NEW_LINE> try: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> fn = self._processMap[name] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise TApplicationException(TApplicationException.UNKNOWN_METHOD, 'Unknown function %s' % (name)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> fn(self, seqid, iprot, oprot) <NEW_LINE> <DEDENT> <DEDENT> except TApplicationException as exc: <NEW_LINE> <INDENT> oprot.writeMessageBegin(name, TMessageType.EXCEPTION, seqid) <NEW_LINE> exc.write(oprot) <NEW_LINE> oprot.writeMessageEnd() <NEW_LINE> oprot.trans.flush() <NEW_LINE> return <NEW_LINE> <DEDENT> return True | Process application error if there is one. | 62598fa73539df3088ecc1c0 |
class SimpleRigidBody2d(BasePointMass2d): <NEW_LINE> <INDENT> BasePointMass2d._PHYSICS_DEFAULTS.update(**SIMPLERIGIDBODY2D_DEFAULTS) <NEW_LINE> def __init__(self, position, radius, velocity, beta, omega, spritedata=None): <NEW_LINE> <INDENT> BasePointMass2d.__init__(self, position, radius, velocity, spritedata) <NEW_LINE> self.inertia = BasePointMass2d._PHYSICS_DEFAULTS['INERTIA'] <NEW_LINE> self.omega = omega <NEW_LINE> self.maxomega = BasePointMass2d._PHYSICS_DEFAULTS['MAXOMEGA'] <NEW_LINE> self.maxtorque = BasePointMass2d._PHYSICS_DEFAULTS['MAXTORQUE'] <NEW_LINE> self.front = self.front.rotated_by(beta) <NEW_LINE> self.left = self.front.left_normal() <NEW_LINE> if spritedata is not None: <NEW_LINE> <INDENT> self.sprite = PointMass2dSprite(self, *spritedata) <NEW_LINE> <DEDENT> <DEDENT> def move(self, delta_t=1.0, force_vector=None): <NEW_LINE> <INDENT> self.pos = self.pos + self.vel.scm(delta_t) <NEW_LINE> if force_vector: <NEW_LINE> <INDENT> force_vector.truncate(self.maxforce) <NEW_LINE> accel = force_vector.scm(delta_t/self.mass) <NEW_LINE> self.vel = self.vel + accel <NEW_LINE> <DEDENT> self.vel.truncate(self.maxspeed) <NEW_LINE> <DEDENT> def rotate(self, delta_t=1.0, torque=0): <NEW_LINE> <INDENT> self.front = self.front.rotated_by(self.omega).unit() <NEW_LINE> self.left = self.front.left_normal() <NEW_LINE> torque = max(min(torque, self.maxtorque), -self.maxtorque) <NEW_LINE> alpha = torque*delta_t/self.inertia <NEW_LINE> omega = self.omega + alpha <NEW_LINE> self.omega = max(min(omega, self.maxomega), -self.maxomega) | Moving object with linear and angular motion, with optional sprite.
Notes
-----
Although this isn't really a point mass in the physical sense, we inherit
from BasePointMass2d in order to avoid duplicating or refactoring code. | 62598fa7e1aae11d1e7ce7a9 |
class FilteredProductSeriesVocabulary(SQLObjectVocabularyBase): <NEW_LINE> <INDENT> _table = ProductSeries <NEW_LINE> _orderBy = ['product', 'name'] <NEW_LINE> def toTerm(self, obj): <NEW_LINE> <INDENT> return SimpleTerm( obj, obj.id, '%s %s' % (obj.product.name, obj.name)) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> launchbag = getUtility(ILaunchBag) <NEW_LINE> if launchbag.product is not None: <NEW_LINE> <INDENT> for series in launchbag.product.series: <NEW_LINE> <INDENT> yield self.toTerm(series) | Describes ProductSeries of a particular product. | 62598fa756ac1b37e63020f8 |
class VideoPlayView(LoginRequiredMixin, View): <NEW_LINE> <INDENT> def get(self, request, video_id): <NEW_LINE> <INDENT> video = Video.objects.get(id=int(video_id)) <NEW_LINE> course=video.lesson.course <NEW_LINE> course.students += 1 <NEW_LINE> course.save() <NEW_LINE> user_courses = UserCourse.objects.filter(user=request.user, course=course) <NEW_LINE> if not user_courses: <NEW_LINE> <INDENT> user_course = UserCourse() <NEW_LINE> user_course.user = request.user <NEW_LINE> user_course.course = course <NEW_LINE> user_course.save() <NEW_LINE> <DEDENT> all_resources = CourseResource.objects.filter(course=course) <NEW_LINE> user_courses = UserCourse.objects.filter(course=course) <NEW_LINE> user_ids = [user_course.user.id for user_course in user_courses] <NEW_LINE> all_user_courses = UserCourse.objects.filter(user_id__in=user_ids) <NEW_LINE> course_ids = [user_course.course.id for user_course in all_user_courses] <NEW_LINE> all_courses = Course.objects.filter(id__in=course_ids).order_by('-click_nums') <NEW_LINE> return render(request, 'course-play.html', { 'course': course, 'all_resources': all_resources, 'all_courses': all_courses, 'video':video, }) | 课程章节视频播放页面 | 62598fa7656771135c48958d |
class Helper(Basic): <NEW_LINE> <INDENT> def __init__( self, name, registry): <NEW_LINE> <INDENT> super(Helper, self).__init__('does not matter', 'does not matter') <NEW_LINE> self._name = name <NEW_LINE> self._registry = registry.registry <NEW_LINE> <DEDENT> @property <NEW_LINE> def suffix(self): <NEW_LINE> <INDENT> p = subprocess.Popen(['docker-credential-{name}'.format(name=self._name), 'get'], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT) <NEW_LINE> stdout = p.communicate(input=self._registry)[0] <NEW_LINE> if p.returncode != 0: <NEW_LINE> <INDENT> raise Exception('Error fetching credential for %s, exit status: %d\n%s' % (self._name, p.returncode, stdout)) <NEW_LINE> <DEDENT> blob = json.loads(stdout.decode()) <NEW_LINE> return base64.b64encode(blob['Username'] + ':' + blob['Secret']) | This provider wraps a particularly named credential helper. | 62598fa7b7558d589546353b |
class VerificationIPFlowParameters(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'target_resource_id': {'required': True}, 'direction': {'required': True}, 'protocol': {'required': True}, 'local_port': {'required': True}, 'remote_port': {'required': True}, 'local_ip_address': {'required': True}, 'remote_ip_address': {'required': True}, } <NEW_LINE> _attribute_map = { 'target_resource_id': {'key': 'targetResourceId', 'type': 'str'}, 'direction': {'key': 'direction', 'type': 'str'}, 'protocol': {'key': 'protocol', 'type': 'str'}, 'local_port': {'key': 'localPort', 'type': 'str'}, 'remote_port': {'key': 'remotePort', 'type': 'str'}, 'local_ip_address': {'key': 'localIPAddress', 'type': 'str'}, 'remote_ip_address': {'key': 'remoteIPAddress', 'type': 'str'}, 'target_nic_resource_id': {'key': 'targetNicResourceId', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(VerificationIPFlowParameters, self).__init__(**kwargs) <NEW_LINE> self.target_resource_id = kwargs['target_resource_id'] <NEW_LINE> self.direction = kwargs['direction'] <NEW_LINE> self.protocol = kwargs['protocol'] <NEW_LINE> self.local_port = kwargs['local_port'] <NEW_LINE> self.remote_port = kwargs['remote_port'] <NEW_LINE> self.local_ip_address = kwargs['local_ip_address'] <NEW_LINE> self.remote_ip_address = kwargs['remote_ip_address'] <NEW_LINE> self.target_nic_resource_id = kwargs.get('target_nic_resource_id', None) | Parameters that define the IP flow to be verified.
All required parameters must be populated in order to send to Azure.
:param target_resource_id: Required. The ID of the target resource to perform next-hop on.
:type target_resource_id: str
:param direction: Required. The direction of the packet represented as a 5-tuple. Possible
values include: "Inbound", "Outbound".
:type direction: str or ~azure.mgmt.network.v2016_12_01.models.Direction
:param protocol: Required. Protocol to be verified on. Possible values include: "TCP", "UDP".
:type protocol: str or ~azure.mgmt.network.v2016_12_01.models.Protocol
:param local_port: Required. The local port. Acceptable values are a single integer in the
range (0-65535). Support for * for the source port, which depends on the direction.
:type local_port: str
:param remote_port: Required. The remote port. Acceptable values are a single integer in the
range (0-65535). Support for * for the source port, which depends on the direction.
:type remote_port: str
:param local_ip_address: Required. The local IP address. Acceptable values are valid IPv4
addresses.
:type local_ip_address: str
:param remote_ip_address: Required. The remote IP address. Acceptable values are valid IPv4
addresses.
:type remote_ip_address: str
:param target_nic_resource_id: The NIC ID. (If VM has multiple NICs and IP forwarding is
enabled on any of them, then this parameter must be specified. Otherwise optional).
:type target_nic_resource_id: str | 62598fa72c8b7c6e89bd36d1 |
class PageTitleMixin(object): <NEW_LINE> <INDENT> page_title = None <NEW_LINE> active_tab = None <NEW_LINE> def get_page_title(self): <NEW_LINE> <INDENT> return self.page_title <NEW_LINE> <DEDENT> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> ctx = super(PageTitleMixin, self).get_context_data(**kwargs) <NEW_LINE> ctx.setdefault('page_title', self.get_page_title()) <NEW_LINE> ctx.setdefault('active_tab', self.active_tab) <NEW_LINE> return ctx | Passes page_title and active_tab into context, which makes it quite useful
for the accounts views.
Dynamic page titles are possible by overriding get_page_title. | 62598fa755399d3f05626430 |
class CyclesPlotter: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.labels = [] <NEW_LINE> self.cycles = [] <NEW_LINE> <DEDENT> def items(self): <NEW_LINE> <INDENT> return zip(self.labels, self.cycles) <NEW_LINE> <DEDENT> def add_label_cycle(self, label, cycle): <NEW_LINE> <INDENT> self.labels.append(label) <NEW_LINE> self.cycles.append(cycle) <NEW_LINE> <DEDENT> @add_fig_kwargs <NEW_LINE> def combiplot(self, fontsize=8, **kwargs): <NEW_LINE> <INDENT> ax_list = None <NEW_LINE> for i, (label, cycle) in enumerate(self.items()): <NEW_LINE> <INDENT> fig = cycle.plot( ax_list=ax_list, label=label, fontsize=fontsize, lw=2.0, marker="o", linestyle="-", show=False, ) <NEW_LINE> ax_list = fig.axes <NEW_LINE> <DEDENT> return fig <NEW_LINE> <DEDENT> def slideshow(self, **kwargs): <NEW_LINE> <INDENT> for label, cycle in self.items(): <NEW_LINE> <INDENT> cycle.plot(title=label, tight_layout=True) | Relies on the plot method of cycle objects to build multiple subfigures. | 62598fa72ae34c7f260aafed |
class TestConstraintPropagation(unittest.TestCase): <NEW_LINE> <INDENT> def test_3by3_matrix(self): <NEW_LINE> <INDENT> affinity = np.array([[1, 0.25, 0], [0.31, 1, 0], [0, 0, 1]]) <NEW_LINE> constraint_matrix = np.array([[1, 1, 0], [1, 1, 0], [0, 0, 0]]) <NEW_LINE> adjusted_affinity = constraint.ConstraintPropagation( alpha=0.6).adjust_affinity(affinity, constraint_matrix) <NEW_LINE> expected = np.array([[1, 0.97, 0], [1.03, 1, 0], [0, 0, 1]]) <NEW_LINE> self.assertTrue( np.allclose(np.array(adjusted_affinity), np.array(expected), atol=0.01)) | Tests for the ConstraintPropagation class. | 62598fa776e4537e8c3ef4b8 |
class VersionNegotiationFailed(NoApplicableCode): <NEW_LINE> <INDENT> code = 400 | Version negotiation exception implementation
| 62598fa767a9b606de545ed8 |
class Trade(BaseModel): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self._default_params = { 'book': kwargs.get('book'), 'tid': kwargs.get('tid'), 'amount': Decimal(kwargs.get('amount')), 'price': Decimal(kwargs.get('price')), 'maker_side': kwargs.get('maker_side'), 'created_at': dateutil.parser.parse(kwargs.get('created_at')) } <NEW_LINE> for (param, val) in self._default_params.items(): <NEW_LINE> <INDENT> setattr(self, param, val) <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Trade(tid={tid}, price={price}, amount={amount}, maker_side={maker_side}, created_at={created_at})".format( tid=self.tid, price=self.price, amount=self.amount, maker_side=self.maker_side, created_at=self.created_at) | A class that represents a Bitso public trade. | 62598fa7d6c5a102081e2053 |
class TempFile: <NEW_LINE> <INDENT> def __init__(self, content: str) -> None: <NEW_LINE> <INDENT> with NamedTemporaryFile(delete=False, mode="w", encoding="utf-8") as f: <NEW_LINE> <INDENT> f.write(content) <NEW_LINE> f.flush() <NEW_LINE> f.close() <NEW_LINE> self.f = f.name <NEW_LINE> <DEDENT> <DEDENT> def __del__(self) -> None: <NEW_LINE> <INDENT> self.delete() <NEW_LINE> <DEDENT> def get_name(self) -> str: <NEW_LINE> <INDENT> return self.f <NEW_LINE> <DEDENT> def delete(self) -> None: <NEW_LINE> <INDENT> if os.path.exists(self.f): <NEW_LINE> <INDENT> os.unlink(self.f) | Temporary file for convenience in tests that include opening and reading files. | 62598fa791f36d47f2230e2a |
class Summarizer(Summarizer): <NEW_LINE> <INDENT> def __init__(self, args, opts): <NEW_LINE> <INDENT> self.s_t = SentTokenizer(offsets=False) <NEW_LINE> self.w_t = WordTokenizer(stem=False) <NEW_LINE> <DEDENT> def summarize(self, extracted_refs, facet_results, max_length=250): <NEW_LINE> <INDENT> summaries = defaultdict(lambda: defaultdict(list)) <NEW_LINE> for t in extracted_refs: <NEW_LINE> <INDENT> topic = t[0]['topic'] <NEW_LINE> citance = t[0]['citance_number'] <NEW_LINE> if isinstance(t[0]['sentence'][0], list): <NEW_LINE> <INDENT> logger.warn('Unexpected, should check') <NEW_LINE> <DEDENT> summaries[topic.upper()] [facet_results[topic.upper()] [str(citance)]['SVM_LABEL']].append([t[0]['citation_text']]) <NEW_LINE> <DEDENT> summarizer = TextRankSummarizer(Stemmer('english')) <NEW_LINE> final_summ = defaultdict(lambda: defaultdict(dict)) <NEW_LINE> ret_summ = defaultdict(list) <NEW_LINE> counts = defaultdict(lambda: defaultdict(dict)) <NEW_LINE> for t in summaries: <NEW_LINE> <INDENT> for facet in summaries[t]: <NEW_LINE> <INDENT> if len(summaries[t][facet]) > 1: <NEW_LINE> <INDENT> summs = list( itertools.chain.from_iterable(summaries[t][facet])) <NEW_LINE> parser = PlaintextParser.from_string( ' '.join(summs), Tokenizer('english')) <NEW_LINE> summ = summarizer(parser.document, max_length) <NEW_LINE> final_summ[t][facet] = [unicode(sent) for sent in summ] <NEW_LINE> counts[t][facet] = len(final_summ[t][facet]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> final_summ[t][facet] = self.s_t(summaries[t][facet][0]) <NEW_LINE> <DEDENT> <DEDENT> i = 0 <NEW_LINE> while self.w_t.count_words(ret_summ[t]) < max_length: <NEW_LINE> <INDENT> for fct in final_summ[t]: <NEW_LINE> <INDENT> if i < len(final_summ[t][fct]): <NEW_LINE> <INDENT> ret_summ[t].append(final_summ[t][fct][i]) <NEW_LINE> <DEDENT> <DEDENT> i += 1 <NEW_LINE> <DEDENT> while self.w_t.count_words(ret_summ[t]) > max_length: <NEW_LINE> <INDENT> ret_summ[t].pop() <NEW_LINE> <DEDENT> <DEDENT> return ret_summ | classdocs | 62598fa7460517430c431fe2 |
class RevisionValidationForm(RevisionForm): <NEW_LINE> <INDENT> def clean_slug(self): <NEW_LINE> <INDENT> is_valid = True <NEW_LINE> original = self.cleaned_data['slug'] <NEW_LINE> if '/' in original or '?' in original or ' ' in original: <NEW_LINE> <INDENT> is_valid = False <NEW_LINE> raise forms.ValidationError(SLUG_INVALID) <NEW_LINE> <DEDENT> self.cleaned_data['slug'] = self.data['slug'] = self.parent_slug + '/' + original <NEW_LINE> is_valid = is_valid and super(RevisionValidationForm, self).clean_slug() <NEW_LINE> self.cleaned_data['slug'] = self.data['slug'] = original <NEW_LINE> return self.cleaned_data['slug'] | Created primarily to disallow slashes in slugs during validation | 62598fa710dbd63aa1c70abf |
class RectPack: <NEW_LINE> <INDENT> def __init__(self, l, u, division_num, dim, scaler, aq_func): <NEW_LINE> <INDENT> self.l = l <NEW_LINE> self.u = u <NEW_LINE> self.center = (l + u) / 2 <NEW_LINE> j = np.mod(division_num, dim) <NEW_LINE> k = (division_num - j) / dim <NEW_LINE> self.d = np.sqrt(j * np.power(3, float(-2 * (k + 1))) + (dim - j) * np.power(3, float(-2 * k))) / 2 <NEW_LINE> self.division_num = division_num <NEW_LINE> self.fc, _, _ = aq_func.compute(scaler.inverse_transform(self.center)) <NEW_LINE> self.fc = -self.fc | class for the rectangular
including border, center and acquisition function value | 62598fa74f88993c371f0490 |
class RosdepWrapper(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> installer_context = create_default_installer_context(verbose=False) <NEW_LINE> self.installer, self.installer_keys, self.default_key, self.os_name, self.os_version = get_default_installer( installer_context=installer_context, verbose=False) <NEW_LINE> sources_loader = SourcesListLoader.create_default() <NEW_LINE> lookup = RosdepLookup.create_from_rospkg(sources_loader=sources_loader) <NEW_LINE> lookup.verbose = True <NEW_LINE> self.view = lookup.get_rosdep_view(DEFAULT_VIEW_KEY, verbose=False) <NEW_LINE> <DEDENT> def get_rule(self, name): <NEW_LINE> <INDENT> rosdep_dependency = self.view.lookup(name) <NEW_LINE> installer_name, rule = rosdep_dependency.get_rule_for_platform( self.os_name, self.os_version, self.installer_keys, self.default_key) <NEW_LINE> return installer_name, rule <NEW_LINE> <DEDENT> def resolve(self, rule): <NEW_LINE> <INDENT> return self.installer.resolve(rule) | Wrapper around rosdep.
Hides all the configuration of rosdep from the caller. | 62598fa7627d3e7fe0e06db8 |
class Pep8CheckCommand(sublime_plugin.TextCommand): <NEW_LINE> <INDENT> def run(self, edit): <NEW_LINE> <INDENT> if self.view.file_name().endswith('.py'): <NEW_LINE> <INDENT> folder_name, file_name = os.path.split(self.view.file_name()) <NEW_LINE> self.view.window().run_command('exec', {'cmd': ['pep8', '--repeat', '--verbose', '--ignore=E501', '--show-source', '--statistics', '--count', file_name], 'working_dir': folder_name}) <NEW_LINE> sublime.status_message("pep8 " + file_name) <NEW_LINE> <DEDENT> <DEDENT> def is_enabled(self): <NEW_LINE> <INDENT> return self.view.file_name().endswith('.py') | This will invoke PEP8 checking on the given file.
pep8.py must be in your system's path for this to work.
http://pypi.python.org/pypi/pep8
Options:
--version show program's version number and exit
--help show this help message and exit
--verbose print status messages, or debug with -vv
--quiet report only file names, or nothing with -qq
--repeat show all occurrences of the same error
--exclude=patterns exclude files or directories which match these comma
separated patterns (default: .svn,CVS,.bzr,.hg,.git)
--filename=patterns when parsing directories, only check filenames
matching these comma separated patterns (default: *.py)
--select=errors select errors and warnings (e.g. E,W6)
--ignore=errors skip errors and warnings (e.g. E4,W)
--show-source show source code for each error
--show-pep8 show text of PEP 8 for each error
--statistics count errors and warnings
--count print total number of errors and warnings to standard
error and set exit code to 1 if total is not null
--benchmark measure processing speed
--testsuite=dir run regression tests from dir
--doctest run doctest on myself | 62598fa7fff4ab517ebcd6f2 |
class TestTtest(object): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setup_class(cls): <NEW_LINE> <INDENT> data = longley.load(as_pandas=False) <NEW_LINE> data.exog = add_constant(data.exog, prepend=False) <NEW_LINE> cls.res1 = OLS(data.endog, data.exog).fit() <NEW_LINE> R = np.identity(7) <NEW_LINE> cls.Ttest = cls.res1.t_test(R) <NEW_LINE> hyp = 'x1 = 0, x2 = 0, x3 = 0, x4 = 0, x5 = 0, x6 = 0, const = 0' <NEW_LINE> cls.NewTTest = cls.res1.t_test(hyp) <NEW_LINE> <DEDENT> def test_new_tvalue(self): <NEW_LINE> <INDENT> assert_equal(self.NewTTest.tvalue, self.Ttest.tvalue) <NEW_LINE> <DEDENT> def test_tvalue(self): <NEW_LINE> <INDENT> assert_almost_equal(self.Ttest.tvalue, self.res1.tvalues, DECIMAL_4) <NEW_LINE> <DEDENT> def test_sd(self): <NEW_LINE> <INDENT> assert_almost_equal(self.Ttest.sd, self.res1.bse, DECIMAL_4) <NEW_LINE> <DEDENT> def test_pvalue(self): <NEW_LINE> <INDENT> assert_almost_equal(self.Ttest.pvalue, student_t.sf( np.abs(self.res1.tvalues), self.res1.model.df_resid)*2, DECIMAL_4) <NEW_LINE> <DEDENT> def test_df_denom(self): <NEW_LINE> <INDENT> assert_equal(self.Ttest.df_denom, self.res1.model.df_resid) <NEW_LINE> <DEDENT> def test_effect(self): <NEW_LINE> <INDENT> assert_almost_equal(self.Ttest.effect, self.res1.params) | Test individual t-tests. Ie., are the coefficients significantly
different than zero.
| 62598fa78c0ade5d55dc3617 |
class itkAccumulateImageFilterIUL2IUL2(itkImageToImageFilterAPython.itkImageToImageFilterIUL2IUL2): <NEW_LINE> <INDENT> thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> InputImageDimension = _itkAccumulateImageFilterPython.itkAccumulateImageFilterIUL2IUL2_InputImageDimension <NEW_LINE> OutputImageDimension = _itkAccumulateImageFilterPython.itkAccumulateImageFilterIUL2IUL2_OutputImageDimension <NEW_LINE> ImageDimensionCheck = _itkAccumulateImageFilterPython.itkAccumulateImageFilterIUL2IUL2_ImageDimensionCheck <NEW_LINE> def __New_orig__(): <NEW_LINE> <INDENT> return _itkAccumulateImageFilterPython.itkAccumulateImageFilterIUL2IUL2___New_orig__() <NEW_LINE> <DEDENT> __New_orig__ = staticmethod(__New_orig__) <NEW_LINE> def GetAccumulateDimension(self): <NEW_LINE> <INDENT> return _itkAccumulateImageFilterPython.itkAccumulateImageFilterIUL2IUL2_GetAccumulateDimension(self) <NEW_LINE> <DEDENT> def SetAccumulateDimension(self, *args): <NEW_LINE> <INDENT> return _itkAccumulateImageFilterPython.itkAccumulateImageFilterIUL2IUL2_SetAccumulateDimension(self, *args) <NEW_LINE> <DEDENT> def SetAverage(self, *args): <NEW_LINE> <INDENT> return _itkAccumulateImageFilterPython.itkAccumulateImageFilterIUL2IUL2_SetAverage(self, *args) <NEW_LINE> <DEDENT> def GetAverage(self): <NEW_LINE> <INDENT> return _itkAccumulateImageFilterPython.itkAccumulateImageFilterIUL2IUL2_GetAverage(self) <NEW_LINE> <DEDENT> def AverageOn(self): <NEW_LINE> <INDENT> return _itkAccumulateImageFilterPython.itkAccumulateImageFilterIUL2IUL2_AverageOn(self) <NEW_LINE> <DEDENT> def AverageOff(self): <NEW_LINE> <INDENT> return _itkAccumulateImageFilterPython.itkAccumulateImageFilterIUL2IUL2_AverageOff(self) <NEW_LINE> <DEDENT> __swig_destroy__ = _itkAccumulateImageFilterPython.delete_itkAccumulateImageFilterIUL2IUL2 <NEW_LINE> def cast(*args): <NEW_LINE> <INDENT> return _itkAccumulateImageFilterPython.itkAccumulateImageFilterIUL2IUL2_cast(*args) <NEW_LINE> <DEDENT> cast = staticmethod(cast) <NEW_LINE> def GetPointer(self): <NEW_LINE> <INDENT> return _itkAccumulateImageFilterPython.itkAccumulateImageFilterIUL2IUL2_GetPointer(self) <NEW_LINE> <DEDENT> def New(*args, **kargs): <NEW_LINE> <INDENT> obj = itkAccumulateImageFilterIUL2IUL2.__New_orig__() <NEW_LINE> import itkTemplate <NEW_LINE> itkTemplate.New(obj, *args, **kargs) <NEW_LINE> return obj <NEW_LINE> <DEDENT> New = staticmethod(New) | Proxy of C++ itkAccumulateImageFilterIUL2IUL2 class | 62598fa71b99ca400228f4b6 |
class Bond(_msys.Bond): <NEW_LINE> <INDENT> __slots__ = () <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return "<Bond %d>" % self.id <NEW_LINE> <DEDENT> @property <NEW_LINE> def system(self): <NEW_LINE> <INDENT> return System(self._ptr) <NEW_LINE> <DEDENT> @property <NEW_LINE> def first(self): <NEW_LINE> <INDENT> return Atom(self._ptr, self.i) <NEW_LINE> <DEDENT> @property <NEW_LINE> def second(self): <NEW_LINE> <INDENT> return Atom(self._ptr, self.j) <NEW_LINE> <DEDENT> def other(self, atom): <NEW_LINE> <INDENT> return Atom(self._ptr, self.otherId(atom.id)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def atoms(self): <NEW_LINE> <INDENT> return self.first, self.second | Represents a bond in a System | 62598fa7a8ecb0332587111d |
class EMC1072(): <NEW_LINE> <INDENT> def __init__(self, bus: int, chip_address: int=0x4c): <NEW_LINE> <INDENT> self._bus = SMBus(bus) <NEW_LINE> self._chip_address = chip_address <NEW_LINE> self.status = Status(self._bus, self._chip_address) <NEW_LINE> self.configuration = Configuration(self._bus, self._chip_address) <NEW_LINE> self.temperature = Temperature(self._bus, self._chip_address) <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> self._bus.close() | Interface to the EMC1072 temperature sensor. | 62598fa724f1403a9268583a |
class Devotional(ObjectType): <NEW_LINE> <INDENT> id = ID() <NEW_LINE> title = String() <NEW_LINE> passage = String() <NEW_LINE> body = String() <NEW_LINE> creation_date = DateTime() <NEW_LINE> publish_date = Date() <NEW_LINE> author = Field(lambda: User) <NEW_LINE> comments = List(lambda: Comment) <NEW_LINE> def __init__(self, model, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> self.model = model <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_devotional(cls, id): <NEW_LINE> <INDENT> model = DevotionalModel.query.filter_by(id=id).first() <NEW_LINE> return cls.create_devotional_from_model(model) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def create_devotional_from_model(cls, model): <NEW_LINE> <INDENT> return cls( id=model.id, title=model.title, passage=model.passage, body=model.body, creation_date=model.creation_date, publish_date=model.publish_date, model=model ) <NEW_LINE> <DEDENT> def resolve_author(self, info): <NEW_LINE> <INDENT> return User.create_user_from_model(self.model.author) <NEW_LINE> <DEDENT> def resolve_comments(self, info): <NEW_LINE> <INDENT> print(len(self.model.comments)) <NEW_LINE> print(self.model.comments[0]) <NEW_LINE> result = [Comment.create_comment_from_model(c) for c in self.model.comments] <NEW_LINE> print(result) <NEW_LINE> return result | Devotional graphql type definition. | 62598fa7eab8aa0e5d30bc98 |
class SystemUserChangeForm(forms.ModelForm): <NEW_LINE> <INDENT> password = ReadOnlyPasswordHashField() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = SystemUser <NEW_LINE> fields = ('email', 'password', 'username', 'is_active', 'is_superuser') <NEW_LINE> <DEDENT> def clean_password(self): <NEW_LINE> <INDENT> return self.initial["password"] | A form for updating users. Includes all the fields on
the user, but replaces the password field with admin's
password hash display field. | 62598fa7656771135c48958f |
class AllViewSet(viewsets.ReadOnlyModelViewSet): <NEW_LINE> <INDENT> queryset = Product.objects.all() <NEW_LINE> serializer_class = ProductSerializer | A viewset for viewing all products | 62598fa78a43f66fc4bf208a |
class ComputationLayer: <NEW_LINE> <INDENT> def __init__(self, name): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.input = None <NEW_LINE> self.output = None <NEW_LINE> <DEDENT> def _ops(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def _compile(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def ops_format(self): <NEW_LINE> <INDENT> raise NotImplementedError | Base class for computation graph layers.
Inherited by NeuronLayer and ConnectionLayer.
Basically, creates a computation graph kernel (or subset thereof).
Defines:
- computation graph nodes the subclasses must have (and possibly create): input and output
- abstract methods the subclasses must implement in order to compile to a computation graph
Variables:
name: name of the layer. Must be unique within sibling layers.
input: tf.Tensor operation, such as tf.Variable
output: tf.Tensor operation, such as tf.Variable | 62598fa7dd821e528d6d8e43 |
class AbsComplexPlane(ABC): <NEW_LINE> <INDENT> xmin = NotImplemented <NEW_LINE> xmax = NotImplemented <NEW_LINE> xlen = NotImplemented <NEW_LINE> ymin = NotImplemented <NEW_LINE> ymax = NotImplemented <NEW_LINE> ylen = NotImplemented <NEW_LINE> plane = NotImplemented <NEW_LINE> f = NotImplemented <NEW_LINE> @abstractmethod <NEW_LINE> def refresh(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def zoom(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def set_f(self): <NEW_LINE> <INDENT> pass | Abstract base class for complex plane.
A complex plane is a 2x2 grid of complex numbers, having
the form (x + y*1j), where 1j is the unit imaginary number in
Python, and one can think of x and y as the coordinates for
the horizontal axis and the vertical axis of the plane,
respectively. Recall that (1j)*(1j) == -1. Also recall that
the FOIL rule for multiplication still works:
(x + y*1j)*(v + w*1j) = (x*v - y*w + (x*w + y*v)*1j)
You can check these results in an interpreter.
We will explore several implementations for a complex plane in
this course, so we wish to have an abstract interface that
is independent of any particular implementation.
In addition to generating the 2x2 grid of numbers (x + y*1j),
we wish to easily support transformations of the plane with
an arbitrary function f. Done properly, the attribute self.plane
should store a 2x2 grid of numbers f(x + y*1j) such that the
parameter x ranges from self.xmin to self.xmax with self.xlen
total points, while the parameter y ranges from self.ymin to
self.ymax with self.ylen total points. By default, the function
f should be the identity function id, which does nothing to
the bare complex plane.
Attributes:
xmax (float) : maximum horizontal axis value
xmin (float) : minimum horizontal axis value
xlen (int) : number of horizontal points
ymax (float) : maximum vertical axis value
ymin (float) : minimum vertical axis value
ylen (int) : number of vertical points
plane : stored complex plane implementation
f (func) : function displayed in the plane | 62598fa7851cf427c66b81d6 |
class ActionGroup(object): <NEW_LINE> <INDENT> STANDARD = 0 <NEW_LINE> TOGGLE = 1 <NEW_LINE> def __init__(self, shell, group_name): <NEW_LINE> <INDENT> self.group_name = group_name <NEW_LINE> self.shell = shell <NEW_LINE> self._actions = {} <NEW_LINE> if is_rb3(self.shell): <NEW_LINE> <INDENT> self.actiongroup = Gio.SimpleActionGroup() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.actiongroup = Gtk.ActionGroup(group_name) <NEW_LINE> uim = self.shell.props.ui_manager <NEW_LINE> uim.insert_action_group(self.actiongroup) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self.group_name <NEW_LINE> <DEDENT> def remove_actions(self): <NEW_LINE> <INDENT> for action in self.actiongroup.list_actions(): <NEW_LINE> <INDENT> self.actiongroup.remove_action(action) <NEW_LINE> <DEDENT> <DEDENT> def get_action(self, action_name): <NEW_LINE> <INDENT> return self._actions[action_name] <NEW_LINE> <DEDENT> def add_action_with_accel(self, func, action_name, accel, **args): <NEW_LINE> <INDENT> args['accel'] = accel <NEW_LINE> return self.add_action(func, action_name, **args) <NEW_LINE> <DEDENT> def add_action(self, func, action_name, **args): <NEW_LINE> <INDENT> if 'label' in args: <NEW_LINE> <INDENT> label = args['label'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> label = action_name <NEW_LINE> <DEDENT> if 'accel' in args: <NEW_LINE> <INDENT> accel = args['accel'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> accel = None <NEW_LINE> <DEDENT> state = ActionGroup.STANDARD <NEW_LINE> if 'action_state' in args: <NEW_LINE> <INDENT> state = args['action_state'] <NEW_LINE> <DEDENT> if is_rb3(self.shell): <NEW_LINE> <INDENT> if state == ActionGroup.TOGGLE: <NEW_LINE> <INDENT> action = Gio.SimpleAction.new_stateful(action_name, None, GLib.Variant('b', False)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> action = Gio.SimpleAction.new(action_name, None) <NEW_LINE> <DEDENT> action_type = 'win' <NEW_LINE> if 'action_type' in args: <NEW_LINE> <INDENT> if args['action_type'] == 'app': <NEW_LINE> <INDENT> action_type = 'app' <NEW_LINE> <DEDENT> <DEDENT> app = Gio.Application.get_default() <NEW_LINE> if action_type == 'app': <NEW_LINE> <INDENT> app.add_action(action) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.shell.props.window.add_action(action) <NEW_LINE> self.actiongroup.add_action(action) <NEW_LINE> <DEDENT> if accel: <NEW_LINE> <INDENT> app.add_accelerator(accel, action_type + "." + action_name, None) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if 'stock_id' in args: <NEW_LINE> <INDENT> stock_id = args['stock_id'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> stock_id = Gtk.STOCK_CLEAR <NEW_LINE> <DEDENT> if state == ActionGroup.TOGGLE: <NEW_LINE> <INDENT> action = Gtk.ToggleAction(label=label, name=action_name, tooltip='', stock_id=stock_id) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> action = Gtk.Action(label=label, name=action_name, tooltip='', stock_id=stock_id) <NEW_LINE> <DEDENT> if accel: <NEW_LINE> <INDENT> self.actiongroup.add_action_with_accel(action, accel) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.actiongroup.add_action(action) <NEW_LINE> <DEDENT> <DEDENT> act = Action(self.shell, action) <NEW_LINE> act.connect('activate', func, args) <NEW_LINE> act.label = label <NEW_LINE> act.accel = accel <NEW_LINE> self._actions[action_name] = act <NEW_LINE> return act | container for all Actions used to associate with menu items | 62598fa72c8b7c6e89bd36d3 |
class AppkeyGetAllRsp(ResponsePacket): <NEW_LINE> <INDENT> def __init__(self, raw_data): <NEW_LINE> <INDENT> __data = {} <NEW_LINE> __data["subnet_handle"], = struct.unpack("<H", raw_data[0:2]) <NEW_LINE> __data["appkey_key_index"] = raw_data[2:94] <NEW_LINE> super(AppkeyGetAllRsp, self).__init__("AppkeyGetAll", 0x9A, __data) | Response to a(n) AppkeyGetAll command. | 62598fa78e7ae83300ee8fb0 |
class TestController(object): <NEW_LINE> <INDENT> application_under_test = application_name <NEW_LINE> fixtures = [BaseFixture, ] <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> self.app = load_app(self.application_under_test) <NEW_LINE> try: <NEW_LINE> <INDENT> teardown_db() <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print('-> err ({})'.format(e.__str__())) <NEW_LINE> <DEDENT> setup_app(section_name=self.application_under_test) <NEW_LINE> setup_db() <NEW_LINE> fixtures_loader = FixturesLoader([BaseFixture]) <NEW_LINE> fixtures_loader.loads(self.fixtures) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> DBSession.close() <NEW_LINE> daemons.execute_in_thread('radicale', lambda: transaction.commit()) <NEW_LINE> teardown_db() <NEW_LINE> transaction.commit() <NEW_LINE> DBSession.close_all() <NEW_LINE> config['tg.app_globals'].sa_engine.dispose() | Base functional test case for the controllers.
The tracim application instance (``self.app``) set up in this test
case (and descendants) has authentication disabled, so that developers can
test the protected areas independently of the :mod:`repoze.who` plugins
used initially. This way, authentication can be tested once and separately.
Check tracim.tests.functional.test_authentication for the repoze.who
integration tests.
This is the officially supported way to test protected areas with
repoze.who-testutil (http://code.gustavonarea.net/repoze.who-testutil/). | 62598fa74e4d562566372333 |
class TestPositionalsNargsOptional(ParserTestCase): <NEW_LINE> <INDENT> argument_signatures = [Sig('foo', nargs='?')] <NEW_LINE> failures = ['-x', 'a b'] <NEW_LINE> successes = [ ('', NS(foo=None)), ('a', NS(foo='a')), ] | Tests an Optional Positional | 62598fa75fdd1c0f98e5dea6 |
class SimpleProcess(LocalProcess): <NEW_LINE> <INDENT> def read(self, filename=None): <NEW_LINE> <INDENT> if filename is None: <NEW_LINE> <INDENT> filename = self.main_src.output <NEW_LINE> <DEDENT> if os.path.isdir(filename): <NEW_LINE> <INDENT> filelist = [os.path.join(filename, f) for f in os.listdir(filename) if not f.startswith('.')] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> filelist = [filename] <NEW_LINE> <DEDENT> for f in filelist: <NEW_LINE> <INDENT> inf = open(f, 'r') <NEW_LINE> for line in inf: <NEW_LINE> <INDENT> yield line <NEW_LINE> <DEDENT> inf.close() <NEW_LINE> <DEDENT> <DEDENT> def write(self, fmt, *args): <NEW_LINE> <INDENT> self.outf.write(fmt % args) <NEW_LINE> <DEDENT> def execute(self): <NEW_LINE> <INDENT> self.outf = open(self.output, 'w') <NEW_LINE> try: <NEW_LINE> <INDENT> self.do_execute() <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> self.outf.close() <NEW_LINE> <DEDENT> <DEDENT> def do_execute(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> with open(self.output, 'r') as outf: <NEW_LINE> <INDENT> return outf.read() <NEW_LINE> <DEDENT> <DEDENT> def iter(self): <NEW_LINE> <INDENT> with open(self.output, 'r') as outf: <NEW_LINE> <INDENT> for line in outf: <NEW_LINE> <INDENT> yield line | A process that provides simple utilities for reading inputs and
writing outputs. It is running locally. | 62598fa792d797404e388aec |
class SSDEfficientNetB2BiFPNKerasFeatureExtractor( SSDEfficientNetBiFPNKerasFeatureExtractor): <NEW_LINE> <INDENT> def __init__(self, is_training, depth_multiplier, min_depth, pad_to_multiple, conv_hyperparams, freeze_batchnorm, inplace_batchnorm_update, bifpn_min_level=3, bifpn_max_level=7, bifpn_num_iterations=5, bifpn_num_filters=112, bifpn_combine_method='fast_attention', use_explicit_padding=None, use_depthwise=None, override_base_feature_extractor_hyperparams=None, name='EfficientDet-D2'): <NEW_LINE> <INDENT> super(SSDEfficientNetB2BiFPNKerasFeatureExtractor, self).__init__( is_training=is_training, depth_multiplier=depth_multiplier, min_depth=min_depth, pad_to_multiple=pad_to_multiple, conv_hyperparams=conv_hyperparams, freeze_batchnorm=freeze_batchnorm, inplace_batchnorm_update=inplace_batchnorm_update, bifpn_min_level=bifpn_min_level, bifpn_max_level=bifpn_max_level, bifpn_num_iterations=bifpn_num_iterations, bifpn_num_filters=bifpn_num_filters, bifpn_combine_method=bifpn_combine_method, efficientnet_version='efficientnet-b2', use_explicit_padding=use_explicit_padding, use_depthwise=use_depthwise, override_base_feature_extractor_hyperparams= override_base_feature_extractor_hyperparams, name=name) | SSD Keras EfficientNet-b2 BiFPN (EfficientDet-d2) Feature Extractor. | 62598fa7f7d966606f747ef2 |
class DeserializeInstance(object): <NEW_LINE> <INDENT> def __init__(self, obj_dict): <NEW_LINE> <INDENT> self.user = None <NEW_LINE> for key, value in obj_dict.items(): <NEW_LINE> <INDENT> if isinstance(value, dict): <NEW_LINE> <INDENT> setattr(self, key, DeserializeInstance(value) if isinstance(value, dict) else value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> setattr(self, key, value) | 字典对象反序列化
:param:
* obj_dict: (dict) 对象序列化字典
:return:
* obj: (object) 对象
举例如下::
print('--- DeserializeInstance demo ---')
temp_dict = {'user': {'name': {'last_name': 'zhang', 'first_name': 'san'}, 'address': 'Beijing'}}
new_obj = DeserializeInstance(temp_dict)
print('last_name is: ', new_obj.user.name.last_name)
print('first_name is: ', new_obj.user.name.first_name)
print('address is: ', new_obj.user.address)
print('---')
执行结果::
--- DeserializeInstance demo ---
last_name is: zhang
first_name is: san
address is: Beijing
--- | 62598fa760cbc95b0636425a |
class IVistor(ABC): <NEW_LINE> <INDENT> @abstractmethod <NEW_LINE> def visit_for_concrete_component_a(self, component: ConcreteComponentA): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def visit_for_concrete_component_b(self, component: ConcreteComponentB): <NEW_LINE> <INDENT> pass | Интерфейс посетителя (Visitor).
Объявляет набор методов, соответстующих классам компонентов.
Сигнатура метода посещения позволяет посетителю
понять конкретный класс компонента, с которым он имеет дело. | 62598fa75166f23b2e2432e5 |
class List(ConfigType): <NEW_LINE> <INDENT> def __init__(self, item_type=None, bounds=False, type_name='list value'): <NEW_LINE> <INDENT> super(List, self).__init__(type_name=type_name) <NEW_LINE> if item_type is None: <NEW_LINE> <INDENT> item_type = String() <NEW_LINE> <DEDENT> if not callable(item_type): <NEW_LINE> <INDENT> raise TypeError('item_type must be callable') <NEW_LINE> <DEDENT> self.item_type = item_type <NEW_LINE> self.bounds = bounds <NEW_LINE> <DEDENT> def __call__(self, value): <NEW_LINE> <INDENT> if isinstance(value, (list, tuple)): <NEW_LINE> <INDENT> return list(value) <NEW_LINE> <DEDENT> s = value.strip() <NEW_LINE> if self.bounds: <NEW_LINE> <INDENT> if not s.startswith('['): <NEW_LINE> <INDENT> raise ValueError('Value should start with "["') <NEW_LINE> <DEDENT> if not s.endswith(']'): <NEW_LINE> <INDENT> raise ValueError('Value should end with "]"') <NEW_LINE> <DEDENT> s = s[1:-1] <NEW_LINE> <DEDENT> if s: <NEW_LINE> <INDENT> values = s.split(',') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> values = [] <NEW_LINE> <DEDENT> if not values: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> result = [] <NEW_LINE> while values: <NEW_LINE> <INDENT> value = values.pop(0) <NEW_LINE> while True: <NEW_LINE> <INDENT> first_error = None <NEW_LINE> try: <NEW_LINE> <INDENT> validated_value = self.item_type(value.strip()) <NEW_LINE> break <NEW_LINE> <DEDENT> except ValueError as e: <NEW_LINE> <INDENT> if not first_error: <NEW_LINE> <INDENT> first_error = e <NEW_LINE> <DEDENT> if len(values) == 0: <NEW_LINE> <INDENT> raise first_error <NEW_LINE> <DEDENT> <DEDENT> value += ',' + values.pop(0) <NEW_LINE> <DEDENT> result.append(validated_value) <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'List of %s' % repr(self.item_type) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return ( (self.__class__ == other.__class__) and (self.item_type == other.item_type) ) <NEW_LINE> <DEDENT> def _formatter(self, value): <NEW_LINE> <INDENT> if isinstance(value, six.string_types): <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> return ','.join(value) | List type.
Represent values of other (item) type, separated by commas.
The resulting value is a list containing those values.
List doesn't know if item type can also contain commas. To workaround this
it tries the following: if the next part fails item validation, it appends
comma and next item until validation succeeds or there is no parts left.
In the later case it will signal validation error.
:param item_type: type of list items
:param bounds: if True, value should be inside "[" and "]" pair
:param type_name: Type name to be used in the sample config file.
.. versionchanged:: 2.7
Added *type_name* parameter. | 62598fa7e76e3b2f99fd8944 |
class HuobifGateway(BaseGateway): <NEW_LINE> <INDENT> default_setting = { "access_key": "", "secret_key": "", "session_number": 3, "proxy_host": "", "proxy_port": "", } <NEW_LINE> exchanges = [Exchange.HUOBI] <NEW_LINE> def __init__(self, event_engine): <NEW_LINE> <INDENT> super().__init__(event_engine, "HUOBIF") <NEW_LINE> self.rest_api = HuobifRestApi(self) <NEW_LINE> self.trade_ws_api = HuobifTradeWebsocketApi(self) <NEW_LINE> self.market_ws_api = HuobifDataWebsocketApi(self) <NEW_LINE> <DEDENT> def connect(self, setting: dict): <NEW_LINE> <INDENT> access_key = setting["access_key"] <NEW_LINE> secret_key = setting["secret_key"] <NEW_LINE> session_number = setting["session_number"] <NEW_LINE> proxy_host = setting["proxy_host"] <NEW_LINE> proxy_port = setting["proxy_port"] <NEW_LINE> if proxy_port.isdigit(): <NEW_LINE> <INDENT> proxy_port = int(proxy_port) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> proxy_port = 0 <NEW_LINE> <DEDENT> self.rest_api.connect(access_key, secret_key, session_number, proxy_host, proxy_port) <NEW_LINE> self.trade_ws_api.connect(access_key, secret_key, proxy_host, proxy_port) <NEW_LINE> self.market_ws_api.connect(access_key, secret_key, proxy_host, proxy_port) <NEW_LINE> self.init_query() <NEW_LINE> <DEDENT> def subscribe(self, req: SubscribeRequest): <NEW_LINE> <INDENT> self.market_ws_api.subscribe(req) <NEW_LINE> <DEDENT> def send_order(self, req: OrderRequest): <NEW_LINE> <INDENT> return self.rest_api.send_order(req) <NEW_LINE> <DEDENT> def cancel_order(self, req: CancelRequest): <NEW_LINE> <INDENT> self.rest_api.cancel_order(req) <NEW_LINE> <DEDENT> def send_orders(self, reqs: Sequence[OrderRequest]): <NEW_LINE> <INDENT> return self.rest_api.send_orders(reqs) <NEW_LINE> <DEDENT> def query_account(self): <NEW_LINE> <INDENT> self.rest_api.query_account() <NEW_LINE> <DEDENT> def query_position(self): <NEW_LINE> <INDENT> self.rest_api.query_position() <NEW_LINE> <DEDENT> def query_history(self, req: HistoryRequest): <NEW_LINE> <INDENT> return self.rest_api.query_history(req) <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> self.rest_api.stop() <NEW_LINE> self.trade_ws_api.stop() <NEW_LINE> self.market_ws_api.stop() <NEW_LINE> <DEDENT> def process_timer_event(self, event: Event): <NEW_LINE> <INDENT> self.count += 1 <NEW_LINE> if self.count < 3: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.query_account() <NEW_LINE> self.query_position() <NEW_LINE> <DEDENT> def init_query(self): <NEW_LINE> <INDENT> self.count = 0 <NEW_LINE> self.event_engine.register(EVENT_TIMER, self.process_timer_event) | VN Trader Gateway for Huobif connection. | 62598fa7d7e4931a7ef3bfaa |
class OfficialMovable(BaseModel): <NEW_LINE> <INDENT> pass | Public official movable property | 62598fa74527f215b58e9df1 |
class IllegalOpcode(Exception): <NEW_LINE> <INDENT> def __init__(self, opcode=None): <NEW_LINE> <INDENT> self.msg = "Illegal Opcode" <NEW_LINE> if opcode: <NEW_LINE> <INDENT> self.msg += ": " + str(opcode) <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return repr(self.msg) | Catch illegal opcodes | 62598fa7baa26c4b54d4f1bf |
class TagSitemap(Sitemap): <NEW_LINE> <INDENT> def changefreq(self, obj): <NEW_LINE> <INDENT> if obj.touched > timezone.now()-timedelta(hours=1): <NEW_LINE> <INDENT> return "hourly" <NEW_LINE> <DEDENT> if obj.touched > timezone.now()-timedelta(days=1): <NEW_LINE> <INDENT> return "daily" <NEW_LINE> <DEDENT> if obj.touched > timezone.now()-timedelta(days=7): <NEW_LINE> <INDENT> return "weekly" <NEW_LINE> <DEDENT> return "monthly" <NEW_LINE> <DEDENT> def priority(self, obj): <NEW_LINE> <INDENT> posts_per_tag = obj.posts().count() <NEW_LINE> total_posts = 100 <NEW_LINE> priority = float(posts_per_tag) / float(total_posts) <NEW_LINE> return priority <NEW_LINE> <DEDENT> def items(self): <NEW_LINE> <INDENT> return Tag.objects.all() <NEW_LINE> <DEDENT> def lastmod(self, obj): <NEW_LINE> <INDENT> return obj.touched | SiteMap for Tags | 62598fa71f5feb6acb162b30 |
class ExternalMediaOutlet(models.Model): <NEW_LINE> <INDENT> name = models.CharField(_('Name'), max_length=255) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return u'%s' % self.name <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = _('External media outlet') <NEW_LINE> verbose_name_plural = _('External media outlets') <NEW_LINE> ordering = ('name', ) | An instance of this class is an external media outlet.
'__str__' Returns the name.
'class Meta' Sets the description model (singular and plural) and defines ordering of data by name. | 62598fa7a8370b77170f02ea |
class Config(object): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> config_file = kwargs.get('config_file', '/etc/tribe.json') <NEW_LINE> self._config = self._get_config(config_file) <NEW_LINE> <DEDENT> def _get_config(self, config_file): <NEW_LINE> <INDENT> return json.load(open(config_file)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def connection_tuple(self): <NEW_LINE> <INDENT> hosts = self._config.get('etcd_hosts') <NEW_LINE> port = self._config.get('etcd_port', 4001) <NEW_LINE> return tuple([tuple([host, port]) for host in hosts]) <NEW_LINE> <DEDENT> @property <NEW_LINE> def etcd_path(self): <NEW_LINE> <INDENT> return self._config.get('etcd_prefix', '/tribe/nodes') <NEW_LINE> <DEDENT> @property <NEW_LINE> def ping_ttl(self): <NEW_LINE> <INDENT> return self._config.get('ping_ttl', 10) <NEW_LINE> <DEDENT> @property <NEW_LINE> def aliases(self): <NEW_LINE> <INDENT> return self._config.get('aliases', []) <NEW_LINE> <DEDENT> @property <NEW_LINE> def interface(self): <NEW_LINE> <INDENT> return self._config.get('interface', 'eth0') | A class which handles the configuration of tribe. | 62598fa7b7558d589546353e |
class BasePlugin(object): <NEW_LINE> <INDENT> help_text = "Somebody didn't give their plugin any help text. For shame." | The root Plugin object.
Provides all plugins with a default help text. | 62598fa7627d3e7fe0e06dba |
class InvalidFilterValue(JSONAPIParameterException): <NEW_LINE> <INDENT> status_code = http.BAD_REQUEST <NEW_LINE> def __init__(self, detail=None, value=None, field_type=None): <NEW_LINE> <INDENT> if not detail: <NEW_LINE> <INDENT> detail = "Value '{0}' is not valid".format(value) <NEW_LINE> if field_type: <NEW_LINE> <INDENT> detail += ' for a filter on type {0}'.format( field_type ) <NEW_LINE> <DEDENT> detail += '.' <NEW_LINE> <DEDENT> super(InvalidFilterValue, self).__init__(detail=detail, parameter='filter') | Raised when client passes an invalid value to a query param filter. | 62598fa77d847024c075c2d3 |
class GenerateFilesAction(SystemBuildahAction): <NEW_LINE> <INDENT> def _create_manifest(self, namespace, parser): <NEW_LINE> <INDENT> manifest = { "version": "1.0", "defaultValues": {}, } <NEW_LINE> for item in namespace.default: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> k, v = item.split('=') <NEW_LINE> manifest['defaultValues'][k] = v <NEW_LINE> <DEDENT> except ValueError as error: <NEW_LINE> <INDENT> parser._print_message( '{} not in a=b format. Skipping...'.format(item)) <NEW_LINE> <DEDENT> <DEDENT> return manifest <NEW_LINE> <DEDENT> def _render_service_template(self, namespace): <NEW_LINE> <INDENT> loader = jinja2.PackageLoader('system_buildah') <NEW_LINE> return loader.load( jinja2.Environment(), 'service.template.j2').render( description=namespace.description) <NEW_LINE> <DEDENT> def _render_init_template(self, namespace): <NEW_LINE> <INDENT> loader = jinja2.PackageLoader('system_buildah') <NEW_LINE> return loader.load( jinja2.Environment(), 'init.sh.j2').render() <NEW_LINE> <DEDENT> def _generate_ocitools_command(self, namespace, parser): <NEW_LINE> <INDENT> ocitools_cmd = ['ocitools', 'generate', "--read-only"] <NEW_LINE> if namespace.config: <NEW_LINE> <INDENT> for item in namespace.config.split(' '): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> item.index('=') <NEW_LINE> ocitools_cmd = ocitools_cmd + item.split('=') <NEW_LINE> <DEDENT> except ValueError as error: <NEW_LINE> <INDENT> parser._print_message( '{} not in a=b format. Skipping...'.format(item)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return ocitools_cmd <NEW_LINE> <DEDENT> def run(self, parser, namespace, values, dest, option_string=None): <NEW_LINE> <INDENT> output = util.mkdir(values) <NEW_LINE> manifest_struct = self._create_manifest(namespace, parser) <NEW_LINE> manifest_out = os.path.sep.join([output, 'manifest.json']) <NEW_LINE> with open(manifest_out, 'w') as manifest: <NEW_LINE> <INDENT> json.dump(manifest_struct, manifest, indent=8) <NEW_LINE> <DEDENT> rendered = self._render_service_template(namespace) <NEW_LINE> service_out = os.path.sep.join([output, 'service.template']) <NEW_LINE> with open(service_out, 'w') as service: <NEW_LINE> <INDENT> service.write(rendered) <NEW_LINE> <DEDENT> rendered_init = self._render_init_template(namespace) <NEW_LINE> init_out = os.path.sep.join([output, 'init.sh']) <NEW_LINE> with open(init_out, 'w') as init: <NEW_LINE> <INDENT> init.write(rendered_init) <NEW_LINE> <DEDENT> temp_dir = tempfile.mkdtemp() <NEW_LINE> ocitools_cmd = self._generate_ocitools_command(namespace, parser) <NEW_LINE> with util.pushd(temp_dir): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> subprocess.check_call(ocitools_cmd) <NEW_LINE> config_out = os.path.sep.join([output, 'config.json.template']) <NEW_LINE> try: <NEW_LINE> <INDENT> with open('config.json', 'r') as config_file: <NEW_LINE> <INDENT> configuration = json.load(config_file) <NEW_LINE> configuration['process']['terminal'] = False <NEW_LINE> <DEDENT> with open(config_out, 'w') as dest: <NEW_LINE> <INDENT> json.dump( configuration, dest, indent=8, sort_keys=True) <NEW_LINE> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> os.unlink('config.json') <NEW_LINE> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> shutil.rmtree(temp_dir) | Creates new system image files. | 62598fa721bff66bcd722b75 |
class Scroll(Transition): <NEW_LINE> <INDENT> UP, DOWN, LEFT, RIGHT = range(4) <NEW_LINE> def __init__(self, fromRenderer, toRenderer, dir=UP, duration=8): <NEW_LINE> <INDENT> self.dir = dir <NEW_LINE> Transition.__init__(self, fromRenderer, toRenderer, duration) <NEW_LINE> <DEDENT> def tween(self, rwdc, fromFrame, toFrame): <NEW_LINE> <INDENT> if self.dir == self.UP: <NEW_LINE> <INDENT> shift = self.frameNum * 8 / self.duration <NEW_LINE> return ''.join([ chr(0xFF & ((ord(a) >> shift) | (ord(b) << (8-shift)))) for a, b in zip(fromFrame, toFrame) ]) <NEW_LINE> <DEDENT> if self.dir == self.DOWN: <NEW_LINE> <INDENT> shift = self.frameNum * 8 / self.duration <NEW_LINE> return ''.join([ chr(0xFF & ((ord(a) << shift) | (ord(b) >> (8-shift)))) for a, b in zip(fromFrame, toFrame) ]) <NEW_LINE> <DEDENT> if self.dir == self.LEFT: <NEW_LINE> <INDENT> shift = self.frameNum * len(toFrame) / self.duration <NEW_LINE> return (fromFrame + toFrame)[shift:shift+len(toFrame)] <NEW_LINE> <DEDENT> if self.dir == self.RIGHT: <NEW_LINE> <INDENT> shift = len(toFrame) - self.frameNum * len(toFrame) / self.duration <NEW_LINE> return (toFrame + fromFrame)[shift:shift+len(toFrame)] | Vertical/horizontal scrolling transition | 62598fa78c0ade5d55dc3618 |
class OleRecordBase(object): <NEW_LINE> <INDENT> TYPE = None <NEW_LINE> MAX_SIZE = None <NEW_LINE> SIZE = None <NEW_LINE> def __init__(self, type, size, more_data, pos, data): <NEW_LINE> <INDENT> if self.TYPE is not None and type != self.TYPE: <NEW_LINE> <INDENT> raise ValueError('Wrong subclass {0} for type {1}' .format(self.__class__.__name__, type)) <NEW_LINE> <DEDENT> self.type = type <NEW_LINE> if self.SIZE is not None and size != self.SIZE: <NEW_LINE> <INDENT> raise ValueError('Wrong size {0} for record type {1}' .format(size, type)) <NEW_LINE> <DEDENT> elif self.MAX_SIZE is not None and size > self.MAX_SIZE: <NEW_LINE> <INDENT> raise ValueError('Wrong size: {0} > MAX_SIZE for record type {1}' .format(size, type)) <NEW_LINE> <DEDENT> self.size = size <NEW_LINE> self.pos = pos <NEW_LINE> self.data = data <NEW_LINE> self.finish_constructing(more_data) <NEW_LINE> <DEDENT> def finish_constructing(self, more_data): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def read_some_more(self, stream): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def _type_str(self): <NEW_LINE> <INDENT> return '{0} type {1}'.format(self.__class__.__name__, self.type) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '[' + self._type_str() + ' (size {0} from {1})]'.format(self.size, self.pos) | a record found in an OleRecordStream
always has a type and a size, also pos and data | 62598fa701c39578d7f12c8f |
class AllowAny(BasePermission): <NEW_LINE> <INDENT> def has_permission(self, request, view): <NEW_LINE> <INDENT> return True | Allows everybody to access the view. | 62598fa7090684286d593663 |
class ArLLACoords(Ar3DPoint): <NEW_LINE> <INDENT> thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> def __init__(self, *args): <NEW_LINE> <INDENT> this = _AriaPy.new_ArLLACoords(*args) <NEW_LINE> try: self.this.append(this) <NEW_LINE> except: self.this = this <NEW_LINE> <DEDENT> def LLA2ECEF(self): <NEW_LINE> <INDENT> return _AriaPy.ArLLACoords_LLA2ECEF(self) <NEW_LINE> <DEDENT> def getLatitude(self): <NEW_LINE> <INDENT> return _AriaPy.ArLLACoords_getLatitude(self) <NEW_LINE> <DEDENT> def getLongitude(self): <NEW_LINE> <INDENT> return _AriaPy.ArLLACoords_getLongitude(self) <NEW_LINE> <DEDENT> def getAltitude(self): <NEW_LINE> <INDENT> return _AriaPy.ArLLACoords_getAltitude(self) <NEW_LINE> <DEDENT> def setLatitude(self, *args): <NEW_LINE> <INDENT> return _AriaPy.ArLLACoords_setLatitude(self, *args) <NEW_LINE> <DEDENT> def setLongitude(self, *args): <NEW_LINE> <INDENT> return _AriaPy.ArLLACoords_setLongitude(self, *args) <NEW_LINE> <DEDENT> def setAltitude(self, *args): <NEW_LINE> <INDENT> return _AriaPy.ArLLACoords_setAltitude(self, *args) <NEW_LINE> <DEDENT> __swig_destroy__ = _AriaPy.delete_ArLLACoords <NEW_LINE> __del__ = lambda self : None; | Proxy of C++ ArLLACoords class | 62598fa7498bea3a75a57a2c |
class Mcl(AutotoolsPackage): <NEW_LINE> <INDENT> homepage = "https://www.micans.org/mcl/index.html" <NEW_LINE> url = "https://www.micans.org/mcl/src/mcl-14-137.tar.gz" <NEW_LINE> version('14-137', 'bc8740456cf51019d0a9ac5eba665bb5') | The MCL algorithm is short for the Markov Cluster Algorithm, a fast
and scalable unsupervised cluster algorithm for graphs (also known
as networks) based on simulation of (stochastic) flow in graphs. | 62598fa7eab8aa0e5d30bc9a |
class Loader(object): <NEW_LINE> <INDENT> def __init__(self, config_path=None): <NEW_LINE> <INDENT> config_path = config_path or CONF.api_paste_config <NEW_LINE> self.config_path = CONF.find_file(config_path) <NEW_LINE> if not self.config_path: <NEW_LINE> <INDENT> raise exception.ConfigNotFound(path=config_path) <NEW_LINE> <DEDENT> <DEDENT> def load_app(self, name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return deploy.loadapp("config:%s" % self.config_path, name=name) <NEW_LINE> <DEDENT> except LookupError as err: <NEW_LINE> <INDENT> LOG.error(err) <NEW_LINE> raise exception.PasteAppNotFound(name=name, path=self.config_path) | Used to load WSGI applications from paste configurations. | 62598fa724f1403a9268583b |
class SQLQueryBuilder(object): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def create_operation(model, fieldname, operator, argument, relation=None): <NEW_LINE> <INDENT> opfunc = OPERATORS[operator] <NEW_LINE> field = getattr(model, relation or fieldname) <NEW_LINE> return opfunc(field, argument) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def create_filters(model, filters): <NEW_LINE> <INDENT> nfilters = [] <NEW_LINE> for f in filters: <NEW_LINE> <INDENT> fname = f.field <NEW_LINE> relation = None <NEW_LINE> if '.' in fname: <NEW_LINE> <INDENT> relation, fname = fname.split('.') <NEW_LINE> <DEDENT> param = SQLQueryBuilder.create_operation(model, fname, f.operator, f.argument, relation) <NEW_LINE> nfilters.append(param) <NEW_LINE> <DEDENT> return nfilters <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def create_query(model, query_params): <NEW_LINE> <INDENT> if not isinstance(query_params, QueryParameters): <NEW_LINE> <INDENT> raise ValueError("query_params must be an instance of " "QueryParameters") <NEW_LINE> <DEDENT> query = model.query <NEW_LINE> filters = SQLQueryBuilder.create_filters(model, query_params.filters) <NEW_LINE> query = query.filter(and_(*filters)) <NEW_LINE> for s in query_params.sort: <NEW_LINE> <INDENT> field = getattr(model, s.field) <NEW_LINE> direction = SORT_ORDER[s.direction](field) <NEW_LINE> query = query.order_by(direction()) <NEW_LINE> <DEDENT> return query | Provides static functions for building SQLAlchemy query object based on a
:class:`QueryParameters` instance. | 62598fa7e1aae11d1e7ce7ab |
class MillConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): <NEW_LINE> <INDENT> VERSION = 1 <NEW_LINE> async def async_step_user(self, user_input=None): <NEW_LINE> <INDENT> data_schema = vol.Schema( { vol.Required(CONNECTION_TYPE, default=CLOUD): vol.In( ( CLOUD, LOCAL, ) ) } ) <NEW_LINE> if user_input is None: <NEW_LINE> <INDENT> return self.async_show_form( step_id="user", data_schema=data_schema, ) <NEW_LINE> <DEDENT> if user_input[CONNECTION_TYPE] == LOCAL: <NEW_LINE> <INDENT> return await self.async_step_local() <NEW_LINE> <DEDENT> return await self.async_step_cloud() <NEW_LINE> <DEDENT> async def async_step_local(self, user_input=None): <NEW_LINE> <INDENT> data_schema = vol.Schema({vol.Required(CONF_IP_ADDRESS): str}) <NEW_LINE> if user_input is None: <NEW_LINE> <INDENT> return self.async_show_form( step_id="local", data_schema=data_schema, ) <NEW_LINE> <DEDENT> mill_data_connection = MillLocal( user_input[CONF_IP_ADDRESS], websession=async_get_clientsession(self.hass), ) <NEW_LINE> await self.async_set_unique_id(mill_data_connection.device_ip) <NEW_LINE> self._abort_if_unique_id_configured() <NEW_LINE> if not await mill_data_connection.connect(): <NEW_LINE> <INDENT> return self.async_show_form( step_id="local", data_schema=data_schema, errors={"base": "cannot_connect"}, ) <NEW_LINE> <DEDENT> return self.async_create_entry( title=user_input[CONF_IP_ADDRESS], data={ CONF_IP_ADDRESS: user_input[CONF_IP_ADDRESS], CONNECTION_TYPE: LOCAL, }, ) <NEW_LINE> <DEDENT> async def async_step_cloud(self, user_input=None): <NEW_LINE> <INDENT> data_schema = vol.Schema( {vol.Required(CONF_USERNAME): str, vol.Required(CONF_PASSWORD): str} ) <NEW_LINE> if user_input is None: <NEW_LINE> <INDENT> return self.async_show_form( step_id="cloud", data_schema=data_schema, errors={}, ) <NEW_LINE> <DEDENT> username = user_input[CONF_USERNAME].replace(" ", "") <NEW_LINE> password = user_input[CONF_PASSWORD].replace(" ", "") <NEW_LINE> mill_data_connection = Mill( username, password, websession=async_get_clientsession(self.hass), ) <NEW_LINE> errors = {} <NEW_LINE> if not await mill_data_connection.connect(): <NEW_LINE> <INDENT> errors["base"] = "cannot_connect" <NEW_LINE> return self.async_show_form( step_id="cloud", data_schema=data_schema, errors=errors, ) <NEW_LINE> <DEDENT> unique_id = username <NEW_LINE> await self.async_set_unique_id(unique_id) <NEW_LINE> self._abort_if_unique_id_configured() <NEW_LINE> return self.async_create_entry( title=unique_id, data={ CONF_USERNAME: username, CONF_PASSWORD: password, CONNECTION_TYPE: CLOUD, }, ) | Handle a config flow for Mill integration. | 62598fa7656771135c489591 |
class Overlay(FSLCommand): <NEW_LINE> <INDENT> _cmd = 'overlay' <NEW_LINE> input_spec = OverlayInputSpec <NEW_LINE> output_spec = OverlayOutputSpec <NEW_LINE> def _format_arg(self, name, spec, value): <NEW_LINE> <INDENT> if name == 'transparency': <NEW_LINE> <INDENT> if value: <NEW_LINE> <INDENT> return '1' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return '0' <NEW_LINE> <DEDENT> <DEDENT> if name == 'out_type': <NEW_LINE> <INDENT> if value == 'float': <NEW_LINE> <INDENT> return '0' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return '1' <NEW_LINE> <DEDENT> <DEDENT> if name == 'show_negative_stats': <NEW_LINE> <INDENT> return '%s %.2f %.2f' % (self.inputs.stat_image, self.inputs.stat_thresh[0] * -1, self.inputs.stat_thresh[1] * -1) <NEW_LINE> <DEDENT> return super(Overlay, self)._format_arg(name, spec, value) <NEW_LINE> <DEDENT> def _list_outputs(self): <NEW_LINE> <INDENT> outputs = self._outputs().get() <NEW_LINE> out_file = self.inputs.out_file <NEW_LINE> if not isdefined(out_file): <NEW_LINE> <INDENT> if isdefined(self.inputs.stat_image2) and ( not isdefined(self.inputs.show_negative_stats) or not self.inputs.show_negative_stats): <NEW_LINE> <INDENT> stem = "%s_and_%s" % ( split_filename(self.inputs.stat_image)[1], split_filename(self.inputs.stat_image2)[1]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> stem = split_filename(self.inputs.stat_image)[1] <NEW_LINE> <DEDENT> out_file = self._gen_fname(stem, suffix='_overlay') <NEW_LINE> <DEDENT> outputs['out_file'] = os.path.abspath(out_file) <NEW_LINE> return outputs <NEW_LINE> <DEDENT> def _gen_filename(self, name): <NEW_LINE> <INDENT> if name == 'out_file': <NEW_LINE> <INDENT> return self._list_outputs()['out_file'] <NEW_LINE> <DEDENT> return None | Use FSL's overlay command to combine background and statistical images
into one volume
Examples
--------
>>> from nipype.interfaces import fsl
>>> combine = fsl.Overlay()
>>> combine.inputs.background_image = 'mean_func.nii.gz'
>>> combine.inputs.auto_thresh_bg = True
>>> combine.inputs.stat_image = 'zstat1.nii.gz'
>>> combine.inputs.stat_thresh = (3.5, 10)
>>> combine.inputs.show_negative_stats = True
>>> res = combine.run() #doctest: +SKIP | 62598fa7b7558d589546353f |
class RequestError(httplib.HTTPException): <NEW_LINE> <INDENT> pass | An HTTPException thrown when the server reports an error in the
client's request.
This exception corresponds to the HTTP status code 400. | 62598fa7f548e778e596b4b4 |
class EveryTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.crontab = CronTab(tabfile=os.path.join(TEST_DIR, 'data', 'test.tab')) <NEW_LINE> <DEDENT> def test_00_minutes(self): <NEW_LINE> <INDENT> for job in self.crontab: <NEW_LINE> <INDENT> job.every(3).minutes() <NEW_LINE> self.assertEqual(job.slices.clean_render(), '*/3 * * * *') <NEW_LINE> job.minutes.every(5) <NEW_LINE> self.assertEqual(job.slices.clean_render(), '*/5 * * * *') <NEW_LINE> <DEDENT> <DEDENT> def test_01_hours(self): <NEW_LINE> <INDENT> for job in self.crontab: <NEW_LINE> <INDENT> job.every(3).hours() <NEW_LINE> self.assertEqual(job.slices.clean_render(), '0 */3 * * *') <NEW_LINE> <DEDENT> <DEDENT> def test_02_dom(self): <NEW_LINE> <INDENT> for job in self.crontab: <NEW_LINE> <INDENT> job.every(3).dom() <NEW_LINE> self.assertEqual(job.slices.clean_render(), '0 0 */3 * *') <NEW_LINE> <DEDENT> <DEDENT> def test_03_single(self): <NEW_LINE> <INDENT> for job in self.crontab: <NEW_LINE> <INDENT> job.every().hour() <NEW_LINE> self.assertEqual(job.slices.clean_render(), '0 * * * *') <NEW_LINE> <DEDENT> <DEDENT> def test_04_month(self): <NEW_LINE> <INDENT> for job in self.crontab: <NEW_LINE> <INDENT> job.every(3).months() <NEW_LINE> self.assertEqual(job.slices.clean_render(), '0 0 1 */3 *') <NEW_LINE> <DEDENT> <DEDENT> def test_05_dow(self): <NEW_LINE> <INDENT> for job in self.crontab: <NEW_LINE> <INDENT> job.every(3).dow() <NEW_LINE> self.assertEqual(job.slices.clean_render(), '0 0 * * */3') <NEW_LINE> <DEDENT> <DEDENT> def test_06_year(self): <NEW_LINE> <INDENT> for job in self.crontab: <NEW_LINE> <INDENT> job.every().year() <NEW_LINE> self.assertEqual(job.slices.render(), '@yearly') <NEW_LINE> self.assertEqual(job.slices.clean_render(), '0 0 1 1 *') <NEW_LINE> self.assertRaises(ValueError, job.every(2).year) <NEW_LINE> <DEDENT> <DEDENT> def test_07_reboot(self): <NEW_LINE> <INDENT> for job in self.crontab: <NEW_LINE> <INDENT> job.every_reboot() <NEW_LINE> self.assertEqual(job.slices.render(), '@reboot') <NEW_LINE> self.assertEqual(job.slices.clean_render(), '* * * * *') <NEW_LINE> <DEDENT> <DEDENT> def test_08_newitem(self): <NEW_LINE> <INDENT> job = self.crontab.new(command='hourly') <NEW_LINE> job.every().hour() <NEW_LINE> self.assertEqual(job.slices.render(), '@hourly') <NEW_LINE> job = self.crontab.new(command='firstly') <NEW_LINE> job.hours.every(2) <NEW_LINE> self.assertEqual(job.slices.render(), '* */2 * * *') | Test basic functionality of crontab. | 62598fa7379a373c97d98f21 |
class Solution: <NEW_LINE> <INDENT> def minimumSize(self, nums, s): <NEW_LINE> <INDENT> if not nums: <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> prefix_sum = self.get_prefix_sum(nums) <NEW_LINE> min_size = float('inf') <NEW_LINE> for start in range(len(nums)): <NEW_LINE> <INDENT> for end in range(start, len(nums)): <NEW_LINE> <INDENT> if prefix_sum[end + 1] - prefix_sum[start] >= s: <NEW_LINE> <INDENT> min_size = min(min_size, end + 1 - start) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if min_size == float('inf'): <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> return min_size <NEW_LINE> <DEDENT> def get_prefix_sum(self, nums): <NEW_LINE> <INDENT> prefix_sum = [0] <NEW_LINE> for num in nums: <NEW_LINE> <INDENT> prefix_sum.append(prefix_sum[-1] + num) <NEW_LINE> <DEDENT> return prefix_sum | @param nums: an array of integers
@param s: An integer
@return: an integer representing the minimum size of subarray
前缀和:Time O(n^2) Space O(n) 超时 | 62598fa763b5f9789fe85075 |
class SquareError(ErrorMetric): <NEW_LINE> <INDENT> def distance(self, a, b): <NEW_LINE> <INDENT> return (a - b) ** 2 | Squared error of two tensors. | 62598fa77047854f4633f2e9 |
class IsAdmin(BaseRule): <NEW_LINE> <INDENT> def __init__(self, is_admin: bool): <NEW_LINE> <INDENT> self.is_admin: bool = is_admin <NEW_LINE> <DEDENT> async def check(self, message: types.Message): <NEW_LINE> <INDENT> status = USERS[message.from_id] <NEW_LINE> if not self.is_admin and status != "admin": <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif not self.is_admin and status == "admin": <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> elif self.is_admin and status == "admin": <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif self.is_admin and status != "admin": <NEW_LINE> <INDENT> return False | Check admin rights of user. | 62598fa73539df3088ecc1c4 |
class scannerClose_result(object): <NEW_LINE> <INDENT> def __init__(self, io=None, ia=None,): <NEW_LINE> <INDENT> self.io = io <NEW_LINE> self.ia = ia <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 == 1: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.io = IOError() <NEW_LINE> self.io.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 2: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.ia = IllegalArgument() <NEW_LINE> self.ia.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('scannerClose_result') <NEW_LINE> if self.io is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('io', TType.STRUCT, 1) <NEW_LINE> self.io.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.ia is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('ia', TType.STRUCT, 2) <NEW_LINE> self.ia.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:
- io
- ia | 62598fa7dd821e528d6d8e45 |
class Session(db.Model): <NEW_LINE> <INDENT> id = db.Column(db.Unicode(255), primary_key=True) <NEW_LINE> election_id = db.Column(db.Integer, db.ForeignKey('election.id')) <NEW_LINE> question_number = db.Column(db.Integer) <NEW_LINE> election = db.relationship('Election', backref=db.backref('sessions', lazy='dynamic', order_by=question_number)) <NEW_LINE> status = db.Column(db.Unicode(128)) <NEW_LINE> public_key = db.Column(db.UnicodeText) <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> for key, value in kwargs.items(): <NEW_LINE> <INDENT> setattr(self, key, value) <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<Session %r>' % self.title <NEW_LINE> <DEDENT> def to_dict(self, full=False): <NEW_LINE> <INDENT> return { 'id': self.id, 'election_id': self.election_id, 'status': self.status, 'public_key': self.public_key, 'question_number': self.question_number } | Refers vfork session, with its own public key and protinfo | 62598fa738b623060ffa8fa7 |
class InflectionTable(OrderedDotDict): <NEW_LINE> <INDENT> def __str__(self): <NEW_LINE> <INDENT> return self.format_values() | A table of inflected forms of a word.
| 62598fa745492302aabfc3e0 |
class LabelInfoFormatError(Error): <NEW_LINE> <INDENT> pass | An error encountered if the label format is not correct. | 62598fa7925a0f43d25e7f4e |
class Trial: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._elements = {} <NEW_LINE> del self._elements['_elements'] <NEW_LINE> <DEDENT> def __setattr__(self, name: str, value): <NEW_LINE> <INDENT> super.__setattr__(self, name, value) <NEW_LINE> self._elements[name] = value <NEW_LINE> <DEDENT> def __eq__(self, other: dict or 'Trial'): <NEW_LINE> <INDENT> if isinstance(other, Trial): <NEW_LINE> <INDENT> return self._elements == other._elements <NEW_LINE> <DEDENT> elif isinstance(other, dict): <NEW_LINE> <INDENT> return self._elements == other <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self._elements) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> o = "{" <NEW_LINE> for k, v in self._elements.items(): <NEW_LINE> <INDENT> if k == '_elements': <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> o += f"{k}: {v}, " <NEW_LINE> <DEDENT> o = o[:-2] <NEW_LINE> o += "}" <NEW_LINE> return o <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> return self._elements <NEW_LINE> <DEDENT> def to_numpy(self): <NEW_LINE> <INDENT> return np.array([v for k, v in self._elements.items()]) | this class is only accessed by TrialGenerator.
| 62598fa76e29344779b0056c |
class TestV1EndpointAddress(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 testV1EndpointAddress(self): <NEW_LINE> <INDENT> pass | V1EndpointAddress unit test stubs | 62598fa74e4d562566372335 |
class ObjDict(Dictomatic): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def wrap(cls, data, decode=True, start=True): <NEW_LINE> <INDENT> return wrap_obj(data, cls, decode, start) <NEW_LINE> <DEDENT> def __getattr__(self, name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self[name] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise AttributeError( "'nudge.json.ObjDict' has no attribute %s" % name ) | Simple dictionary that behaves like an object dict that doesn't hide
errors, or do any dehumping stuff. | 62598fa7435de62698e9bd05 |
class Corrector(Plugin): <NEW_LINE> <INDENT> REGEX = re.compile(r"(.*)") <NEW_LINE> REGEX_RGX = re.compile(r"s/([^/]+)\/([^/]+)/?.*") <NEW_LINE> def __init__(self, bot): <NEW_LINE> <INDENT> super().__init__(bot) <NEW_LINE> self.last_words = {} <NEW_LINE> <DEDENT> def do_command(self, bot, message, matched_groups=None, sudo=False): <NEW_LINE> <INDENT> results = '' <NEW_LINE> author = message.author <NEW_LINE> regres = Corrector.REGEX_RGX.fullmatch(matched_groups[0]) <NEW_LINE> if regres is not None: <NEW_LINE> <INDENT> regres = regres.groups() <NEW_LINE> if author in self.last_words: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> regex = re.compile(regres[0]) <NEW_LINE> replace = regres[1] if len(regres) > 1 else '' <NEW_LINE> corrected = re.sub(regex, replace, self.last_words[author]) <NEW_LINE> if corrected != self.last_words[author]: <NEW_LINE> <INDENT> results = corrected <NEW_LINE> results += ' \t«««« corrected ' + author + ' words' <NEW_LINE> self.last_words[author] = corrected <NEW_LINE> <DEDENT> <DEDENT> except re.error: <NEW_LINE> <INDENT> results += "from the dark side, you're REGEX comes.\n" <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.last_words[author] = message.all <NEW_LINE> <DEDENT> return results <NEW_LINE> <DEDENT> @property <NEW_LINE> def help(self): <NEW_LINE> <INDENT> return """CORRECTOR: apply regex as s/// format to your last sentence. Useless but fun.""" <NEW_LINE> <DEDENT> @property <NEW_LINE> def only_on_explicit_dest(self): <NEW_LINE> <INDENT> return False | Simple Plugin application.
Repeat last sentence of user that correct it by using a regex.
example:
lucas| hellp
lucas| s/p/o
bot | lucas would say: hello | 62598fa7435de62698e9bd06 |
class TestDecimalToBinaryIP(unittest.TestCase): <NEW_LINE> <INDENT> def test_decimal_to_binary_ip(self): <NEW_LINE> <INDENT> self.assertEqual("00000000.00000000.00000000.00000000", decimal_to_binary_ip("0.0.0.0")) <NEW_LINE> self.assertEqual("11111111.11111111.11111111.11111111", decimal_to_binary_ip("255.255.255.255")) <NEW_LINE> self.assertEqual("11000000.10101000.00000000.00000001", decimal_to_binary_ip("192.168.0.1")) | Test for the file decimal_to_binary_ip.py
Arguments:
unittest {[type]} -- [description] | 62598fa7f9cc0f698b1c5251 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.