code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class ChoicesSC14(BasicName): <NEW_LINE> <INDENT> pass
Represents MoV Source options
62598fa526068e7796d4c826
class Hash(Builtin): <NEW_LINE> <INDENT> rules = { 'Hash[expr_]': 'Hash[expr, "MD5"]', } <NEW_LINE> attributes = ('Protected', 'ReadProtected') <NEW_LINE> _supported_hashes = { 'Adler32': lambda: _ZLibHash(zlib.adler32), 'CRC32': lambda: _ZLibHash(zlib.crc32), 'MD5': hashlib.md5, 'SHA': hashlib.sha1, 'SHA224': hashlib.sha224, 'SHA256': hashlib.sha256, 'SHA384': hashlib.sha384, 'SHA512': hashlib.sha512, } <NEW_LINE> @staticmethod <NEW_LINE> def compute(user_hash, py_hashtype): <NEW_LINE> <INDENT> hash_func = Hash._supported_hashes.get(py_hashtype) <NEW_LINE> if hash_func is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> h = hash_func() <NEW_LINE> user_hash(h.update) <NEW_LINE> return from_python(int(h.hexdigest(), 16)) <NEW_LINE> <DEDENT> def apply(self, expr, hashtype, evaluation): <NEW_LINE> <INDENT> return Hash.compute(expr.user_hash, hashtype.get_string_value())
<dl> <dt>'Hash[$expr$]' <dd>returns an integer hash for the given $expr$. <dt>'Hash[$expr$, $type$]' <dd>returns an integer hash of the specified $type$ for the given $expr$.</dd> <dd>The types supported are "MD5", "Adler32", "CRC32", "SHA", "SHA224", "SHA256", "SHA384", and "SHA512".</dd> </dl> > Hash["The Adventures of Huckleberry Finn"] = 213425047836523694663619736686226550816 > Hash["The Adventures of Huckleberry Finn", "SHA256"] = 95092649594590384288057183408609254918934351811669818342876362244564858646638 > Hash[1/3] = 56073172797010645108327809727054836008 > Hash[{a, b, {c, {d, e, f}}}] = 135682164776235407777080772547528225284 > Hash[SomeHead[3.1415]] = 58042316473471877315442015469706095084 >> Hash[{a, b, c}, "xyzstr"] = Hash[{a, b, c}, xyzstr]
62598fa5e5267d203ee6b7db
class FaxList(ListResource): <NEW_LINE> <INDENT> def __init__(self, version): <NEW_LINE> <INDENT> super(FaxList, self).__init__(version) <NEW_LINE> self._solution = {} <NEW_LINE> self._uri = '/Faxes'.format(**self._solution) <NEW_LINE> <DEDENT> def stream(self, from_=values.unset, to=values.unset, date_created_on_or_before=values.unset, date_created_after=values.unset, limit=None, page_size=None): <NEW_LINE> <INDENT> limits = self._version.read_limits(limit, page_size) <NEW_LINE> page = self.page( from_=from_, to=to, date_created_on_or_before=date_created_on_or_before, date_created_after=date_created_after, page_size=limits['page_size'], ) <NEW_LINE> return self._version.stream(page, limits['limit'], limits['page_limit']) <NEW_LINE> <DEDENT> def list(self, from_=values.unset, to=values.unset, date_created_on_or_before=values.unset, date_created_after=values.unset, limit=None, page_size=None): <NEW_LINE> <INDENT> return list(self.stream( from_=from_, to=to, date_created_on_or_before=date_created_on_or_before, date_created_after=date_created_after, limit=limit, page_size=page_size, )) <NEW_LINE> <DEDENT> def page(self, from_=values.unset, to=values.unset, date_created_on_or_before=values.unset, date_created_after=values.unset, page_token=values.unset, page_number=values.unset, page_size=values.unset): <NEW_LINE> <INDENT> params = values.of({ 'From': from_, 'To': to, 'DateCreatedOnOrBefore': serialize.iso8601_datetime(date_created_on_or_before), 'DateCreatedAfter': serialize.iso8601_datetime(date_created_after), 'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) <NEW_LINE> response = self._version.page( 'GET', self._uri, params=params, ) <NEW_LINE> return FaxPage(self._version, response, self._solution) <NEW_LINE> <DEDENT> def get_page(self, target_url): <NEW_LINE> <INDENT> response = self._version.domain.twilio.request( 'GET', target_url, ) <NEW_LINE> return FaxPage(self._version, response, self._solution) <NEW_LINE> <DEDENT> def create(self, to, media_url, quality=values.unset, status_callback=values.unset, from_=values.unset, sip_auth_username=values.unset, sip_auth_password=values.unset, store_media=values.unset, ttl=values.unset): <NEW_LINE> <INDENT> data = values.of({ 'To': to, 'MediaUrl': media_url, 'Quality': quality, 'StatusCallback': status_callback, 'From': from_, 'SipAuthUsername': sip_auth_username, 'SipAuthPassword': sip_auth_password, 'StoreMedia': store_media, 'Ttl': ttl, }) <NEW_LINE> payload = self._version.create( 'POST', self._uri, data=data, ) <NEW_LINE> return FaxInstance(self._version, payload, ) <NEW_LINE> <DEDENT> def get(self, sid): <NEW_LINE> <INDENT> return FaxContext(self._version, sid=sid, ) <NEW_LINE> <DEDENT> def __call__(self, sid): <NEW_LINE> <INDENT> return FaxContext(self._version, sid=sid, ) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<Twilio.Fax.V1.FaxList>'
PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution.
62598fa5498bea3a75a579f0
class Connector(object): <NEW_LINE> <INDENT> def __init__(self, factory: AbstractFactory): <NEW_LINE> <INDENT> self.protocol = factory.create_protocol() <NEW_LINE> self.port = factory.create_port() <NEW_LINE> self.parse = factory.create_parser() <NEW_LINE> <DEDENT> def read(self, host, path): <NEW_LINE> <INDENT> url = self.protocol + '://' + host + ':' + str(self.port) + path <NEW_LINE> print('Connecting to ', url) <NEW_LINE> return urrlib2.urlopen(url, timeout=2).read()
A client
62598fa5dd821e528d6d8e03
class API(object): <NEW_LINE> <INDENT> def __init__(self,merchant_account,sci_name, subscription,iten_id,amount,currency = "USD", logo=None,notify_url=None,confirm_url=None, return_url=None,return_method=None, cancel_url=None,testmode="OFF",extra_params=None): <NEW_LINE> <INDENT> self.merchant_account = merchant_account
SolidTrustPay API
62598fa55166f23b2e2432a4
class Hub(Location): <NEW_LINE> <INDENT> __tablename__ = 'hub' <NEW_LINE> __mapper_args__ = {'polymorphic_identity': 'hub'} <NEW_LINE> valid_parents = [Company] <NEW_LINE> id = Column(Integer, ForeignKey('location.id', name='hub_loc_fk', ondelete='CASCADE'), primary_key=True)
Hub is a subtype of location
62598fa54a966d76dd5eedb1
class RSADigitalSignature(RSA): <NEW_LINE> <INDENT> def sign(self, message): <NEW_LINE> <INDENT> return self.decrypt(int.from_bytes(message, byteorder='big')) <NEW_LINE> <DEDENT> def verify(self, encrypted_signature, message): <NEW_LINE> <INDENT> signature = b'\x00' + int_to_bytes(self.encrypt(encrypted_signature)) <NEW_LINE> r = re.compile(b'\x00\x01\xff+?\x00.{15}(.{20})', re.DOTALL) <NEW_LINE> m = r.match(signature) <NEW_LINE> if not m: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> hashed = m.group(1) <NEW_LINE> return hashed == unhexlify(sha1(message))
Extends the RSA class coded before with the sign / verify functions.
62598fa5796e427e5384e661
class TestOVO(unittest.TestCase): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> <DEDENT> def test_linear_OVO(self): <NEW_LINE> <INDENT> bin_clf = LSTSVM('linear') <NEW_LINE> ova_clf = OneVsOneClassifier(bin_clf) <NEW_LINE> ova_clf.fit(X, y) <NEW_LINE> pred = ova_clf.predict(X) <NEW_LINE> assert_greater(np.mean(y == pred), 0.96) <NEW_LINE> <DEDENT> def test_RBF_OVO(self): <NEW_LINE> <INDENT> bin_clf = LSTSVM('RBF', 1, 1, 1, 2**-4) <NEW_LINE> ova_clf = OneVsOneClassifier(bin_clf) <NEW_LINE> ova_clf.fit(X, y) <NEW_LINE> pred = ova_clf.predict(X) <NEW_LINE> assert_greater(np.mean(y == pred), 0.97) <NEW_LINE> <DEDENT> def test_rect_OVO(self): <NEW_LINE> <INDENT> bin_clf = LSTSVM('RBF', 0.75, 1, 1, 2**-2) <NEW_LINE> ova_clf = OneVsOneClassifier(bin_clf) <NEW_LINE> ova_clf.fit(X, y) <NEW_LINE> pred = ova_clf.predict(X) <NEW_LINE> assert_greater(np.mean(y == pred), 0.96)
It tests the functionalities of One-vs-One classifier.
62598fa54e4d5625663722f2
class DescribeslowLogStatisticRequest(JDCloudRequest): <NEW_LINE> <INDENT> def __init__(self, parameters, header=None, version="v2"): <NEW_LINE> <INDENT> super(DescribeslowLogStatisticRequest, self).__init__( '/regions/{regionId}/slowLogStatistic', 'GET', header, version) <NEW_LINE> self.parameters = parameters
最近3小时,24小时,3天慢sql情况
62598fa5090684286d593642
class RandomCrop(object): <NEW_LINE> <INDENT> def __init__(self, size, ): <NEW_LINE> <INDENT> if isinstance(size, numbers.Number): <NEW_LINE> <INDENT> self.size = (int(size), int(size)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.size = size <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def get_params(pic, output_size): <NEW_LINE> <INDENT> w, h = pic.shape[0], pic.shape[1] <NEW_LINE> th, tw = output_size <NEW_LINE> i = random.randint(0, w - tw) <NEW_LINE> j = random.randint(0, h - th) <NEW_LINE> return i, j, th, tw <NEW_LINE> <DEDENT> def __call__(self, pic): <NEW_LINE> <INDENT> if not _is_numpy_image(pic): <NEW_LINE> <INDENT> raise TypeError('img should be numpy array. Got {}'.format(type(pic))) <NEW_LINE> <DEDENT> i, j, th, tw = self.get_params(pic, self.size) <NEW_LINE> if len(pic.shape) == 2: <NEW_LINE> <INDENT> return pic[i:i + th, j:j + tw] <NEW_LINE> <DEDENT> elif len(pic.shape) == 3: <NEW_LINE> <INDENT> return pic[i:i + th, j:j + tw, :] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception('image must grey or 3-channels')
Performs a random crop in a given numpy array using only the first two dimensions (width and height)
62598fa54e4d5625663722f3
class UserRegisterSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = User <NEW_LINE> fields = ('id', 'username', 'password', 'name', 'role', ) <NEW_LINE> extra_kwargs = {'password': {'write_only': True}} <NEW_LINE> <DEDENT> def create(self, validated_data): <NEW_LINE> <INDENT> user = User( username=validated_data['username'], name=validated_data['name'], role=validated_data['role'], ) <NEW_LINE> user.set_password(validated_data['password']) <NEW_LINE> user.save() <NEW_LINE> return user
Custom serializer for registration new User-model
62598fa5656771135c489550
class MembershipInfo(colander.Schema): <NEW_LINE> <INDENT> yes_no = ((u'yes', _(u'Yes')), (u'no', _(u'No'))) <NEW_LINE> membership_type = colander.SchemaNode( colander.String(), title=_(u'I want to become a ... ' u'(choose membership type, see C3S SCE statute §5)'), description=_(u'choose the type of membership.'), widget=deform.widget.RadioChoiceWidget( values=( ( u'normal', _(u'FULL member. Full members have to be natural ' u'persons who register at least three works they ' u'created themselves with C3S. This applies to ' u'composers, lyricists and remixers. They get a ' u'vote.')), ( u'investing', _(u'INVESTING member. Investing members can be ' u'natural or legal entities or private companies ' u'that do not register works with C3S. They do ' u'not get a vote, but may counsel.')) ), ), oid='membership_type' ) <NEW_LINE> member_of_colsoc = colander.SchemaNode( colander.String(), title=_( u'Currently, I am a member of (at least) one other ' u'collecting society.'), validator=colander.OneOf([x[0] for x in yes_no]), widget=deform.widget.RadioChoiceWidget(values=yes_no), oid="other_colsoc", ) <NEW_LINE> name_of_colsoc = colander.SchemaNode( colander.String(), title=_(u'If so, which one(s)? Please separate multiple ' u'collecting societies by comma.'), description=_( u'Please tell us which collecting societies ' u'you are a member of. ' u'If more than one, please separate them by comma.'), missing=unicode(''), oid="colsoc_name", )
Basic member information.
62598fa51f037a2d8b9e3fb9
class CounterSampleQueryDetails(Model): <NEW_LINE> <INDENT> _attribute_map = { 'counter_instance_id': {'key': 'counterInstanceId', 'type': 'str'}, 'from_interval': {'key': 'fromInterval', 'type': 'int'}, 'to_interval': {'key': 'toInterval', 'type': 'int'} } <NEW_LINE> def __init__(self, counter_instance_id=None, from_interval=None, to_interval=None): <NEW_LINE> <INDENT> super(CounterSampleQueryDetails, self).__init__() <NEW_LINE> self.counter_instance_id = counter_instance_id <NEW_LINE> self.from_interval = from_interval <NEW_LINE> self.to_interval = to_interval
CounterSampleQueryDetails. :param counter_instance_id: :type counter_instance_id: str :param from_interval: :type from_interval: int :param to_interval: :type to_interval: int
62598fa51f5feb6acb162af0
class Figure (images.Figure): <NEW_LINE> <INDENT> option_spec = images.Figure.option_spec.copy () <NEW_LINE> option_spec.update ( { 'float': partial (multi_choice, image_float_values), } ) <NEW_LINE> required_arguments = 0 <NEW_LINE> optional_arguments = 1 <NEW_LINE> final_argument_whitespace = True <NEW_LINE> figure_count = 0 <NEW_LINE> def run (self): <NEW_LINE> <INDENT> self.options.setdefault ('align', 'center') <NEW_LINE> if not self.arguments: <NEW_LINE> <INDENT> self.arguments.append (broken) <NEW_LINE> self.options.setdefault ('figwidth', '80%') <NEW_LINE> self.options.setdefault ('width', '5%') <NEW_LINE> <DEDENT> res = images.Figure.run (self) <NEW_LINE> figure = res[0] <NEW_LINE> figure.setdefault ('width', 'image') <NEW_LINE> figure['float'] = self.options.get ('float', ('here', 'top', 'bottom', 'page')) <NEW_LINE> Figure.figure_count += 1 <NEW_LINE> target = lox_target (figure, 'figure-%d' % Figure.figure_count) <NEW_LINE> self.state_machine.document.note_implicit_target (target, target) <NEW_LINE> return res
Override standard figure. Allow use of no filename.
62598fa567a9b606de545e9a
class RandomBatchSampler(VideoBatchSampler): <NEW_LINE> <INDENT> def __init__(self, dir_tree, batch_size, sequential=False, labeled=False): <NEW_LINE> <INDENT> self._dir_tree = dir_tree <NEW_LINE> self.batch_size = int(batch_size) <NEW_LINE> <DEDENT> def update_tree(self, dir_tree): <NEW_LINE> <INDENT> self._dir_tree = dir_tree <NEW_LINE> <DEDENT> def _gen_idxs(self): <NEW_LINE> <INDENT> all_idxs = [] <NEW_LINE> for k, v in enumerate(self._dir_tree.values()): <NEW_LINE> <INDENT> len_v = len(v) <NEW_LINE> seq = list(range(len_v)) <NEW_LINE> idxs = [(k, s) for s in seq] <NEW_LINE> all_idxs.extend(idxs) <NEW_LINE> <DEDENT> all_idxs = [all_idxs[i] for i in torch.randperm(len(all_idxs))] <NEW_LINE> if len(all_idxs) < self.batch_size: <NEW_LINE> <INDENT> while len(all_idxs) < self.batch_size: <NEW_LINE> <INDENT> all_idxs.append(all_idxs[np.random.randint(0, len(all_idxs))]) <NEW_LINE> <DEDENT> <DEDENT> self.idxs = [] <NEW_LINE> end = self.batch_size * (len(all_idxs) // self.batch_size) <NEW_LINE> for i in range(0, end, self.batch_size): <NEW_LINE> <INDENT> xs = all_idxs[i : i + self.batch_size] <NEW_LINE> self.idxs.append(xs) <NEW_LINE> <DEDENT> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> self._gen_idxs() <NEW_LINE> return (self.idxs[i] for i in torch.randperm(len(self.idxs))) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> num_vids = 0 <NEW_LINE> for vids in self._dir_tree.values(): <NEW_LINE> <INDENT> num_vids += len(vids) <NEW_LINE> <DEDENT> return num_vids // self.batch_size
Randomly samples videos from different classes into the same batch.
62598fa5097d151d1a2c0ef6
class LicenseResponse(object): <NEW_LINE> <INDENT> swagger_types = { 'license_lrn_uuid': 'str', 'license_switch_uuid': 'str' } <NEW_LINE> attribute_map = { 'license_lrn_uuid': 'license_lrn_uuid', 'license_switch_uuid': 'license_switch_uuid' } <NEW_LINE> def __init__(self, license_lrn_uuid=None, license_switch_uuid=None): <NEW_LINE> <INDENT> self._license_lrn_uuid = None <NEW_LINE> self._license_switch_uuid = None <NEW_LINE> if license_lrn_uuid is not None: <NEW_LINE> <INDENT> self.license_lrn_uuid = license_lrn_uuid <NEW_LINE> <DEDENT> if license_switch_uuid is not None: <NEW_LINE> <INDENT> self.license_switch_uuid = license_switch_uuid <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def license_lrn_uuid(self): <NEW_LINE> <INDENT> return self._license_lrn_uuid <NEW_LINE> <DEDENT> @license_lrn_uuid.setter <NEW_LINE> def license_lrn_uuid(self, license_lrn_uuid): <NEW_LINE> <INDENT> self._license_lrn_uuid = license_lrn_uuid <NEW_LINE> <DEDENT> @property <NEW_LINE> def license_switch_uuid(self): <NEW_LINE> <INDENT> return self._license_switch_uuid <NEW_LINE> <DEDENT> @license_switch_uuid.setter <NEW_LINE> def license_switch_uuid(self, license_switch_uuid): <NEW_LINE> <INDENT> self._license_switch_uuid = license_switch_uuid <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, LicenseResponse): <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.
62598fa5a79ad16197769f31
class EmailValidator(DjangoEmailValidator): <NEW_LINE> <INDENT> def __call__(self, value, *args, **kwargs): <NEW_LINE> <INDENT> super(EmailValidator, self).__call__(value, *args, **kwargs) <NEW_LINE> value = force_text(value) <NEW_LINE> domain = value.split('@')[1] <NEW_LINE> try: <NEW_LINE> <INDENT> resolver.query(domain, 'MX') <NEW_LINE> <DEDENT> except DNSException: <NEW_LINE> <INDENT> raise ValidationError('Enter a valid email address domain.', code=self.code)
Extended EmailValidator which checks for MX records on the domain.
62598fa544b2445a339b68d6
class UpperConfidenceBound(BaseGaussianUtility): <NEW_LINE> <INDENT> def __init__(self, points, values, kernel, mu_prior=0, noise_sigma=0.0, **params): <NEW_LINE> <INDENT> super(UpperConfidenceBound, self).__init__(points, values, kernel, mu_prior, noise_sigma, **params) <NEW_LINE> delta = params.get('delta', 0.5) <NEW_LINE> self.beta = np.sqrt(2 * np.log(self.dimension * self.iteration**2 * math.pi**2 / (6 * delta))) <NEW_LINE> <DEDENT> def compute_values(self, batch): <NEW_LINE> <INDENT> mu, sigma = self.mean_and_std(batch) <NEW_LINE> return mu + self.beta * sigma
Implements the UCB method. See the following sources for more details: Peter Auer, Using Confidence Bounds for Exploitation-Exploration Trade-offs, Journal of Machine Learning Research 3 (2002) 397-422, 2011.
62598fa556ac1b37e63020bc
class ConnectionMonitorQueryResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'source_status': {'key': 'sourceStatus', 'type': 'str'}, 'states': {'key': 'states', 'type': '[ConnectionStateSnapshot]'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(ConnectionMonitorQueryResult, self).__init__(**kwargs) <NEW_LINE> self.source_status = kwargs.get('source_status', None) <NEW_LINE> self.states = kwargs.get('states', None)
List of connection states snapshots. :param source_status: Status of connection monitor source. Possible values include: "Uknown", "Active", "Inactive". :type source_status: str or ~azure.mgmt.network.v2018_07_01.models.ConnectionMonitorSourceStatus :param states: Information about connection states. :type states: list[~azure.mgmt.network.v2018_07_01.models.ConnectionStateSnapshot]
62598fa55f7d997b871f9348
class TestMap(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 testMap(self): <NEW_LINE> <INDENT> model = swagger_client.models.map.Map()
Map unit test stubs
62598fa523849d37ff850f84
class MetricValueValuesEnum(_messages.Enum): <NEW_LINE> <INDENT> AUTOSCALERS = 0 <NEW_LINE> BACKEND_BUCKETS = 1 <NEW_LINE> BACKEND_SERVICES = 2 <NEW_LINE> CPUS = 3 <NEW_LINE> CPUS_ALL_REGIONS = 4 <NEW_LINE> DISKS_TOTAL_GB = 5 <NEW_LINE> FIREWALLS = 6 <NEW_LINE> FORWARDING_RULES = 7 <NEW_LINE> HEALTH_CHECKS = 8 <NEW_LINE> IMAGES = 9 <NEW_LINE> INSTANCES = 10 <NEW_LINE> INSTANCE_GROUPS = 11 <NEW_LINE> INSTANCE_GROUP_MANAGERS = 12 <NEW_LINE> INSTANCE_TEMPLATES = 13 <NEW_LINE> IN_USE_ADDRESSES = 14 <NEW_LINE> LOCAL_SSD_TOTAL_GB = 15 <NEW_LINE> NETWORKS = 16 <NEW_LINE> NVIDIA_K80_GPUS = 17 <NEW_LINE> PREEMPTIBLE_CPUS = 18 <NEW_LINE> REGIONAL_AUTOSCALERS = 19 <NEW_LINE> REGIONAL_INSTANCE_GROUP_MANAGERS = 20 <NEW_LINE> ROUTERS = 21 <NEW_LINE> ROUTES = 22 <NEW_LINE> SNAPSHOTS = 23 <NEW_LINE> SSD_TOTAL_GB = 24 <NEW_LINE> SSL_CERTIFICATES = 25 <NEW_LINE> STATIC_ADDRESSES = 26 <NEW_LINE> SUBNETWORKS = 27 <NEW_LINE> TARGET_HTTPS_PROXIES = 28 <NEW_LINE> TARGET_HTTP_PROXIES = 29 <NEW_LINE> TARGET_INSTANCES = 30 <NEW_LINE> TARGET_POOLS = 31 <NEW_LINE> TARGET_SSL_PROXIES = 32 <NEW_LINE> TARGET_TCP_PROXIES = 33 <NEW_LINE> TARGET_VPN_GATEWAYS = 34 <NEW_LINE> URL_MAPS = 35 <NEW_LINE> VPN_TUNNELS = 36
[Output Only] Name of the quota metric. Values: AUTOSCALERS: <no description> BACKEND_BUCKETS: <no description> BACKEND_SERVICES: <no description> CPUS: <no description> CPUS_ALL_REGIONS: <no description> DISKS_TOTAL_GB: <no description> FIREWALLS: <no description> FORWARDING_RULES: <no description> HEALTH_CHECKS: <no description> IMAGES: <no description> INSTANCES: <no description> INSTANCE_GROUPS: <no description> INSTANCE_GROUP_MANAGERS: <no description> INSTANCE_TEMPLATES: <no description> IN_USE_ADDRESSES: <no description> LOCAL_SSD_TOTAL_GB: <no description> NETWORKS: <no description> NVIDIA_K80_GPUS: <no description> PREEMPTIBLE_CPUS: <no description> REGIONAL_AUTOSCALERS: <no description> REGIONAL_INSTANCE_GROUP_MANAGERS: <no description> ROUTERS: <no description> ROUTES: <no description> SNAPSHOTS: <no description> SSD_TOTAL_GB: <no description> SSL_CERTIFICATES: <no description> STATIC_ADDRESSES: <no description> SUBNETWORKS: <no description> TARGET_HTTPS_PROXIES: <no description> TARGET_HTTP_PROXIES: <no description> TARGET_INSTANCES: <no description> TARGET_POOLS: <no description> TARGET_SSL_PROXIES: <no description> TARGET_TCP_PROXIES: <no description> TARGET_VPN_GATEWAYS: <no description> URL_MAPS: <no description> VPN_TUNNELS: <no description>
62598fa585dfad0860cbf9dc
class DelegationStrategyType(Enum): <NEW_LINE> <INDENT> ALWAYS = "ALWAYS" <NEW_LINE> SKILL_RESPONSE = "SKILL_RESPONSE" <NEW_LINE> def to_dict(self): <NEW_LINE> <INDENT> result = {self.name: self.value} <NEW_LINE> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.value) <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, DelegationStrategyType): <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
Enumerates delegation strategies used to control automatic dialog management through the defined dialog model. When no delegation strategies are defined, the value SKILL_RESPONSE is assumed. Allowed enum values: [ALWAYS, SKILL_RESPONSE]
62598fa55166f23b2e2432a6
class TestDedupeApi(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.api = isi_sdk_9_1_0.api.dedupe_api.DedupeApi() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_get_dedupe_dedupe_summary(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_get_dedupe_report(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_get_dedupe_reports(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_get_dedupe_settings(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_get_inline_settings(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_update_dedupe_settings(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_update_inline_settings(self): <NEW_LINE> <INDENT> pass
DedupeApi unit test stubs
62598fa5a8ecb033258710de
class AstConditionNode(AstNode, ConditionNode): <NEW_LINE> <INDENT> def __init__(self, ast_cond: _ast.stmt, **kwargs): <NEW_LINE> <INDENT> AstNode.__init__(self, ast_cond, **kwargs) <NEW_LINE> ConditionNode.__init__(self, cond=self.cond_expr()) <NEW_LINE> <DEDENT> def cond_expr(self) -> str: <NEW_LINE> <INDENT> source = astunparse.unparse(self.ast_object) <NEW_LINE> loop_statement = source.strip() <NEW_LINE> lines = loop_statement.splitlines() <NEW_LINE> if len(lines) >= 1: <NEW_LINE> <INDENT> return lines[0].rstrip(':') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 'True' <NEW_LINE> <DEDENT> <DEDENT> def fc_connection(self) -> str: <NEW_LINE> <INDENT> return ""
AstConditionNode is a ConditionNode for _ast.For | _ast.While | _ast.If ({for|while|if}-sentence in code)
62598fa5f548e778e596b474
class Opponent(object): <NEW_LINE> <INDENT> def __init__(self, name, strenght): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.level = strenght <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return f"Digital Oppononent: {self.name} at Level {self.level}"
docstring for Opponent
62598fa5d486a94d0ba2be9d
class AddForm(BaseAddForm): <NEW_LINE> <INDENT> schema = IContextualSearchPortlet <NEW_LINE> def updateWidgets(self): <NEW_LINE> <INDENT> super(AddForm, self).updateWidgets() <NEW_LINE> <DEDENT> def create(self, data): <NEW_LINE> <INDENT> return Assignment(**data)
Portlet add form. This is registered in configure.zcml. The form_fields variable tells zope.formlib which fields to display. The create() method actually constructs the assignment that is being added.
62598fa54a966d76dd5eedb3
class TestMixsyn(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> control.use_numpy_matrix(False) <NEW_LINE> <DEDENT> @unittest.skipIf(not slycot_check(), "slycot not installed") <NEW_LINE> def testSiso(self): <NEW_LINE> <INDENT> from control import tf, augw, hinfsyn, mixsyn <NEW_LINE> from control import ss <NEW_LINE> s = tf([1, 0], 1) <NEW_LINE> g = 200 / (10 * s + 1) / (0.05 * s + 1) ** 2 <NEW_LINE> M = 1.5 <NEW_LINE> wb = 10 <NEW_LINE> A = 1e-4 <NEW_LINE> w1 = (s / M + wb) / (s + wb * A) <NEW_LINE> w2 = tf(1, 1) <NEW_LINE> p = augw(g, w1, w2) <NEW_LINE> kref, clref, gam, rcond = hinfsyn(p, 1, 1) <NEW_LINE> ktest, cltest, info = mixsyn(g, w1, w2) <NEW_LINE> np.testing.assert_allclose(gam, 1.37, atol=1e-2) <NEW_LINE> np.testing.assert_allclose(ktest.A, kref.A) <NEW_LINE> np.testing.assert_allclose(ktest.B, kref.B) <NEW_LINE> np.testing.assert_allclose(ktest.C, kref.C) <NEW_LINE> np.testing.assert_allclose(ktest.D, kref.D) <NEW_LINE> np.testing.assert_allclose(cltest.A, clref.A) <NEW_LINE> np.testing.assert_allclose(cltest.B, clref.B) <NEW_LINE> np.testing.assert_allclose(cltest.C, clref.C) <NEW_LINE> np.testing.assert_allclose(cltest.D, clref.D) <NEW_LINE> np.testing.assert_allclose(gam, info[0]) <NEW_LINE> np.testing.assert_allclose(rcond, info[1]) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> control.config.reset_defaults()
Test control.robust.mixsyn
62598fa5090684286d593643
class BOMReference(ReferenceBase): <NEW_LINE> <INDENT> _schema = load_schema(SCHEMA_DIR,'references.json')["bom_ref"] <NEW_LINE> _validator = jsonschema.Draft4Validator(_schema) <NEW_LINE> def __init__(self,**kwargs): <NEW_LINE> <INDENT> ReferenceBase.__init__(self,**kwargs) <NEW_LINE> <DEDENT> def dereference(self,store): <NEW_LINE> <INDENT> res = ReferenceBase.dereference(self,store) <NEW_LINE> obj = store.get_obj(self.obj_id) <NEW_LINE> res.update(obj.dereference(store)) <NEW_LINE> return res <NEW_LINE> <DEDENT> def collect_ids(self,store): <NEW_LINE> <INDENT> obj = store.get_obj(self.obj_id) <NEW_LINE> return obj.collect_ids(store)
An object with quantities. {{references.json#/bom_ref}}
62598fa57b25080760ed737b
class Develpoment: <NEW_LINE> <INDENT> DEBUG = True <NEW_LINE> TESTING = False
Development environment configuration
62598fa5fff4ab517ebcd6b5
class svn_txdelta_md5_digest_fn_t: <NEW_LINE> <INDENT> __swig_setmethods__ = {} <NEW_LINE> __setattr__ = lambda self, name, value: _swig_setattr(self, svn_txdelta_md5_digest_fn_t, name, value) <NEW_LINE> __swig_getmethods__ = {} <NEW_LINE> __getattr__ = lambda self, name: _swig_getattr(self, svn_txdelta_md5_digest_fn_t, name) <NEW_LINE> def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> def set_parent_pool(self, parent_pool=None): <NEW_LINE> <INDENT> import libsvn.core, weakref <NEW_LINE> self.__dict__["_parent_pool"] = parent_pool or libsvn.core.application_pool; <NEW_LINE> if self.__dict__["_parent_pool"]: <NEW_LINE> <INDENT> self.__dict__["_is_valid"] = weakref.ref( self.__dict__["_parent_pool"]._is_valid) <NEW_LINE> <DEDENT> <DEDENT> def assert_valid(self): <NEW_LINE> <INDENT> if "_is_valid" in self.__dict__: <NEW_LINE> <INDENT> assert self.__dict__["_is_valid"](), "Variable has already been deleted" <NEW_LINE> <DEDENT> <DEDENT> def __getattr__(self, name): <NEW_LINE> <INDENT> self.assert_valid() <NEW_LINE> value = _swig_getattr(self, self.__class__, name) <NEW_LINE> members = self.__dict__.get("_members") <NEW_LINE> if members is not None: <NEW_LINE> <INDENT> _copy_metadata_deep(value, members.get(name)) <NEW_LINE> <DEDENT> _assert_valid_deep(value) <NEW_LINE> return value <NEW_LINE> <DEDENT> def __setattr__(self, name, value): <NEW_LINE> <INDENT> self.assert_valid() <NEW_LINE> self.__dict__.setdefault("_members",{})[name] = value <NEW_LINE> return _swig_setattr(self, self.__class__, name, value) <NEW_LINE> <DEDENT> def __call__(self, *args): <NEW_LINE> <INDENT> return svn_txdelta_invoke_md5_digest_fn(self, *args)
Proxy of C svn_txdelta_md5_digest_fn_t struct
62598fa57d43ff248742736a
class LineReceiver(BaseReceiver, _PauseableMixin): <NEW_LINE> <INDENT> _parsleyGrammarPKG = parseproto.basic <NEW_LINE> _parsleyGrammarName = 'line_receiver' <NEW_LINE> _buffer = b'' <NEW_LINE> _busyReceiving = False <NEW_LINE> delimiter = b'\r\n' <NEW_LINE> MAX_LENGTH = 16384 <NEW_LINE> _mode = 1 <NEW_LINE> @property <NEW_LINE> def line_mode(self): <NEW_LINE> <INDENT> return self._mode <NEW_LINE> <DEDENT> @line_mode.setter <NEW_LINE> def line_mode(self, val): <NEW_LINE> <INDENT> self._mode = val <NEW_LINE> if self._trampolinedParser is not None: <NEW_LINE> <INDENT> self.currentRule = "line" if self._mode else "data" <NEW_LINE> <DEDENT> <DEDENT> @line_mode.deleter <NEW_LINE> def line_mode(self): <NEW_LINE> <INDENT> del self._mode <NEW_LINE> <DEDENT> def clearLineBuffer(self): <NEW_LINE> <INDENT> b, self._buffer = self._buffer, b"" <NEW_LINE> return b <NEW_LINE> <DEDENT> def dataReceived(self, data): <NEW_LINE> <INDENT> if self._busyReceiving: <NEW_LINE> <INDENT> self._buffer += data <NEW_LINE> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self._busyReceiving = True <NEW_LINE> self._buffer += data <NEW_LINE> while self._buffer and not self.paused: <NEW_LINE> <INDENT> if self._trampolinedParser is None: <NEW_LINE> <INDENT> self._initializeParserProtocol() <NEW_LINE> <DEDENT> buf, self._buffer = self._buffer, b'' <NEW_LINE> self._trampolinedParser.receive(buf) <NEW_LINE> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> self._busyReceiving = False <NEW_LINE> <DEDENT> <DEDENT> def setLineMode(self, extra=b''): <NEW_LINE> <INDENT> self.line_mode = 1 <NEW_LINE> if extra: <NEW_LINE> <INDENT> return self.dataReceived(extra) <NEW_LINE> <DEDENT> <DEDENT> def setRawMode(self): <NEW_LINE> <INDENT> self.line_mode = 0 <NEW_LINE> <DEDENT> def rawDataReceived(self, data): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def lineReceived(self, line): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def sendLine(self, line): <NEW_LINE> <INDENT> return self.transport.write(line + self.delimiter) <NEW_LINE> <DEDENT> def lineLengthExceeded(self, line): <NEW_LINE> <INDENT> return self.transport.loseConnection()
A protocol that receives lines and/or raw data, depending on mode. In line mode, each line that's received becomes a callback to L{lineReceived}. In raw data mode, each chunk of raw data becomes a callback to L{rawDataReceived}. The L{setLineMode} and L{setRawMode} methods switch between the two modes. This is useful for line-oriented protocols such as IRC, HTTP, POP, etc. @cvar delimiter: The line-ending delimiter to use. By default this is C{b'\r\n'}. @cvar MAX_LENGTH: The maximum length of a line to allow (If a sent line is longer than this, the connection is dropped). Default is 16384.
62598fa5be383301e02536c8
class FilerTeaserPlugin(CMSPluginBase): <NEW_LINE> <INDENT> module = 'Filer' <NEW_LINE> model = models.FilerTeaser <NEW_LINE> raw_id_fields = ('page_link',) <NEW_LINE> name = _("Teaser") <NEW_LINE> TEMPLATE_NAME = 'cmsplugin_filer_teaser/plugins/teaser/%s.html' <NEW_LINE> render_template = TEMPLATE_NAME % 'default' <NEW_LINE> fieldsets = ( (None, {'fields': [ 'title', 'image', 'image_url', 'description', ]}), (_('More'), { 'classes': ('collapse',), 'fields': [ 'use_autoscale', ('width', 'height'), 'free_link', 'page_link', 'target_blank' ] }) ) <NEW_LINE> if settings.CMSPLUGIN_FILER_TEASER_STYLE_CHOICES: <NEW_LINE> <INDENT> fieldsets[0][1]['fields'].append('style') <NEW_LINE> <DEDENT> def _get_thumbnail_options(self, context, instance): <NEW_LINE> <INDENT> width, height = None, None <NEW_LINE> subject_location = False <NEW_LINE> placeholder_width = context.get('width', None) <NEW_LINE> placeholder_height = context.get('height', None) <NEW_LINE> if instance.use_autoscale and placeholder_width: <NEW_LINE> <INDENT> width = int(placeholder_width) <NEW_LINE> <DEDENT> if instance.use_autoscale and placeholder_height: <NEW_LINE> <INDENT> height = int(placeholder_height) <NEW_LINE> <DEDENT> elif instance.width: <NEW_LINE> <INDENT> width = instance.width <NEW_LINE> <DEDENT> if instance.height: <NEW_LINE> <INDENT> height = instance.height <NEW_LINE> <DEDENT> if instance.image: <NEW_LINE> <INDENT> if instance.image.subject_location: <NEW_LINE> <INDENT> subject_location = instance.image.subject_location <NEW_LINE> <DEDENT> if not height and width: <NEW_LINE> <INDENT> height = int(float(width) * float(instance.image.height) / float(instance.image.width)) <NEW_LINE> <DEDENT> if not width and height: <NEW_LINE> <INDENT> width = int(float(height) * float(instance.image.width) / float(instance.image.height)) <NEW_LINE> <DEDENT> if not width: <NEW_LINE> <INDENT> width = instance.image.width <NEW_LINE> <DEDENT> if not height: <NEW_LINE> <INDENT> height = instance.image.height <NEW_LINE> <DEDENT> <DEDENT> return {'size': (width, height), 'subject_location': subject_location} <NEW_LINE> <DEDENT> def get_thumbnail(self, context, instance): <NEW_LINE> <INDENT> if instance.image: <NEW_LINE> <INDENT> return instance.image.file.get_thumbnail(self._get_thumbnail_options(context, instance)) <NEW_LINE> <DEDENT> <DEDENT> def render(self, context, instance, placeholder): <NEW_LINE> <INDENT> self.render_template = select_template(( 'cmsplugin_filer_teaser/plugins/teaser.html', self.TEMPLATE_NAME % instance.style, self.TEMPLATE_NAME % 'default') ) <NEW_LINE> options = self._get_thumbnail_options(context, instance) <NEW_LINE> context.update({ 'instance': instance, 'link': instance.link, 'opts': options, 'size': options.get('size', None), 'placeholder': placeholder }) <NEW_LINE> return context
TODO: this plugin is becoming very similar to the image plugin... code should be re-used somehow.
62598fa5e5267d203ee6b7de
class Entry(models.Model): <NEW_LINE> <INDENT> topic = models.ForeignKey(Topic, on_delete=models.CASCADE) <NEW_LINE> text = models.TextField() <NEW_LINE> date_added = models.DateTimeField(auto_now_add=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name_plural = 'entries' <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> if len(self.text) > 50: <NEW_LINE> <INDENT> return self.text[:50] + "..." <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.text[:50]
Something specific learned about a topic
62598fa54527f215b58e9db2
class Oper(A10BaseClass): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.ERROR_MSG = "" <NEW_LINE> self.b_key = "oper" <NEW_LINE> self.DeviceProxy = "" <NEW_LINE> self.session_list = [] <NEW_LINE> for keys, value in kwargs.items(): <NEW_LINE> <INDENT> setattr(self,keys, value)
This class does not support CRUD Operations please use parent. :param session_list: {"minItems": 1, "items": {"type": "object"}, "uniqueItems": true, "type": "array", "array": [{"properties": {"Session-id": {"type": "number", "format": "number"}, "TTL-in-seconds": {"type": "number", "format": "number"}, "Domain": {"minLength": 1, "maxLength": 63, "type": "string", "format": "string"}, "Client-IP": {"minLength": 1, "maxLength": 63, "type": "string", "format": "string"}, "optional": true, "Domain-Group": {"minLength": 1, "maxLength": 63, "type": "string", "format": "string"}, "VIP": {"minLength": 1, "maxLength": 63, "type": "string", "format": "string"}, "User": {"minLength": 1, "maxLength": 63, "type": "string", "format": "string"}, "VPort": {"minLength": 1, "maxLength": 63, "type": "string", "format": "string"}, "Type": {"minLength": 1, "maxLength": 63, "type": "string", "format": "string"}, "Created-Time": {"minLength": 1, "maxLength": 63, "type": "string", "format": "string"}}}]} :param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`
62598fa51f5feb6acb162af2
class MySawTooth(PeakProfile): <NEW_LINE> <INDENT> def type(self): <NEW_LINE> <INDENT> return "mysawtooth" <NEW_LINE> <DEDENT> def create(self): <NEW_LINE> <INDENT> return MySawTooth() <NEW_LINE> <DEDENT> def clone(self): <NEW_LINE> <INDENT> import copy <NEW_LINE> return copy.copy(self) <NEW_LINE> <DEDENT> tcnt = 0 <NEW_LINE> def ticker(self): <NEW_LINE> <INDENT> self.tcnt += 1 <NEW_LINE> return PeakProfile.ticker(self) <NEW_LINE> <DEDENT> def __call__(self, x, fwhm): <NEW_LINE> <INDENT> w = 1.0 * fwhm <NEW_LINE> rv = (1 - abs(x) / w) / (1.0 * w) <NEW_LINE> if rv < 0: rv = 0 <NEW_LINE> return rv <NEW_LINE> <DEDENT> def xboundlo(self, fwhm): <NEW_LINE> <INDENT> return -fwhm <NEW_LINE> <DEDENT> def xboundhi(self, fwhm): <NEW_LINE> <INDENT> return +fwhm
Helper class for testing PeakProfile.
62598fa5e64d504609df9321
class LogToBufferHandler(LogToXmlHandler): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(LogToBufferHandler, self).__init__() <NEW_LINE> <DEDENT> def flush(self): <NEW_LINE> <INDENT> pass
.. class:: LogToBufferHandler() A log handler that writes log entries to a memory buffer for later retrieval (to a string) in XML, JSON, or text lines, usually for return to a web service or web page call.
62598fa57d847024c075c296
class VonMisesBM(BasisMatrix): <NEW_LINE> <INDENT> def __init__(self, cs, num_basis, basis_width=1.): <NEW_LINE> <INDENT> def dphi_t(cs, phi): <NEW_LINE> <INDENT> def step(s): <NEW_LINE> <INDENT> return phi.grad(s) * cs.grad() <NEW_LINE> <DEDENT> return step <NEW_LINE> <DEDENT> if num_basis == 1: <NEW_LINE> <INDENT> centers = (1. + 4 * basis_width) / 2. <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> centers = np.linspace(-2 * basis_width, 1 + 2 * basis_width, num_basis) <NEW_LINE> <DEDENT> phi = VonMisesBF(centers, basis_width) <NEW_LINE> dphi = dphi_t(cs, phi) <NEW_LINE> matrix = np.array([phi, dphi]) <NEW_LINE> super(VonMisesBM, self).__init__(matrix)
Von-Mises Basis Matrix Matrix containing Von-Mises basis functions.
62598fa566656f66f7d5a2c0
class ARCUITField(RegexField): <NEW_LINE> <INDENT> default_error_messages = { 'invalid': _('Enter a valid CUIT in XX-XXXXXXXX-X or XXXXXXXXXXXX format.'), 'checksum': _("Invalid CUIT."), 'legal_type': _('Invalid legal type. Type must be 27, 20, 30, 23, 24 or 33.'), } <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(ARCUITField, self).__init__(r'^\d{2}-?\d{8}-?\d$', *args, **kwargs) <NEW_LINE> <DEDENT> def clean(self, value): <NEW_LINE> <INDENT> value = super(ARCUITField, self).clean(value) <NEW_LINE> if value in self.empty_values: <NEW_LINE> <INDENT> return self.empty_value <NEW_LINE> <DEDENT> value, cd = self._canon(value) <NEW_LINE> if not value[:2] in ['27', '20', '30', '23', '24', '33']: <NEW_LINE> <INDENT> raise ValidationError(self.error_messages['legal_type']) <NEW_LINE> <DEDENT> if self._calc_cd(value) != cd: <NEW_LINE> <INDENT> raise ValidationError(self.error_messages['checksum']) <NEW_LINE> <DEDENT> return self._format(value, cd) <NEW_LINE> <DEDENT> def _canon(self, cuit): <NEW_LINE> <INDENT> cuit = cuit.replace('-', '') <NEW_LINE> return cuit[:-1], cuit[-1] <NEW_LINE> <DEDENT> def _calc_cd(self, cuit): <NEW_LINE> <INDENT> mults = (5, 4, 3, 2, 7, 6, 5, 4, 3, 2) <NEW_LINE> tmp = sum([m * int(cuit[idx]) for idx, m in enumerate(mults)]) <NEW_LINE> result = 11 - (tmp % 11) <NEW_LINE> if result == 11: <NEW_LINE> <INDENT> result = 0 <NEW_LINE> <DEDENT> elif result == 10: <NEW_LINE> <INDENT> result = 9 <NEW_LINE> <DEDENT> return str(result) <NEW_LINE> <DEDENT> def _format(self, cuit, check_digit=None): <NEW_LINE> <INDENT> if check_digit is None: <NEW_LINE> <INDENT> check_digit = cuit[-1] <NEW_LINE> cuit = cuit[:-1] <NEW_LINE> <DEDENT> return '%s-%s-%s' % (cuit[:2], cuit[2:], check_digit)
This field validates a CUIT (Código Único de Identificación Tributaria). ACUIT is of the form XX-XXXXXXXX-V. The last digit is a check digit. More info: http://es.wikipedia.org/wiki/Clave_%C3%9Anica_de_Identificaci%C3%B3n_Tributaria English info: http://www.justlanded.com/english/Argentina/Argentina-Guide/Visas-Permits/Other-Legal-Documents
62598fa507f4c71912baf314
class IotManager(): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def get_state_topic(device,control): <NEW_LINE> <INDENT> return str.encode('/IoTmanager/{}/{}/status'.format(device,control)) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_state_value(state): <NEW_LINE> <INDENT> return str.encode('{{\"status\":{}}}'.format(state*1)) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_control_topic(device,control): <NEW_LINE> <INDENT> return str.encode('/IoTmanager/{}/{}/control'.format(device,control)) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_control_value(state): <NEW_LINE> <INDENT> return str.encode('{}'.format(state*1)) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_device_topic(device): <NEW_LINE> <INDENT> return str.encode('/IoTmanager/{}/report'.format(device))
The class provides topics compatible with IoTManager[1] for publishing and reading. The idea is to make architecture pluggable and make it easy to replace this class with another implementation for another client. [1] https://play.google.com/store/apps/details?id=ru.esp8266.iotmanager
62598fa58e7ae83300ee8f72
class TeamCreateView(generics.ListCreateAPIView): <NEW_LINE> <INDENT> queryset = Team.objects.all() <NEW_LINE> serializer_class = TeamSerializer <NEW_LINE> authentication_classes = (TokenAuthentication, BasicAuthentication) <NEW_LINE> def perform_create(self, serializer): <NEW_LINE> <INDENT> serializer.save()
This class defines the create behavior of our rest api.
62598fa530bbd722464698e0
class FormFieldFloat(FormFieldText): <NEW_LINE> <INDENT> def __init__(self, name, required=None, options=None, items=None, caption=None, attributes=None): <NEW_LINE> <INDENT> FormFieldText.__init__(self, name, required, options, items, caption, attributes) <NEW_LINE> self._type = 'float'
Field which allows to store floating point numbers or values
62598fa599cbb53fe6830da6
class SessionStore(requests.Session): <NEW_LINE> <INDENT> def __init__(self, endpoint, reauthenticate, cookie_file=None, login_params=None): <NEW_LINE> <INDENT> super(SessionStore, self).__init__() <NEW_LINE> self.session_base_url = '{0}/api/session'.format(endpoint) <NEW_LINE> self.reauthenticate = reauthenticate <NEW_LINE> self.login_params = login_params <NEW_LINE> if cookie_file is None: <NEW_LINE> <INDENT> cookie_file = DEFAULT_COOKIE_FILE <NEW_LINE> <DEDENT> cookie_dir = os.path.dirname(cookie_file) <NEW_LINE> self.cookies = MozillaCookieJar(cookie_file) <NEW_LINE> if not os.path.isdir(cookie_dir): <NEW_LINE> <INDENT> os.mkdir(cookie_dir, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR) <NEW_LINE> <DEDENT> if os.path.isfile(cookie_file): <NEW_LINE> <INDENT> self.cookies.load(ignore_discard=True) <NEW_LINE> self.cookies.clear_expired_cookies() <NEW_LINE> <DEDENT> <DEDENT> def need_to_login(self, accessed_url, status_code): <NEW_LINE> <INDENT> return self.reauthenticate and status_code in [401, 403] and accessed_url != self.session_base_url <NEW_LINE> <DEDENT> def _request(self, *args, **kwargs): <NEW_LINE> <INDENT> kwargs.setdefault('timeout', DEFAULT_TIMEOUT) <NEW_LINE> return super(SessionStore, self).request(*args, **kwargs) <NEW_LINE> <DEDENT> def request(self, *args, **kwargs): <NEW_LINE> <INDENT> response = self._request(*args, **kwargs) <NEW_LINE> if not self.verify and response.cookies: <NEW_LINE> <INDENT> self._unsecure_cookie(args[1], response) <NEW_LINE> <DEDENT> if 'Set-Cookie' in response.headers: <NEW_LINE> <INDENT> self.cookies.save(ignore_discard=True) <NEW_LINE> <DEDENT> url = args[1] <NEW_LINE> if self.need_to_login(url, response.status_code): <NEW_LINE> <INDENT> login_response = self.cimi_login(self.login_params) <NEW_LINE> if login_response is not None and login_response.status_code == 201: <NEW_LINE> <INDENT> response = self._request(*args, **kwargs) <NEW_LINE> <DEDENT> <DEDENT> return response <NEW_LINE> <DEDENT> def cimi_login(self, login_params): <NEW_LINE> <INDENT> self.login_params = login_params <NEW_LINE> if self.login_params: <NEW_LINE> <INDENT> return self.request('POST', self.session_base_url, headers={'Content-Type': 'application/json', 'Accept': 'application/json'}, json={'sessionTemplate': login_params}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def _unsecure_cookie(self, url_str, response): <NEW_LINE> <INDENT> url = urlparse(url_str) <NEW_LINE> if url.scheme == 'http': <NEW_LINE> <INDENT> for cookie in response.cookies: <NEW_LINE> <INDENT> cookie.secure = False <NEW_LINE> self.cookies.set_cookie_if_ok(cookie, MockRequest(response.request)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def clear(self, domain): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.cookies.clear(domain) <NEW_LINE> self.cookies.save() <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass
A ``requests.Session`` subclass implementing a file-based session store.
62598fa516aa5153ce4003d3
class NameLookup: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._uid_to_cls = {} <NEW_LINE> self._uid_to_name = {} <NEW_LINE> self._cls_to_uid = {} <NEW_LINE> path = os.path.join(data_dir, path_uid_to_name) <NEW_LINE> with open(file=path, mode='r') as file: <NEW_LINE> <INDENT> lines = file.readlines() <NEW_LINE> for line in lines: <NEW_LINE> <INDENT> line = line.replace("\n", "") <NEW_LINE> elements = line.split("\t") <NEW_LINE> uid = elements[0] <NEW_LINE> name = elements[1] <NEW_LINE> self._uid_to_name[uid] = name <NEW_LINE> <DEDENT> <DEDENT> path = os.path.join(data_dir, path_uid_to_cls) <NEW_LINE> with open(file=path, mode='r') as file: <NEW_LINE> <INDENT> lines = file.readlines() <NEW_LINE> for line in lines: <NEW_LINE> <INDENT> if line.startswith(" target_class: "): <NEW_LINE> <INDENT> elements = line.split(": ") <NEW_LINE> cls = int(elements[1]) <NEW_LINE> <DEDENT> elif line.startswith(" target_class_string: "): <NEW_LINE> <INDENT> elements = line.split(": ") <NEW_LINE> uid = elements[1] <NEW_LINE> uid = uid[1:-2] <NEW_LINE> self._uid_to_cls[uid] = cls <NEW_LINE> self._cls_to_uid[cls] = uid <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def uid_to_cls(self, uid): <NEW_LINE> <INDENT> return self._uid_to_cls[uid] <NEW_LINE> <DEDENT> def uid_to_name(self, uid, only_first_name=False): <NEW_LINE> <INDENT> name = self._uid_to_name[uid] <NEW_LINE> if only_first_name: <NEW_LINE> <INDENT> name = name.split(",")[0] <NEW_LINE> <DEDENT> return name <NEW_LINE> <DEDENT> def cls_to_name(self, cls, only_first_name=False): <NEW_LINE> <INDENT> uid = self._cls_to_uid[cls] <NEW_LINE> name = self.uid_to_name(uid=uid, only_first_name=only_first_name) <NEW_LINE> return name
Used for looking up the name associated with a class-number. This is used to print the name of a class instead of its number, e.g. "plant" or "horse". Maps between: - cls is the class-number as an integer between 1 and 1000 (inclusive). - uid is a class-id as a string from the ImageNet data-set, e.g. "n00017222". - name is the class-name as a string, e.g. "plant, flora, plant life" There are actually 1008 output classes of the transfer-learning model but there are only 1000 named classes in these mapping-files. The remaining 8 output classes of the model should not be used.
62598fa5cb5e8a47e493c0e0
class RegistrationForm(forms.Form): <NEW_LINE> <INDENT> username = forms.RegexField( r"^[a-zA-Z0-9_\-\.]*$", max_length=30, error_messages={ 'invalid': _('Only A-Z, 0-9, "_", "-", and "." are allowed.'), }) <NEW_LINE> password1 = forms.CharField(label=_('Password'), min_length=5, widget=forms.PasswordInput) <NEW_LINE> password2 = forms.CharField(label=_('Password (confirm)'), widget=forms.PasswordInput) <NEW_LINE> email = forms.EmailField(label=_('E-mail address')) <NEW_LINE> first_name = forms.CharField(max_length=30, required=False) <NEW_LINE> last_name = forms.CharField(max_length=30, required=False) <NEW_LINE> def __init__(self, request=None, *args, **kwargs): <NEW_LINE> <INDENT> super(RegistrationForm, self).__init__(*args, **kwargs) <NEW_LINE> self.request = request <NEW_LINE> <DEDENT> def clean_password2(self): <NEW_LINE> <INDENT> formdata = self.cleaned_data <NEW_LINE> if ('password1' in formdata and formdata['password1'] != formdata['password2']): <NEW_LINE> <INDENT> raise ValidationError(_('Passwords must match')) <NEW_LINE> <DEDENT> return formdata['password2'] <NEW_LINE> <DEDENT> def save(self): <NEW_LINE> <INDENT> if not self.errors: <NEW_LINE> <INDENT> username = self.cleaned_data['username'] <NEW_LINE> try: <NEW_LINE> <INDENT> with transaction.atomic(): <NEW_LINE> <INDENT> return User.objects.create_user( username=username, password=self.cleaned_data['password1'], email=self.cleaned_data['email'], first_name=self.cleaned_data['first_name'], last_name=self.cleaned_data['last_name']) <NEW_LINE> <DEDENT> <DEDENT> except Exception: <NEW_LINE> <INDENT> if User.objects.filter(username=username).exists(): <NEW_LINE> <INDENT> self.errors['username'] = self.error_class( [_('Sorry, this username is taken.')]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return None
A standard registration form collecting basic account information. This form prompts the user for a username, a password (and a confirmation on that password), e-mail address, first name, and last name. It then validates these, attempting to create a :py:class:`User`. This class can be extended by subclasses to provide additional fields.
62598fa5e76e3b2f99fd8907
class PodcastDatabaseManager(object): <NEW_LINE> <INDENT> def __init__(self, debug_=False): <NEW_LINE> <INDENT> basedir = "~/.podcast" <NEW_LINE> path = basedir + os.sep + 'podcast.sqlite' <NEW_LINE> if not os.path.exists(expanduser(basedir)): <NEW_LINE> <INDENT> print("Creating base dir %s"%basedir) <NEW_LINE> os.makedirs(expanduser(basedir)) <NEW_LINE> <DEDENT> PodcastDatabase._connection = builder()(expanduser(path), debug=debug_) <NEW_LINE> PodcastDatabase.createTable(ifNotExists=True) <NEW_LINE> self.debug_ = debug_ <NEW_LINE> <DEDENT> def get_all_subscribed_podcasts(self): <NEW_LINE> <INDENT> podcasts = PodcastDatabase.select() <NEW_LINE> if self.debug_: <NEW_LINE> <INDENT> print(podcasts) <NEW_LINE> <DEDENT> return podcasts <NEW_LINE> <DEDENT> def get_matching_podcast(self, podcast_name): <NEW_LINE> <INDENT> return list(PodcastDatabase.select(PodcastDatabase.q.name == podcast_name))[0] <NEW_LINE> <DEDENT> def add_podcast(self, podcast): <NEW_LINE> <INDENT> if not self.is_podcast_already_added(podcast.url): <NEW_LINE> <INDENT> PodcastDatabase(name=podcast.title, url=podcast.url) <NEW_LINE> if self.debug_: <NEW_LINE> <INDENT> print("Podcast <{0}> registered".format(podcast)) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if self.debug_: <NEW_LINE> <INDENT> print ("Podcast <{0}> already registered".format(podcast)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def is_podcast_already_added(self, podcast_url): <NEW_LINE> <INDENT> return PodcastDatabase.select(PodcastDatabase.q.url == podcast_url).count() > 0 <NEW_LINE> <DEDENT> def delete(self, podcast_names): <NEW_LINE> <INDENT> if self.debug_: <NEW_LINE> <INDENT> print("Podcasts to delete: [{}]".format(podcast_names)) <NEW_LINE> <DEDENT> for podcast_name in podcast_names: <NEW_LINE> <INDENT> print("Deleting podcast [{}]".format(podcast_name)) <NEW_LINE> id_ = list(PodcastDatabase.select(PodcastDatabase.q.name == podcast_name))[0].id <NEW_LINE> PodcastDatabase.delete(id_)
Access to database layer of podcasts.
62598fa521bff66bcd722b37
class AdicionaManPMEdigi(Operator, AddObjectHelper): <NEW_LINE> <INDENT> bl_idname = "mesh.add_man_pme_digi" <NEW_LINE> bl_label = "Add Centroide" <NEW_LINE> bl_options = {'REGISTER', 'UNDO'} <NEW_LINE> @classmethod <NEW_LINE> def poll(cls, context): <NEW_LINE> <INDENT> found = 'Man-PME-digi' in bpy.data.objects <NEW_LINE> if found == False: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if found == True: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def execute(self, context): <NEW_LINE> <INDENT> AdicionaEMPTYDef("Man-PME-digi") <NEW_LINE> return {'FINISHED'}
Create a new Mesh Object
62598fa5a8ecb033258710e0
class OctaveShift(MusicXMLElement): <NEW_LINE> <INDENT> def __init__(self, type=None): <NEW_LINE> <INDENT> MusicXMLElement.__init__(self) <NEW_LINE> self._tag = 'octave-shift' <NEW_LINE> self._attr['type'] = None <NEW_LINE> self._attr['number'] = None <NEW_LINE> self._attr['size'] = None
>>> os = musicxml.OctaveShift() >>> os.tag 'octave-shift'
62598fa5dd821e528d6d8e07
class TEST(object): <NEW_LINE> <INDENT> def __init__(self,test): <NEW_LINE> <INDENT> self.__test = test <NEW_LINE> <DEDENT> def learn_kernel(self,method='tstat',learning_rate=0.01): <NEW_LINE> <INDENT> if method=='power': <NEW_LINE> <INDENT> loss = -self.__test.get_power() <NEW_LINE> <DEDENT> elif method=='measure': <NEW_LINE> <INDENT> loss = -self.__test.get_estimate() <NEW_LINE> <DEDENT> elif method=='tstat': <NEW_LINE> <INDENT> loss = -self.__test.get_tstat(True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> loss = -self.__test.get_tstat(True) <NEW_LINE> <DEDENT> optimizer = tf.train.AdamOptimizer(learning_rate) <NEW_LINE> return optimizer.minimize(loss)
main class test needs to have: get_tstat() get_estimate() reset(params1,params2) get_treshold get_power()
62598fa567a9b606de545e9d
class ChangeopenidForm(forms.Form): <NEW_LINE> <INDENT> openid_url = forms.CharField(max_length=255, widget=forms.TextInput(attrs={'class': "required" })) <NEW_LINE> def __init__(self, data=None, user=None, *args, **kwargs): <NEW_LINE> <INDENT> if user is None: <NEW_LINE> <INDENT> raise TypeError("Keyword argument 'user' must be supplied") <NEW_LINE> <DEDENT> super(ChangeopenidForm, self).__init__(data, *args, **kwargs) <NEW_LINE> self.user = user
change openid form
62598fa563d6d428bbee2683
class Collectioner(threading.Thread): <NEW_LINE> <INDENT> def __init__(self, scraper): <NEW_LINE> <INDENT> threading.Thread.__init__(self) <NEW_LINE> self.name = 'Collect - {0}'.format(listOfScrapers.index(scraper)+1) <NEW_LINE> self.setDaemon(True) <NEW_LINE> self.scraper = scraper <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> logger.debug('Collectioner start collecting...') <NEW_LINE> self.collect() <NEW_LINE> <DEDENT> def collect(self): <NEW_LINE> <INDENT> proxyHarvesterObj = proxyhandler.ProxyHarvester('proxies.p') <NEW_LINE> extractedProxies = self.scraper.main(proxies=proxyHarvesterObj) <NEW_LINE> proxies = self.scraper.normalize(extractedProxies) <NEW_LINE> if proxies: <NEW_LINE> <INDENT> [uncheckedProxy.put(proxy['proxy']) for proxy in proxies] <NEW_LINE> logger.debug('Got proxies from {0}. NumOfProxies: {1}'.format(proxies[0]['source'], len(proxies)))
Collectioner is responsible for scrapeing proxies. As argument during initialization it takes custom scrapers for website with free proxy lists. It uses global variable (listOfScrapers) were custom scrapers (for websites with free proxy lists) are listed.
62598fa566673b3332c3029b
class UserSetDefaultLocalizationValues(): <NEW_LINE> <INDENT> mi_vals = ['enus', 'engb', 'enuk', 'cygb', 'kwgb', 'enlr', 'mymm', ] <NEW_LINE> def process_request(self, request): <NEW_LINE> <INDENT> if request.user.is_authenticated(): <NEW_LINE> <INDENT> if not request.user.profile.pref_distance_unit: <NEW_LINE> <INDENT> lc = request.META['HTTP_ACCEPT_LANGUAGE'] <NEW_LINE> lc = lc.split(';', 1)[0].split(',', 1)[0] <NEW_LINE> lc = re.sub(r'[^a-z]', '', lc.lower()) <NEW_LINE> if lc in self.mi_vals: <NEW_LINE> <INDENT> request.user.profile.pref_distance_unit = 'mi' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> request.user.profile.pref_distance_unit = 'km' <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return None
Set some default vals on the request, based on user's HTTP headers
62598fa501c39578d7f12c52
class Sensor(ZhaEntity): <NEW_LINE> <INDENT> _domain = DOMAIN <NEW_LINE> def __init__(self, unique_id, zha_device, channels, **kwargs): <NEW_LINE> <INDENT> super().__init__(unique_id, zha_device, channels, **kwargs) <NEW_LINE> self._sensor_type = kwargs.get(SENSOR_TYPE, GENERIC) <NEW_LINE> self._unit = UNIT_REGISTRY.get(self._sensor_type) <NEW_LINE> self._formatter_function = FORMATTER_FUNC_REGISTRY.get( self._sensor_type, pass_through_formatter ) <NEW_LINE> self._force_update = FORCE_UPDATE_REGISTRY.get( self._sensor_type, False ) <NEW_LINE> self._should_poll = POLLING_REGISTRY.get( self._sensor_type, False ) <NEW_LINE> self._channel = self.cluster_channels.get( CHANNEL_REGISTRY.get(self._sensor_type, ATTRIBUTE_CHANNEL) ) <NEW_LINE> <DEDENT> async def async_added_to_hass(self): <NEW_LINE> <INDENT> await super().async_added_to_hass() <NEW_LINE> await self.async_accept_signal( self._channel, SIGNAL_ATTR_UPDATED, self.async_set_state) <NEW_LINE> await self.async_accept_signal( self._channel, SIGNAL_STATE_ATTR, self.async_update_state_attribute) <NEW_LINE> <DEDENT> @property <NEW_LINE> def unit_of_measurement(self): <NEW_LINE> <INDENT> return self._unit <NEW_LINE> <DEDENT> @property <NEW_LINE> def state(self) -> str: <NEW_LINE> <INDENT> if self._state is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if isinstance(self._state, float): <NEW_LINE> <INDENT> return str(round(self._state, 2)) <NEW_LINE> <DEDENT> return self._state <NEW_LINE> <DEDENT> def async_set_state(self, state): <NEW_LINE> <INDENT> self._unit = UNIT_REGISTRY.get(self._sensor_type) <NEW_LINE> self._state = self._formatter_function(state) <NEW_LINE> self.async_schedule_update_ha_state() <NEW_LINE> <DEDENT> @callback <NEW_LINE> def async_restore_last_state(self, last_state): <NEW_LINE> <INDENT> self._state = last_state.state <NEW_LINE> self._unit = last_state.attributes.get(ATTR_UNIT_OF_MEASUREMENT)
Base ZHA sensor.
62598fa5fff4ab517ebcd6b7
class PatientStateMonitor: <NEW_LINE> <INDENT> def __init__(self, parameters): <NEW_LINE> <INDENT> self._currentState = parameters.get_initial_health_state() <NEW_LINE> self._delta_t = parameters.get_delta_t() <NEW_LINE> self._survivalTime = 0 <NEW_LINE> self._timeToAIDS = 0 <NEW_LINE> self._ifDevelopedAIDS = False <NEW_LINE> <DEDENT> def update(self, k, next_state): <NEW_LINE> <INDENT> if not self.get_if_alive(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if next_state in [P.HealthStats.HIV_DEATH, P.HealthStats.BACKGROUND_DEATH]: <NEW_LINE> <INDENT> self._survivalTime = (k+0.5)*self._delta_t <NEW_LINE> <DEDENT> if self._currentState != P.HealthStats.AIDS and next_state == P.HealthStats.AIDS: <NEW_LINE> <INDENT> self._ifDevelopedAIDS = True <NEW_LINE> self._timeToAIDS = (k + 0.5) * self._delta_t <NEW_LINE> <DEDENT> self._currentState = next_state <NEW_LINE> <DEDENT> def get_if_alive(self): <NEW_LINE> <INDENT> result = True <NEW_LINE> if self._currentState in [P.HealthStats.HIV_DEATH, P.HealthStats.BACKGROUND_DEATH]: <NEW_LINE> <INDENT> result = False <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def get_current_state(self): <NEW_LINE> <INDENT> return self._currentState <NEW_LINE> <DEDENT> def get_survival_time(self): <NEW_LINE> <INDENT> if not self.get_if_alive(): <NEW_LINE> <INDENT> return self._survivalTime <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def get_time_to_AIDS(self): <NEW_LINE> <INDENT> if self._ifDevelopedAIDS: <NEW_LINE> <INDENT> return self._timeToAIDS <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None
to update patient outcomes (years survived, cost, etc.) throughout the simulation
62598fa57d43ff248742736b
class WebSocket(WebSocketMixin, web.View): <NEW_LINE> <INDENT> async def get(self) -> web.WebSocketResponse: <NEW_LINE> <INDENT> self.room = await get_object_or_404( self.request, Room, name=self.request.match_info['slug'].lower() ) <NEW_LINE> user = self.request.user <NEW_LINE> app = self.request.app <NEW_LINE> app.logger.debug('Prepare WS connection') <NEW_LINE> ws = web.WebSocketResponse() <NEW_LINE> await ws.prepare(self.request) <NEW_LINE> if self.room.room_id not in app.wslist: <NEW_LINE> <INDENT> app.wslist[self.room.room_id] = {} <NEW_LINE> <DEDENT> message = await app.objects.create( Message, room=self.room, users=None, text=f'@{user.username} join chat room' ) <NEW_LINE> app.wslist[self.room.room_id][user.username] = ws <NEW_LINE> await self.broadcast(message) <NEW_LINE> async for msg in ws: <NEW_LINE> <INDENT> app.logger.debug(msg) <NEW_LINE> if msg.tp == web.MsgType.text: <NEW_LINE> <INDENT> if msg.data == 'close': <NEW_LINE> <INDENT> await ws.close() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> text = msg.data.strip() <NEW_LINE> if text.startswith('/'): <NEW_LINE> <INDENT> ans = await self.command_line(text) <NEW_LINE> if ans is not None: <NEW_LINE> <INDENT> await ws.send_json(ans) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> message = await app.objects.create( Message, room=self.room, users=user, text=text ) <NEW_LINE> await self.broadcast(message) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> elif msg.tp == web.MsgType.error: <NEW_LINE> <INDENT> app.logger.debug( f'Connection closed with exception {ws.exception()}' ) <NEW_LINE> <DEDENT> <DEDENT> return ws
Helper для работы с вебсокетами
62598fa54527f215b58e9db4
class IngressHelm(base.BaseHelm): <NEW_LINE> <INDENT> CHART = constants.HELM_CHART_INGRESS <NEW_LINE> SUPPORTED_NAMESPACES = [ common.HELM_NS_KUBE_SYSTEM, common.HELM_NS_OPENSTACK ] <NEW_LINE> def get_namespaces(self): <NEW_LINE> <INDENT> return self.SUPPORTED_NAMESPACES <NEW_LINE> <DEDENT> def get_overrides(self, namespace=None): <NEW_LINE> <INDENT> overrides = { common.HELM_NS_KUBE_SYSTEM: { 'pod': { 'replicas': { 'error_page': self._num_controllers() } }, 'deployment': { 'mode': 'cluster', 'type': 'DaemonSet' }, 'network': { 'host_namespace': 'true' }, 'endpoints': { 'ingress': { 'port': { 'http': { 'default': 8081 } } } } }, common.HELM_NS_OPENSTACK: { 'pod': { 'replicas': { 'ingress': self._num_controllers(), 'error_page': self._num_controllers() } } } } <NEW_LINE> if namespace in self.SUPPORTED_NAMESPACES: <NEW_LINE> <INDENT> return overrides[namespace] <NEW_LINE> <DEDENT> elif namespace: <NEW_LINE> <INDENT> raise exception.InvalidHelmNamespace(chart=self.CHART, namespace=namespace) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return overrides
Class to encapsulate helm operations for the ingress chart
62598fa51f5feb6acb162af4
class SaturationTransform(Transform): <NEW_LINE> <INDENT> def __call__(self, data, label, gt, seg_gt, seg_gt_to_compare): <NEW_LINE> <INDENT> data = cv2.cvtColor(data, cv2.COLOR_BGR2HSV) <NEW_LINE> data = data.astype(np.float32) <NEW_LINE> delta = random.uniform(self.lower, self.upper) <NEW_LINE> data[1] *= delta <NEW_LINE> data[1][data[1]>255] = 255 <NEW_LINE> data[1][data[1]<0] = 0 <NEW_LINE> data = data.astype(np.uint8) <NEW_LINE> data = cv2.cvtColor(data, cv2.COLOR_HSV2BGR) <NEW_LINE> return data, label, gt, seg_gt, seg_gt_to_compare
Transform hue Parameters: lower, upper
62598fa5a17c0f6771d5c107
class CommandList(command.BaseCommand): <NEW_LINE> <INDENT> NAME = "list" <NEW_LINE> HELP = "List metrics." <NEW_LINE> def add_arguments(self, parser): <NEW_LINE> <INDENT> parser.add_argument("glob", help="One metric name or globbing on metrics names") <NEW_LINE> parser.add_argument( "--graphite", default=False, action="store_true", help="Enable Graphite globbing", ) <NEW_LINE> <DEDENT> def run(self, accessor, opts): <NEW_LINE> <INDENT> accessor.connect() <NEW_LINE> if not opts.graphite: <NEW_LINE> <INDENT> directories_names = accessor.glob_directory_names(opts.glob) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> _, directories_names = graphite_glob( accessor, opts.glob, metrics=False, directories=True ) <NEW_LINE> <DEDENT> for directory in directories_names: <NEW_LINE> <INDENT> print("d %s" % directory) <NEW_LINE> <DEDENT> for metric in list_metrics(accessor, opts.glob, opts.graphite): <NEW_LINE> <INDENT> if metric: <NEW_LINE> <INDENT> print("m %s %s" % (metric.name, metric.metadata.as_string_dict()))
List for metrics.
62598fa599cbb53fe6830da7
class deleteRecoveryTasks_args: <NEW_LINE> <INDENT> thrift_spec = ( None, (1, TType.STRUCT, 'query', (TaskQuery, TaskQuery.thrift_spec), None, ), (2, TType.STRUCT, 'session', (SessionKey, SessionKey.thrift_spec), None, ), ) <NEW_LINE> def __init__(self, query=None, session=None,): <NEW_LINE> <INDENT> self.query = query <NEW_LINE> self.session = session <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> fastbinary.decode_binary(self, iprot.trans, (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.query = TaskQuery() <NEW_LINE> self.query.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.session = SessionKey() <NEW_LINE> self.session.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.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('deleteRecoveryTasks_args') <NEW_LINE> if self.query is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('query', TType.STRUCT, 1) <NEW_LINE> self.query.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.session is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('session', TType.STRUCT, 2) <NEW_LINE> self.session.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 __hash__(self): <NEW_LINE> <INDENT> value = 17 <NEW_LINE> value = (value * 31) ^ hash(self.query) <NEW_LINE> value = (value * 31) ^ hash(self.session) <NEW_LINE> return value <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: - query - session
62598fa556ac1b37e63020bf
class RosettaSetup: <NEW_LINE> <INDENT> def __init__(self, win, part, previous_movie = None, suffix = ""): <NEW_LINE> <INDENT> self.assy = part.assy <NEW_LINE> self.suffix = suffix <NEW_LINE> self.previous_movie = previous_movie or _stickyParams or Movie(self.assy) <NEW_LINE> self.movie = Movie(self.assy) <NEW_LINE> self.movie.filename = "RosettaDesignTest.xyz" <NEW_LINE> <DEDENT> pass
The "Run Dynamics" dialog class for setting up and launching a simulator run.
62598fa5435de62698e9bcc8
class ProtocolError(SwiftestError): <NEW_LINE> <INDENT> pass
An unexpected state was encountered in the OpenStack protocol. This is raised on many 500 conditions, for example, or cases where expected headers are missing from HTTP responses.
62598fa5d7e4931a7ef3bf6e
class Identifier(object): <NEW_LINE> <INDENT> def __init__(self, namespace=None, id=None, url=None): <NEW_LINE> <INDENT> self.namespace = namespace <NEW_LINE> self.id = id <NEW_LINE> self.url = url <NEW_LINE> <DEDENT> def to_tuple(self): <NEW_LINE> <INDENT> return (self.namespace, self.id, self.url) <NEW_LINE> <DEDENT> def is_equal(self, other): <NEW_LINE> <INDENT> return self.__class__ == other.__class__ and self.namespace == other.namespace and self.id == other.id and self.url == other.url
An identifier Attributes: namespace (:obj:`str`): namespace id (:obj:`str`): id url (:obj:`str`): URL
62598fa58e7ae83300ee8f74
class Config(object): <NEW_LINE> <INDENT> def __init__(self, config_file=None, **kwargs): <NEW_LINE> <INDENT> if config_file: <NEW_LINE> <INDENT> with open(config_file, "r") as f: <NEW_LINE> <INDENT> data = yaml.load(f.read()) or {} <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> data = {} <NEW_LINE> <DEDENT> for parameter, param_conf in CONF.items(): <NEW_LINE> <INDENT> self._assign_property(parameter, param_conf, data) <NEW_LINE> <DEDENT> for k, v in data.items(): <NEW_LINE> <INDENT> if k not in CONF: <NEW_LINE> <INDENT> setattr(self, k, v) <NEW_LINE> <DEDENT> <DEDENT> for k, v in kwargs.items(): <NEW_LINE> <INDENT> setattr(self, k, v) <NEW_LINE> <DEDENT> resolve_imports = ["inventory", "transform_function", "jinja_filters"] <NEW_LINE> for r in resolve_imports: <NEW_LINE> <INDENT> obj = self._resolve_import_from_string(kwargs.get(r, getattr(self, r))) <NEW_LINE> setattr(self, r, obj) <NEW_LINE> <DEDENT> callable_func = ["jinja_filters"] <NEW_LINE> for c in callable_func: <NEW_LINE> <INDENT> func = getattr(self, c) <NEW_LINE> if func: <NEW_LINE> <INDENT> setattr(self, c, func()) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def string_to_bool(self, v): <NEW_LINE> <INDENT> if v.lower() in ["false", "no", "n", "off", "0"]: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> def _assign_property(self, parameter, param_conf, data): <NEW_LINE> <INDENT> v = None <NEW_LINE> if param_conf["type"] in ("bool", "int", "str"): <NEW_LINE> <INDENT> env = param_conf.get("env") or "BRIGADE_" + parameter.upper() <NEW_LINE> v = os.environ.get(env) <NEW_LINE> <DEDENT> if v is None: <NEW_LINE> <INDENT> v = data.get(parameter, param_conf["default"]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if param_conf["type"] == "bool": <NEW_LINE> <INDENT> v = self.string_to_bool(v) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> v = types[param_conf["type"]](v) <NEW_LINE> <DEDENT> <DEDENT> setattr(self, parameter, v) <NEW_LINE> <DEDENT> def get(self, parameter, env=None, default=None, parameter_type="str", root=""): <NEW_LINE> <INDENT> value = os.environ.get(env) if env else None <NEW_LINE> if value is None: <NEW_LINE> <INDENT> if root: <NEW_LINE> <INDENT> d = getattr(self, root, {}) <NEW_LINE> value = d.get(parameter, default) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> value = getattr(self, parameter, default) <NEW_LINE> <DEDENT> <DEDENT> if parameter_type in [bool, "bool"]: <NEW_LINE> <INDENT> if not isinstance(value, bool): <NEW_LINE> <INDENT> value = self.string_to_bool(value) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> value = types[str(parameter_type)](value) <NEW_LINE> <DEDENT> return value <NEW_LINE> <DEDENT> def _resolve_import_from_string(self, import_path): <NEW_LINE> <INDENT> if not import_path or callable(import_path): <NEW_LINE> <INDENT> return import_path <NEW_LINE> <DEDENT> module_name = ".".join(import_path.split(".")[:-1]) <NEW_LINE> obj_name = import_path.split(".")[-1] <NEW_LINE> module = importlib.import_module(module_name) <NEW_LINE> return getattr(module, obj_name)
This object handles the configuration of Nornir. Arguments: config_file(``str``): Yaml configuration file.
62598fa538b623060ffa8f69
class RandomProjectionHasher(Hasher): <NEW_LINE> <INDENT> def __init__(self, feat_dim, sig_dim): <NEW_LINE> <INDENT> super(RandomProjectionHasher, self).__init__(feat_dim, sig_dim) <NEW_LINE> self.planes = self._init_planes() <NEW_LINE> <DEDENT> def _init_planes(self): <NEW_LINE> <INDENT> return randn(self.sig_dim, self.feat_dim) <NEW_LINE> <DEDENT> def hash(self, feature): <NEW_LINE> <INDENT> return bitarray([val > 0 for val in np.dot(self.planes, feature)])
RandomProjectionHasher generates random hyperplanes and make projections from features onto these planes to generate hash values. It's used together with cosine similarity measure
62598fa544b2445a339b68d8
class Listing(RNode): <NEW_LINE> <INDENT> KIND = "Listing" <NEW_LINE> SCHEMA = RSchema.from_dict({ "modhash": (str, True), "dist": (str, True), "children": (list, False), "after": (str, True), "before": (str, True), }) <NEW_LINE> def __init__(self, _d): <NEW_LINE> <INDENT> super().__init__(_d) <NEW_LINE> <DEDENT> def iter_children(self, no_more=False): <NEW_LINE> <INDENT> d_children = self.data.get("children") <NEW_LINE> children = ( RNode.resolve(i) for i in d_children ) <NEW_LINE> include = lambda node: True <NEW_LINE> if no_more: <NEW_LINE> <INDENT> include = lambda node: type(node) != More <NEW_LINE> <DEDENT> return ( child for child in children if include(child) ) <NEW_LINE> <DEDENT> def get_children(self): <NEW_LINE> <INDENT> children = list(self.iter_children()) <NEW_LINE> return children
Internal RNode used for linkage of data structure.
62598fa59c8ee823130400d9
@base.vectorize <NEW_LINE> class divc(base.Instruction): <NEW_LINE> <INDENT> __slots__ = [] <NEW_LINE> code = base.opcodes['DIVC'] <NEW_LINE> arg_format = ['cw', 'c', 'c'] <NEW_LINE> def execute(self): <NEW_LINE> <INDENT> self.args[0].value = self.args[1].value * pow(self.args[2].value, program.P - 2, program.P) % program.P
Clear division c_i=c_j/c_k. This instruction is vectorizable
62598fa57cff6e4e811b58fc
class OrOp(object): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def create(cls, opb, loc, values): <NEW_LINE> <INDENT> state = mlir.OperationState(loc, "tfp.Or") <NEW_LINE> state.addTypes( [UnrankedTensorType.get(IntegerType.get(1, opb.getContext()))]) <NEW_LINE> state.addOperands(values) <NEW_LINE> return opb.createOperation(state)
tfp.Or(ops...) This is like tf.Any, except that the first dimension is opened into `ops`. Returns a tensor of 1-bit integers which is "Logical OR" of the coressponding elements in ops...
62598fa55f7d997b871f934a
class Stream2EventsStream: <NEW_LINE> <INDENT> max_streambuf = 5 <NEW_LINE> count_streambuf = 0 <NEW_LINE> collected_buffer = b'' <NEW_LINE> pdata = {} <NEW_LINE> def __init__(self, normalizedHandler, slicerHandler): <NEW_LINE> <INDENT> self.nh = normalizedHandler <NEW_LINE> self.sh = slicerHandler <NEW_LINE> <DEDENT> def _flush_collected_stream(self): <NEW_LINE> <INDENT> self.count_streambuf = 0 <NEW_LINE> self.collected_buffer = b'' <NEW_LINE> <DEDENT> def get_slicer(self, slicer_id): <NEW_LINE> <INDENT> return self.nh.get_slicers()[slicer_id] <NEW_LINE> <DEDENT> def _get_root_slicer(self): <NEW_LINE> <INDENT> return self.get_slicer(0) <NEW_LINE> <DEDENT> def _normalize_subslice(self, slicer, data): <NEW_LINE> <INDENT> s = self.sh.get_slicer(slicer['type']) <NEW_LINE> (n_events, sliced_buf) = s.slice_buffer(slicer, data, None) <NEW_LINE> return (n_events, sliced_buf) <NEW_LINE> <DEDENT> def _normalize_line(self, slicer, main_sliced_buf): <NEW_LINE> <INDENT> line_n = 0 <NEW_LINE> for line in main_sliced_buf: <NEW_LINE> <INDENT> col_n = 0 <NEW_LINE> for col in slicer['columns']: <NEW_LINE> <INDENT> if col['slicer'] is not None: <NEW_LINE> <INDENT> slicer_id = col['slicer-id'] <NEW_LINE> child_slicer = self.get_slicer(slicer_id) <NEW_LINE> (sub_n_events, subsliced_buf) = self._normalize_subslice(child_slicer, line[col_n].encode('utf-8')) <NEW_LINE> line.pop(col_n) <NEW_LINE> for el in subsliced_buf.__reversed__(): <NEW_LINE> <INDENT> line.insert(col_n, el) <NEW_LINE> <DEDENT> <DEDENT> col_n += 1 <NEW_LINE> <DEDENT> line_n += 1 <NEW_LINE> <DEDENT> return main_sliced_buf <NEW_LINE> <DEDENT> def _normalize(self, slicer): <NEW_LINE> <INDENT> s = self.sh.get_slicer(slicer['type']) <NEW_LINE> (n_events, main_sliced_buf) = s.slice_buffer(slicer, self.collected_buffer, self.pdata) <NEW_LINE> main_sliced_buf = self._normalize_line(slicer, main_sliced_buf) <NEW_LINE> return (n_events, main_sliced_buf) <NEW_LINE> <DEDENT> def _need_to_collect_more(self, data): <NEW_LINE> <INDENT> self.collected_buffer += data <NEW_LINE> self.count_streambuf += 1 <NEW_LINE> return [] <NEW_LINE> <DEDENT> def get(self, data, terminate=False): <NEW_LINE> <INDENT> n_events = 0 <NEW_LINE> normalized = [] <NEW_LINE> if not terminate: <NEW_LINE> <INDENT> if self.count_streambuf == self.max_streambuf: <NEW_LINE> <INDENT> self.collected_buffer += data <NEW_LINE> (n_events, normalized) = self._normalize(self._get_root_slicer()) <NEW_LINE> self._flush_collected_stream() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> normalized = self._need_to_collect_more(data) <NEW_LINE> n_events = 0 <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.collected_buffer += data <NEW_LINE> try: <NEW_LINE> <INDENT> (n_events, normalized) = self._normalize(self._get_root_slicer()) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> print("Nothing was normalized") <NEW_LINE> <DEDENT> self._flush_collected_stream() <NEW_LINE> <DEDENT> return (n_events, normalized)
This is a major class, transforming a stream of data (coming from a file, socket etc.) into a normalized array (event)
62598fa5460517430c431fc5
class CompositeOverlay(ViewableElement, Composable): <NEW_LINE> <INDENT> _deep_indexable = True <NEW_LINE> def hist(self, dimension=None, num_bins=20, bin_range=None, adjoin=True, index=None, show_legend=False, **kwargs): <NEW_LINE> <INDENT> main_layer_int_index = getattr(self, "main_layer", None) or 0 <NEW_LINE> if index is not None: <NEW_LINE> <INDENT> valid_ind = isinstance(index, int) and (0 <= index < len(self)) <NEW_LINE> valid_label = index in [el.label for el in self] <NEW_LINE> if not any([valid_ind, valid_label]): <NEW_LINE> <INDENT> raise TypeError("Please supply a suitable index or label for the histogram data") <NEW_LINE> <DEDENT> if valid_ind: <NEW_LINE> <INDENT> main_layer_int_index = index <NEW_LINE> <DEDENT> if valid_label: <NEW_LINE> <INDENT> main_layer_int_index = self.keys().index(index) <NEW_LINE> <DEDENT> <DEDENT> if dimension is None: <NEW_LINE> <INDENT> dimension = [dim.name for dim in self.values()[main_layer_int_index].kdims] <NEW_LINE> <DEDENT> hists_per_dim = { dim: OrderedDict([ ( elem_key, elem.hist( adjoin=False, dimension=dim, bin_range=bin_range, num_bins=num_bins, **kwargs ) ) for i, (elem_key, elem) in enumerate(self.items()) if (index is None) or (getattr(elem, "label", None) == index) or (index == i) ]) for dim in dimension } <NEW_LINE> hists_overlay_per_dim = { dim: self.clone(hists).opts(show_legend=show_legend) for dim, hists in hists_per_dim.items() } <NEW_LINE> if adjoin: <NEW_LINE> <INDENT> layout = self <NEW_LINE> for dim in reversed(self.values()[main_layer_int_index].kdims): <NEW_LINE> <INDENT> if dim.name in hists_overlay_per_dim: <NEW_LINE> <INDENT> layout = layout << hists_overlay_per_dim[dim.name] <NEW_LINE> <DEDENT> <DEDENT> layout.main_layer = main_layer_int_index <NEW_LINE> <DEDENT> elif len(dimension) > 1: <NEW_LINE> <INDENT> layout = Layout(list(hists_overlay_per_dim.values())) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> layout = hists_overlay_per_dim[0] <NEW_LINE> <DEDENT> return layout <NEW_LINE> <DEDENT> def dimension_values(self, dimension, expanded=True, flat=True): <NEW_LINE> <INDENT> values = [] <NEW_LINE> found = False <NEW_LINE> for el in self: <NEW_LINE> <INDENT> if dimension in el.dimensions(label=True): <NEW_LINE> <INDENT> values.append(el.dimension_values(dimension)) <NEW_LINE> found = True <NEW_LINE> <DEDENT> <DEDENT> if not found: <NEW_LINE> <INDENT> return super().dimension_values(dimension, expanded, flat) <NEW_LINE> <DEDENT> values = [v for v in values if v is not None and len(v)] <NEW_LINE> if not values: <NEW_LINE> <INDENT> return np.array() <NEW_LINE> <DEDENT> vals = np.concatenate(values) <NEW_LINE> return vals if expanded else unique_array(vals)
CompositeOverlay provides a common baseclass for Overlay classes.
62598fa53617ad0b5ee06026
class ReportSection(object): <NEW_LINE> <INDENT> def __init__(self, view, generator): <NEW_LINE> <INDENT> self.view = view <NEW_LINE> self.generator = generator <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.view(self.generator())
A Report Section A report section contains a generator and a top-level view. When something attempts to serialize the section by calling str() on it, the section runs the generator and calls the view on the resulting model. .. seealso:: Class :class:`BasicReport` :func:`BasicReport.add_section` :param view: the top-level view for this section :param generator: the generator for this section which could be any callable object which takes no parameters and returns a data model
62598fa56aa9bd52df0d4d9d
class Match(db.Model): <NEW_LINE> <INDENT> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> user_id = db.Column(db.Integer, db.ForeignKey('user.id')) <NEW_LINE> project_id = db.Column(db.Integer, db.ForeignKey('project.id')) <NEW_LINE> result = db.Column(db.Integer, nullable=False) <NEW_LINE> def __init__(self, user_id, project_id): <NEW_LINE> <INDENT> self.user_id = user_id <NEW_LINE> self.project_id = project_id <NEW_LINE> self.result = 1 <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<Match with id %r between user %r and project %r>" % (self.id, self.user_id, self.project_id)
This class is the database model for the Match between a L{User} and a L{Project}.
62598fa54428ac0f6e6583f5
class ArgValidatorPath(ArgValidatorStr): <NEW_LINE> <INDENT> def __init__(self, name, required=False, default_value=None): <NEW_LINE> <INDENT> ArgValidatorStr.__init__(self, name, required, default_value, None) <NEW_LINE> <DEDENT> def _validate_impl(self, value, name): <NEW_LINE> <INDENT> ArgValidatorStr._validate_impl(self, value, name) <NEW_LINE> if posixpath.isabs(value) is False: <NEW_LINE> <INDENT> raise ValidationError( name, "value '%s' is not a valid posix absolute path" % (value), ) <NEW_LINE> <DEDENT> return value
Valides that the value is a valid posix absolute path
62598fa5236d856c2adc93a5
class DocumentWatchTests(TestCaseBase): <NEW_LINE> <INDENT> fixtures = ['users.json'] <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> super(DocumentWatchTests, self).setUp() <NEW_LINE> self.document = _create_document() <NEW_LINE> self.client.login(username='rrosario', password='testpass') <NEW_LINE> product(save=True) <NEW_LINE> <DEDENT> def test_watch_GET_405(self): <NEW_LINE> <INDENT> response = get(self.client, 'wiki.document_watch', args=[self.document.slug]) <NEW_LINE> eq_(405, response.status_code) <NEW_LINE> <DEDENT> def test_unwatch_GET_405(self): <NEW_LINE> <INDENT> response = get(self.client, 'wiki.document_unwatch', args=[self.document.slug]) <NEW_LINE> eq_(405, response.status_code) <NEW_LINE> <DEDENT> def test_watch_unwatch(self): <NEW_LINE> <INDENT> user_ = User.objects.get(username='rrosario') <NEW_LINE> response = post(self.client, 'wiki.document_watch', args=[self.document.slug]) <NEW_LINE> eq_(200, response.status_code) <NEW_LINE> assert EditDocumentEvent.is_notifying(user_, self.document), 'Watch was not created' <NEW_LINE> response = post(self.client, 'wiki.document_unwatch', args=[self.document.slug]) <NEW_LINE> eq_(200, response.status_code) <NEW_LINE> assert not EditDocumentEvent.is_notifying(user_, self.document), 'Watch was not destroyed'
Tests for un/subscribing to document edit notifications.
62598fa54e4d5625663722f8
class SampleView(grok.View): <NEW_LINE> <INDENT> grok.context(IISBNValidationResult) <NEW_LINE> grok.require('zope2.View')
sample view class
62598fa566673b3332c3029d
class GenomeDownloader(object): <NEW_LINE> <INDENT> def __init__(self, config, ftp_host, ftp_path, genome, update_progress): <NEW_LINE> <INDENT> self.ftp_util = FTPUtil(config) <NEW_LINE> self.local_dir = os.path.join(config.download_dir, genome) <NEW_LINE> self.ftp_host = ftp_host <NEW_LINE> self.ftp_path = ftp_path <NEW_LINE> self.genome = genome <NEW_LINE> self.update_progress = update_progress <NEW_LINE> <DEDENT> def download(self): <NEW_LINE> <INDENT> self._download_file(self.get_ftp_filename(), self.get_local_path()) <NEW_LINE> <DEDENT> def _download_file(self, filename, out_filename): <NEW_LINE> <INDENT> self.update_progress('Downloading: ' + filename) <NEW_LINE> self.ftp_util.download_ftp(self.ftp_host, self.get_ftp_dir(), filename, self.genome) <NEW_LINE> <DEDENT> def get_ftp_dir(self): <NEW_LINE> <INDENT> return os.path.dirname(self.ftp_path) <NEW_LINE> <DEDENT> def get_ftp_filename(self): <NEW_LINE> <INDENT> return os.path.basename(self.ftp_path) <NEW_LINE> <DEDENT> def get_local_path(self): <NEW_LINE> <INDENT> return os.path.join(self.local_dir, self.get_ftp_filename()) <NEW_LINE> <DEDENT> def get_url(self): <NEW_LINE> <INDENT> return "{}/{}".format(self.ftp_host, self.ftp_path)
Retrieves 2bit genome file from via FTP.
62598fa5851cf427c66b819c
class PasswordResetConfirmView(CurrentAppMixin, generic.UpdateView): <NEW_LINE> <INDENT> template_name = "registration/password_reset_confirm.html" <NEW_LINE> form_class = SetPasswordForm <NEW_LINE> success_url = reverse_lazy('django.contrib.auth.views.password_reset_complete') <NEW_LINE> token_generator = default_token_generator <NEW_LINE> current_app = None <NEW_LINE> extra_context = None <NEW_LINE> def get_object(self, queryset=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> pk = base36_to_int(self.kwargs['uidb36']) <NEW_LINE> user = User.objects.get(pk=pk) <NEW_LINE> <DEDENT> except (ValueError, User.DoesNotExist): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if not self.token_generator.check_token(user, self.kwargs['token']): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return user <NEW_LINE> <DEDENT> def get_form_kwargs(self): <NEW_LINE> <INDENT> kwargs = super(PasswordResetConfirmView, self).get_form_kwargs() <NEW_LINE> kwargs['user'] = kwargs.pop('instance') <NEW_LINE> return kwargs <NEW_LINE> <DEDENT> def form_valid(self, form): <NEW_LINE> <INDENT> if self.object is None: <NEW_LINE> <INDENT> return self.form_invalid(form) <NEW_LINE> <DEDENT> return super(PasswordResetConfirmView, self).form_valid(form) <NEW_LINE> <DEDENT> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super(PasswordResetConfirmView, self).get_context_data(**kwargs) <NEW_LINE> context.update({ 'validlink': self.object is not None }) <NEW_LINE> context.update(self.extra_context or {}) <NEW_LINE> return context <NEW_LINE> <DEDENT> @method_decorator(sensitive_post_parameters()) <NEW_LINE> @method_decorator(never_cache) <NEW_LINE> def dispatch(self, request, *args, **kwargs): <NEW_LINE> <INDENT> return super(PasswordResetConfirmView, self).dispatch(request, *args, **kwargs)
Check that the given token is valid then prompt the user for a new pasword.
62598fa58e71fb1e983bb986
class ProtectedFileSystemStorage(FileSystemStorage): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> kwargs["location"] = PROTECTED_MEDIA_ROOT <NEW_LINE> kwargs["base_url"] = PROTECTED_MEDIA_URL <NEW_LINE> super(ProtectedFileSystemStorage, self).__init__(*args, **kwargs)
A class to manage protected files. We have to override the methods in the FileSystemStorage class which are decorated with cached_property for this class to work as intended.
62598fa592d797404e388acf
class AddCaseForm(BaseAddCaseForm, BaseCaseVersionForm, BaseCaseForm): <NEW_LINE> <INDENT> def clean(self): <NEW_LINE> <INDENT> BaseCaseForm.clean(self) <NEW_LINE> BaseAddCaseForm.clean(self) <NEW_LINE> return self.cleaned_data <NEW_LINE> <DEDENT> def save(self): <NEW_LINE> <INDENT> assert self.is_valid() <NEW_LINE> version_kwargs = self.cleaned_data.copy() <NEW_LINE> product = version_kwargs.pop("product") <NEW_LINE> idprefix = version_kwargs.pop("idprefix") <NEW_LINE> self.save_new_tags(product) <NEW_LINE> case = model.Case.objects.create( product=product, user=self.user, idprefix=idprefix, ) <NEW_LINE> version_kwargs["case"] = case <NEW_LINE> version_kwargs["user"] = self.user <NEW_LINE> del version_kwargs["add_tags"] <NEW_LINE> del version_kwargs["add_attachment"] <NEW_LINE> initial_suite = version_kwargs.pop("initial_suite", None) <NEW_LINE> if initial_suite: <NEW_LINE> <INDENT> model.SuiteCase.objects.create( case=case, suite=initial_suite, user=self.user) <NEW_LINE> <DEDENT> productversions = [version_kwargs.pop("productversion")] <NEW_LINE> if version_kwargs.pop("and_later_versions"): <NEW_LINE> <INDENT> productversions.extend(product.versions.filter( order__gt=productversions[0].order)) <NEW_LINE> <DEDENT> for productversion in productversions: <NEW_LINE> <INDENT> this_version_kwargs = version_kwargs.copy() <NEW_LINE> this_version_kwargs["productversion"] = productversion <NEW_LINE> caseversion = model.CaseVersion.objects.create( **this_version_kwargs) <NEW_LINE> steps_formset = StepFormSet( data=self.data, instance=caseversion) <NEW_LINE> steps_formset.save(user=self.user) <NEW_LINE> self.save_tags(caseversion) <NEW_LINE> self.save_attachments(caseversion) <NEW_LINE> <DEDENT> return case
Form for adding a new single case and some number of versions.
62598fa5a17c0f6771d5c109
class Subscription(AbstractSubscription): <NEW_LINE> <INDENT> class Meta(AbstractSubscription.Meta): <NEW_LINE> <INDENT> swappable = 'SUBSCRIPTION_MODEL'
Default Subscription Model. If you want to change this, check out AbstractSubscription
62598fa599cbb53fe6830da9
class ConsoleProtocol(abc.ABC): <NEW_LINE> <INDENT> @abc.abstractmethod <NEW_LINE> def read(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def write(self, data: bytes): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def sendline(self, line: str): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def sendcontrol(self, char: str): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def expect(self, pattern: str): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> class Client(abc.ABC): <NEW_LINE> <INDENT> @abc.abstractmethod <NEW_LINE> def get_console_matches(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def notify_console_match(self, pattern, match): <NEW_LINE> <INDENT> raise NotImplementedError
Abstract class for the ConsoleProtocol
62598fa52c8b7c6e89bd369a
class DataTypeDefinitionTest(test_lib.BaseTestCase): <NEW_LINE> <INDENT> def testIsComposite(self): <NEW_LINE> <INDENT> data_type_definition = data_types.DataTypeDefinition( 'int32', aliases=['LONG', 'LONG32'], description='signed 32-bit integer') <NEW_LINE> result = data_type_definition.IsComposite() <NEW_LINE> self.assertFalse(result)
Data type definition tests.
62598fa599fddb7c1ca62d52
class TutorGroup(models.Model): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = _("Kleingruppe") <NEW_LINE> verbose_name_plural = _("Kleingruppen") <NEW_LINE> ordering = ['group_category', 'name'] <NEW_LINE> unique_together = ('ophase', 'name') <NEW_LINE> <DEDENT> ophase = models.ForeignKey(Ophase, models.CASCADE) <NEW_LINE> name = models.CharField(max_length=50, verbose_name=_("Gruppenname")) <NEW_LINE> tutors = models.ManyToManyField(Person, blank=True, verbose_name=_("Tutoren")) <NEW_LINE> group_category = models.ForeignKey(OphaseCategory, models.CASCADE, verbose_name=_("Gruppenkategorie")) <NEW_LINE> picture = models.FileField(upload_to='grouppicture/', blank=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> """Get the file name of the picture""" <NEW_LINE> def get_picture_name(self): <NEW_LINE> <INDENT> return self.picture.name.split('/')[-1].split('.')[0]
A group of students guided by tutors.
62598fa563d6d428bbee2686
class BaseLMI(object): <NEW_LINE> <INDENT> def __new__(cls, lhs, rhs, rel_cls, assert_symmetry=True): <NEW_LINE> <INDENT> lhs = sympify(lhs) <NEW_LINE> rhs = sympify(rhs) <NEW_LINE> if assert_symmetry: <NEW_LINE> <INDENT> if lhs.is_Matrix and hasattr(lhs, 'is_symmetric') and not lhs.is_symmetric(): <NEW_LINE> <INDENT> raise NonSymmetricMatrixError('lhs matrix is not symmetric') <NEW_LINE> <DEDENT> if rhs.is_Matrix and hasattr(rhs, 'is_symmetric') and not rhs.is_symmetric(): <NEW_LINE> <INDENT> raise NonSymmetricMatrixError('rsh matrix is not symmetric') <NEW_LINE> <DEDENT> <DEDENT> if lhs.is_Matrix and rhs.is_Matrix: <NEW_LINE> <INDENT> if lhs.shape != rhs.shape: <NEW_LINE> <INDENT> raise ShapeError('LMI matrices have different shapes') <NEW_LINE> <DEDENT> <DEDENT> elif not ((lhs.is_Matrix and rhs.is_zero) or (lhs.is_zero and rhs.is_Matrix)): <NEW_LINE> <INDENT> raise ValueError('LMI sides must be two matrices ' 'or a matrix and a zero') <NEW_LINE> <DEDENT> return rel_cls.__new__(cls, lhs, rhs) <NEW_LINE> <DEDENT> def canonical(self): <NEW_LINE> <INDENT> if self.gts.is_Matrix: <NEW_LINE> <INDENT> if self.lts.is_Matrix: <NEW_LINE> <INDENT> diff = self.gts - self.lts <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if isinstance(self, (LMI_PD, LMI_PSD)): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> diff = self.gts <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> diff = -self.lts <NEW_LINE> <DEDENT> diff = block_collapse(diff) <NEW_LINE> if self.is_strict: <NEW_LINE> <INDENT> return LMI_PD(diff, 0) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return LMI_PSD(diff, 0) <NEW_LINE> <DEDENT> <DEDENT> def expanded(self, variables): <NEW_LINE> <INDENT> if self.lhs.is_Matrix: <NEW_LINE> <INDENT> lhs = lm_sym_expanded(self.lhs, variables) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> lhs = self.lhs <NEW_LINE> <DEDENT> if self.rhs.is_Matrix: <NEW_LINE> <INDENT> rhs = lm_sym_expanded(self.rhs, variables) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> rhs = self.rhs <NEW_LINE> <DEDENT> return self.func(lhs, rhs) <NEW_LINE> <DEDENT> def doit(self, **hints): <NEW_LINE> <INDENT> if hints.get('deep', False): <NEW_LINE> <INDENT> lhs = self.lhs.doit(**hints) <NEW_LINE> rhs = self.lhs.doit(**hints) <NEW_LINE> return self.func(lhs, rhs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self
Not intended for general use BaseLMI is used so that LMI_* classes can share functions.
62598fa5009cb60464d013f9
class IOLogRecordResumeTests(TestCaseWithParameters): <NEW_LINE> <INDENT> parameter_names = ('resume_cls',) <NEW_LINE> parameter_values = ((SessionResumeHelper1,), (SessionResumeHelper2,), (SessionResumeHelper3,)) <NEW_LINE> def test_build_IOLogRecord_missing_delay(self): <NEW_LINE> <INDENT> with self.assertRaises(CorruptedSessionError): <NEW_LINE> <INDENT> self.parameters.resume_cls._build_IOLogRecord([]) <NEW_LINE> <DEDENT> <DEDENT> def test_build_IOLogRecord_bad_type_for_delay(self): <NEW_LINE> <INDENT> with self.assertRaises(CorruptedSessionError): <NEW_LINE> <INDENT> self.parameters.resume_cls._build_IOLogRecord([0, 'stdout', '']) <NEW_LINE> <DEDENT> <DEDENT> def test_build_IOLogRecord_negative_delay(self): <NEW_LINE> <INDENT> with self.assertRaises(CorruptedSessionError): <NEW_LINE> <INDENT> self.parameters.resume_cls._build_IOLogRecord([-1.0, 'stdout', '']) <NEW_LINE> <DEDENT> <DEDENT> def test_build_IOLogRecord_missing_stream_name(self): <NEW_LINE> <INDENT> with self.assertRaises(CorruptedSessionError): <NEW_LINE> <INDENT> self.parameters.resume_cls._build_IOLogRecord([0.0]) <NEW_LINE> <DEDENT> <DEDENT> def test_build_IOLogRecord_bad_type_stream_name(self): <NEW_LINE> <INDENT> with self.assertRaises(CorruptedSessionError): <NEW_LINE> <INDENT> self.parameters.resume_cls._build_IOLogRecord([0.0, 1]) <NEW_LINE> <DEDENT> <DEDENT> def test_build_IOLogRecord_bad_value_stream_name(self): <NEW_LINE> <INDENT> with self.assertRaises(CorruptedSessionError): <NEW_LINE> <INDENT> self.parameters.resume_cls._build_IOLogRecord([0.0, "foo", ""]) <NEW_LINE> <DEDENT> <DEDENT> def test_build_IOLogRecord_missing_data(self): <NEW_LINE> <INDENT> with self.assertRaises(CorruptedSessionError): <NEW_LINE> <INDENT> self.parameters.resume_cls._build_IOLogRecord([0.0, 'stdout']) <NEW_LINE> <DEDENT> <DEDENT> def test_build_IOLogRecord_non_ascii_data(self): <NEW_LINE> <INDENT> with self.assertRaises(CorruptedSessionError) as boom: <NEW_LINE> <INDENT> self.parameters.resume_cls._build_IOLogRecord( [0.0, 'stdout', '\uFFFD']) <NEW_LINE> <DEDENT> self.assertIsInstance(boom.exception.__context__, UnicodeEncodeError) <NEW_LINE> <DEDENT> def test_build_IOLogRecord_non_base64_ascii_data(self): <NEW_LINE> <INDENT> with self.assertRaises(CorruptedSessionError) as boom: <NEW_LINE> <INDENT> self.parameters.resume_cls._build_IOLogRecord( [0.0, 'stdout', '==broken']) <NEW_LINE> <DEDENT> self.assertIsInstance(boom.exception.__context__, binascii.Error) <NEW_LINE> <DEDENT> def test_build_IOLogRecord_values(self): <NEW_LINE> <INDENT> record = self.parameters.resume_cls._build_IOLogRecord( [1.5, 'stderr', 'dGhpcyB3b3Jrcw==']) <NEW_LINE> self.assertAlmostEqual(record.delay, 1.5) <NEW_LINE> self.assertEqual(record.stream_name, 'stderr') <NEW_LINE> self.assertEqual(record.data, b"this works")
Tests for :class:`~plainbox.impl.session.resume.SessionResumeHelper1`, :class:`~plainbox.impl.session.resume.SessionResumeHelper2' and :class:`~plainbox.impl.session.resume.SessionResumeHelper3' and how they handle resuming IOLogRecord objects
62598fa53317a56b869be4b4
class ResourceVariableSaveable(SaveableObject): <NEW_LINE> <INDENT> def __init__(self, var, slice_spec, name): <NEW_LINE> <INDENT> self._var_device = var.device <NEW_LINE> self._var_shape = var.shape <NEW_LINE> if isinstance(var, ops.Tensor): <NEW_LINE> <INDENT> self.handle_op = var.op.inputs[0] <NEW_LINE> tensor = var <NEW_LINE> <DEDENT> elif isinstance(var, resource_variable_ops.ResourceVariable): <NEW_LINE> <INDENT> def _read_variable_closure(v): <NEW_LINE> <INDENT> def f(): <NEW_LINE> <INDENT> with ops.device(v.device): <NEW_LINE> <INDENT> x = v.read_value() <NEW_LINE> with ops.device("/device:CPU:0"): <NEW_LINE> <INDENT> return array_ops.identity(x) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return f <NEW_LINE> <DEDENT> self.handle_op = var.handle <NEW_LINE> tensor = _read_variable_closure(var) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError( "Saveable is neither a resource variable nor a read operation." " Got: %s" % repr(var)) <NEW_LINE> <DEDENT> spec = BaseSaverBuilder.SaveSpec(tensor, slice_spec, name, dtype=var.dtype) <NEW_LINE> super(BaseSaverBuilder.ResourceVariableSaveable, self).__init__( var, [spec], name) <NEW_LINE> <DEDENT> def restore(self, restored_tensors, restored_shapes): <NEW_LINE> <INDENT> restored_tensor = restored_tensors[0] <NEW_LINE> if restored_shapes is not None: <NEW_LINE> <INDENT> restored_tensor = array_ops.reshape(restored_tensor, restored_shapes[0]) <NEW_LINE> <DEDENT> with ops.device(self._var_device): <NEW_LINE> <INDENT> restored_tensor = array_ops.identity(restored_tensor) <NEW_LINE> return resource_variable_ops.shape_safe_assign_variable_handle( self.handle_op, self._var_shape, restored_tensor)
SaveableObject implementation that handles ResourceVariables.
62598fa5435de62698e9bcca
class MetricAbstractModel(models.Model): <NEW_LINE> <INDENT> time_start = models.DateTimeField() <NEW_LINE> time_end = models.DateTimeField() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> abstract = True
Metric Abstract Model
62598fa5eab8aa0e5d30bc5e
class hierarchy_info_t(object): <NEW_LINE> <INDENT> def __init__(self, related_class=None, access=None, is_virtual=False): <NEW_LINE> <INDENT> if related_class: <NEW_LINE> <INDENT> assert(isinstance(related_class, class_t)) <NEW_LINE> <DEDENT> self._related_class = related_class <NEW_LINE> if access: <NEW_LINE> <INDENT> assert(access in ACCESS_TYPES.ALL) <NEW_LINE> <DEDENT> self._access = access <NEW_LINE> self._is_virtual = is_virtual <NEW_LINE> self._declaration_path = None <NEW_LINE> self._declaration_path_hash = None <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, hierarchy_info_t): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return (self.declaration_path_hash == other.declaration_path_hash) and self._declaration_path == other._declaration_path and self._access == other._access and self._is_virtual == other._is_virtual <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return self.declaration_path_hash <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self.__eq__(other) <NEW_LINE> <DEDENT> def __lt__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, self.__class__): <NEW_LINE> <INDENT> return self.__class__.__name__ < other.__class__.__name__ <NEW_LINE> <DEDENT> return (self.declaration_path, self.access, self.is_virtual) < (other.declaration_path, other.access, other.is_virtual) <NEW_LINE> <DEDENT> @property <NEW_LINE> def related_class(self): <NEW_LINE> <INDENT> return self._related_class <NEW_LINE> <DEDENT> @related_class.setter <NEW_LINE> def related_class(self, new_related_class): <NEW_LINE> <INDENT> if new_related_class: <NEW_LINE> <INDENT> assert(isinstance(new_related_class, class_t)) <NEW_LINE> <DEDENT> self._related_class = new_related_class <NEW_LINE> self._declaration_path = None <NEW_LINE> self._declaration_path_hash = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def access(self): <NEW_LINE> <INDENT> return self._access <NEW_LINE> <DEDENT> @access.setter <NEW_LINE> def access(self, new_access): <NEW_LINE> <INDENT> assert(new_access in ACCESS_TYPES.ALL) <NEW_LINE> self._access = new_access <NEW_LINE> <DEDENT> @property <NEW_LINE> def access_type(self): <NEW_LINE> <INDENT> return self.access <NEW_LINE> <DEDENT> @access_type.setter <NEW_LINE> def access_type(self, new_access_type): <NEW_LINE> <INDENT> self.access = new_access_type <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_virtual(self): <NEW_LINE> <INDENT> return self._is_virtual <NEW_LINE> <DEDENT> @is_virtual.setter <NEW_LINE> def is_virtual(self, new_is_virtual): <NEW_LINE> <INDENT> self._is_virtual = new_is_virtual <NEW_LINE> <DEDENT> @property <NEW_LINE> def declaration_path(self): <NEW_LINE> <INDENT> if self._declaration_path is None: <NEW_LINE> <INDENT> self._declaration_path = declaration_utils.declaration_path( self.related_class) <NEW_LINE> <DEDENT> return self._declaration_path <NEW_LINE> <DEDENT> @property <NEW_LINE> def declaration_path_hash(self): <NEW_LINE> <INDENT> if self._declaration_path_hash is None: <NEW_LINE> <INDENT> self._declaration_path_hash = hash(tuple(self.declaration_path)) <NEW_LINE> <DEDENT> return self._declaration_path_hash
describes class relationship
62598fa5d6c5a102081e201c
class PersistentConsoleToggleCommand(WindowCommand): <NEW_LINE> <INDENT> def run(self): <NEW_LINE> <INDENT> settings = sublime.load_settings("Persistent Console.sublime-settings") <NEW_LINE> enablePackage = settings.get("enable") <NEW_LINE> verb = "disabled" if enablePackage is True else "enabled" <NEW_LINE> settings.set("enable", not enablePackage) <NEW_LINE> sublime.save_settings("Persistent Console.sublime-settings") <NEW_LINE> self.window.status_message("Persistent Console {}".format(verb))
Checks whether to show console on new window.
62598fa55f7d997b871f934b
class ErrorDetails(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'code': {'key': 'code', 'type': 'str'}, 'target': {'key': 'target', 'type': 'str'}, 'message': {'key': 'message', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, code: Optional[str] = None, target: Optional[str] = None, message: Optional[str] = None, **kwargs ): <NEW_LINE> <INDENT> super(ErrorDetails, self).__init__(**kwargs) <NEW_LINE> self.code = code <NEW_LINE> self.target = target <NEW_LINE> self.message = message
Common error details representation. :ivar code: Error code. :vartype code: str :ivar target: Error target. :vartype target: str :ivar message: Error message. :vartype message: str
62598fa55fdd1c0f98e5de6d
class CEAccessTest: <NEW_LINE> <INDENT> def _getAccessParams( self, element ): <NEW_LINE> <INDENT> _basePath = 'Resources/Sites' <NEW_LINE> domains = gConfig.getSections( _basePath ) <NEW_LINE> if not domains[ 'OK' ]: <NEW_LINE> <INDENT> return domains <NEW_LINE> <DEDENT> domains = domains[ 'Value' ] <NEW_LINE> for domain in domains: <NEW_LINE> <INDENT> sites = gConfig.getSections( '%s/%s' % ( _basePath, domain ) ) <NEW_LINE> if not sites[ 'OK' ]: <NEW_LINE> <INDENT> return sites <NEW_LINE> <DEDENT> sites = sites[ 'Value' ] <NEW_LINE> for site in sites: <NEW_LINE> <INDENT> ces = gConfig.getValue( '%s/%s/%s/CE' % ( _basePath, domain, site ), '' ).split(',') <NEW_LINE> ces = map(lambda str : str.strip(), ces) <NEW_LINE> if element in ces: <NEW_LINE> <INDENT> host = gConfig.getValue('%s/%s/%s/CEs/%s/SSHHost' % ( _basePath, domain, site, element )) <NEW_LINE> cetype = gConfig.getValue('%s/%s/%s/CEs/%s/CEType' % ( _basePath, domain, site, element )) <NEW_LINE> if host: <NEW_LINE> <INDENT> idx = host.find('/') <NEW_LINE> if idx != -1: host = host[ 0 : idx ] <NEW_LINE> return S_OK((host, 22)) <NEW_LINE> <DEDENT> elif cetype == 'CREAM': <NEW_LINE> <INDENT> return S_OK((element, 8443)) <NEW_LINE> <DEDENT> elif cetype == 'ARC': <NEW_LINE> <INDENT> return S_OK((element, 2135)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return S_OK((element, 8443)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return S_ERROR('%s is not a vaild CE.' % element)
CEAccessTest
62598fa5009cb60464d013fa
class full_frame(object): <NEW_LINE> <INDENT> def __init__(self, device): <NEW_LINE> <INDENT> self.bounding_box = (0, 0, device.width, device.height) <NEW_LINE> <DEDENT> def redraw_required(self, image): <NEW_LINE> <INDENT> self.image = image <NEW_LINE> return True <NEW_LINE> <DEDENT> def inflate_bbox(self): <NEW_LINE> <INDENT> return self.bounding_box <NEW_LINE> <DEDENT> def getdata(self): <NEW_LINE> <INDENT> return self.image.getdata()
Always renders the full frame every time. This is slower than :py:class:`diff_to_previous` as there are generally more pixels to update on every render, but it has a more consistent render time. Not all display drivers may be able to use the differencing framebuffer, so this is provided as a drop-in replacement. :param device: The target device, used to determine the bounding box. :type device: luma.core.device.device
62598fa5cc0a2c111447aee5
class OutboundEnvironmentEndpointList(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'value': {'required': True}, 'next_link': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'value': {'key': 'value', 'type': '[OutboundEnvironmentEndpoint]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(OutboundEnvironmentEndpointList, self).__init__(**kwargs) <NEW_LINE> self.value = kwargs['value'] <NEW_LINE> self.next_link = None
Collection of Outbound Environment Endpoints. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param value: Required. Collection of resources. :type value: list[~storage_pool_management.models.OutboundEnvironmentEndpoint] :ivar next_link: Link to next page of resources. :vartype next_link: str
62598fa50a50d4780f7052b1
class DoesNotExist(Exception): <NEW_LINE> <INDENT> pass
The requested content does not exist.
62598fa58a43f66fc4bf2052
class InvalidStream(BloopException, ValueError): <NEW_LINE> <INDENT> pass
This is not a valid stream definition.
62598fa510dbd63aa1c70a87
class InMemoryRequest(DummyRequest): <NEW_LINE> <INDENT> def __init__(self, *a, **kw): <NEW_LINE> <INDENT> DummyRequest.__init__(self, *a, **kw) <NEW_LINE> self.requestHeaders = Headers() <NEW_LINE> <DEDENT> def redirect(self, url): <NEW_LINE> <INDENT> self.setResponseCode(http.FOUND) <NEW_LINE> self.setHeader(b'location', url)
In-memory `IRequest`.
62598fa5dd821e528d6d8e0a
class GeocodeCache(CustomCacheScheme): <NEW_LINE> <INDENT> def get_cache_duration(self): <NEW_LINE> <INDENT> duration = TIMEOUT_1_HOUR <NEW_LINE> return duration
Cache management object for geocode lookups So we don't hit Google maps geocode too frequently for the same location prekey = [<location_name>,]
62598fa563d6d428bbee2687
class DisjunctionPermission(BasePermission): <NEW_LINE> <INDENT> def __init__(self, *permissions): <NEW_LINE> <INDENT> self.permissions = permissions <NEW_LINE> <DEDENT> def has_permission(self, request, view): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def has_object_permission(self, request, view, obj): <NEW_LINE> <INDENT> for permission in self.permissions: <NEW_LINE> <INDENT> if permission.has_permission(request, view) and permission.has_object_permission(request, view, obj): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False
Create new permission as disjunction (OR) of provided instantiated permissions. Requires at least one permission to have both `has_permission` and `has_object_permission` satisfied.
62598fa5498bea3a75a579f9
class Keyword(Base, MasterModel): <NEW_LINE> <INDENT> name = Column(Text) <NEW_LINE> identifier = Column(String(255)) <NEW_LINE> entries = relationship( "Entry", secondary=entry_keyword, back_populates="keywords") <NEW_LINE> @property <NEW_LINE> def data(self): <NEW_LINE> <INDENT> data = { 'name': self.name, 'identifier': self.identifier, 'entry_names': [x.name for x in self.entries] } <NEW_LINE> return data <NEW_LINE> <DEDENT> def to_json(self): <NEW_LINE> <INDENT> return self.data <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '{}:{}'.format(self.name, self.identifier)
UniProt keywords summarise the content of a UniProtKB entry and facilitate the search for proteins of interest. :cvar str name: Keyword :cvar str identifier: Keyword identifier :cvar list entries: list of :class:`.Entry` object **Table view** .. image:: _static/models/keyword.png :target: _images/keyword.png **Links** - `UniProt keywords <http://www.uniprot.org/help/keywords>`_
62598fa5d486a94d0ba2bea3
class MysqlPipeline(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.conn = MySQLdb.connect('127.0.0.1', 'root', '111111', 'spider_db', charset="utf8") <NEW_LINE> self.cursor = self.conn.cursor() <NEW_LINE> <DEDENT> def close_spider(self, spider): <NEW_LINE> <INDENT> self.cursor.close() <NEW_LINE> self.conn.close()
用于不同Mysqlpipeline的继承
62598fa58e7ae83300ee8f77
class VcsPySvnPlugin(QObject): <NEW_LINE> <INDENT> def __init__(self, ui): <NEW_LINE> <INDENT> super(VcsPySvnPlugin, self).__init__(ui) <NEW_LINE> self.__ui = ui <NEW_LINE> self.__subversionDefaults = { "StopLogOnCopy": 1, "LogLimit": 20, "CommitMessages": 20, } <NEW_LINE> from VcsPlugins.vcsPySvn.ProjectHelper import PySvnProjectHelper <NEW_LINE> self.__projectHelperObject = PySvnProjectHelper(None, None) <NEW_LINE> try: <NEW_LINE> <INDENT> e5App().registerPluginObject( pluginTypename, self.__projectHelperObject, pluginType) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> readShortcuts(pluginName=pluginTypename) <NEW_LINE> <DEDENT> def getProjectHelper(self): <NEW_LINE> <INDENT> return self.__projectHelperObject <NEW_LINE> <DEDENT> def initToolbar(self, ui, toolbarManager): <NEW_LINE> <INDENT> if self.__projectHelperObject: <NEW_LINE> <INDENT> self.__projectHelperObject.initToolbar(ui, toolbarManager) <NEW_LINE> <DEDENT> <DEDENT> def activate(self): <NEW_LINE> <INDENT> from VcsPlugins.vcsPySvn.subversion import Subversion <NEW_LINE> self.__object = Subversion(self, self.__ui) <NEW_LINE> tb = self.__ui.getToolbar("vcs")[1] <NEW_LINE> tb.setVisible(False) <NEW_LINE> tb.setEnabled(False) <NEW_LINE> tb = self.__ui.getToolbar("pysvn")[1] <NEW_LINE> tb.setVisible(True) <NEW_LINE> tb.setEnabled(True) <NEW_LINE> return self.__object, True <NEW_LINE> <DEDENT> def deactivate(self): <NEW_LINE> <INDENT> self.__object = None <NEW_LINE> tb = self.__ui.getToolbar("pysvn")[1] <NEW_LINE> tb.setVisible(False) <NEW_LINE> tb.setEnabled(False) <NEW_LINE> tb = self.__ui.getToolbar("vcs")[1] <NEW_LINE> tb.setVisible(True) <NEW_LINE> tb.setEnabled(True) <NEW_LINE> <DEDENT> def getPreferences(self, key): <NEW_LINE> <INDENT> if key in ["StopLogOnCopy"]: <NEW_LINE> <INDENT> return Preferences.toBool(Preferences.Prefs.settings.value( "Subversion/" + key, self.__subversionDefaults[key])) <NEW_LINE> <DEDENT> elif key in ["LogLimit", "CommitMessages"]: <NEW_LINE> <INDENT> return int(Preferences.Prefs.settings.value( "Subversion/" + key, self.__subversionDefaults[key])) <NEW_LINE> <DEDENT> elif key in ["Commits"]: <NEW_LINE> <INDENT> return Preferences.toList(Preferences.Prefs.settings.value( "Subversion/" + key)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Preferences.Prefs.settings.value("Subversion/" + key) <NEW_LINE> <DEDENT> <DEDENT> def setPreferences(self, key, value): <NEW_LINE> <INDENT> Preferences.Prefs.settings.setValue("Subversion/" + key, value) <NEW_LINE> <DEDENT> def getServersPath(self): <NEW_LINE> <INDENT> return getServersPath() <NEW_LINE> <DEDENT> def getConfigPath(self): <NEW_LINE> <INDENT> return getConfigPath() <NEW_LINE> <DEDENT> def prepareUninstall(self): <NEW_LINE> <INDENT> e5App().unregisterPluginObject(pluginTypename) <NEW_LINE> <DEDENT> def prepareUnload(self): <NEW_LINE> <INDENT> if self.__projectHelperObject: <NEW_LINE> <INDENT> self.__projectHelperObject.removeToolbar( self.__ui, e5App().getObject("ToolbarManager")) <NEW_LINE> <DEDENT> e5App().unregisterPluginObject(pluginTypename)
Class implementing the PySvn version control plugin.
62598fa5b7558d5895463505
class OpenGLError(Exception): <NEW_LINE> <INDENT> pass
Generic OpenGL error.
62598fa57b25080760ed7381