code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class _EndpointDiscoveryRetryPolicy(object): <NEW_LINE> <INDENT> Max_retry_attempt_count = 120 <NEW_LINE> Retry_after_in_milliseconds = 1000 <NEW_LINE> FORBIDDEN_STATUS_CODE = 403 <NEW_LINE> WRITE_FORBIDDEN_SUB_STATUS_CODE = 3 <NEW_LINE> def __init__(self, global_endpoint_manager): <NEW_LINE> <INDENT> self.global_endpoint_manager = global_endpoint_manager <NEW_LINE> self._max_retry_attempt_count = _EndpointDiscoveryRetryPolicy.Max_retry_attempt_count <NEW_LINE> self.current_retry_attempt_count = 0 <NEW_LINE> self.retry_after_in_milliseconds = _EndpointDiscoveryRetryPolicy.Retry_after_in_milliseconds <NEW_LINE> logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.INFO) <NEW_LINE> <DEDENT> def ShouldRetry(self, exception): <NEW_LINE> <INDENT> if self.current_retry_attempt_count < self._max_retry_attempt_count and self.global_endpoint_manager.EnableEndpointDiscovery: <NEW_LINE> <INDENT> self.current_retry_attempt_count += 1 <NEW_LINE> logging.info('Write location was changed, refreshing the locations list from database account and will retry the request.') <NEW_LINE> self.global_endpoint_manager.RefreshEndpointList() <NEW_LINE> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False | The endpoint discovery retry policy class used for geo-replicated database accounts
to handle the write forbidden exceptions due to writable/readable location changes
(say, after a failover). | 62598fdb3617ad0b5ee066ff |
class XenPlatformAccountType(Enum): <NEW_LINE> <INDENT> MANAGED = "MANAGED" <NEW_LINE> OWNED = "OWNED" | Account type for xenPlatform | 62598fdb099cdd3c636756ba |
class MastodonFollowingExtractor(MastodonExtractor): <NEW_LINE> <INDENT> subcategory = "following" <NEW_LINE> pattern = BASE_PATTERN + r"/users/([^/?#]+)/following" <NEW_LINE> test = ( ("https://mastodon.social/users/0x4f/following", { "extractor": False, "count": ">= 20", }), ("https://mastodon.social/users/id:10843/following"), ("https://pawoo.net/users/yoru_nine/following"), ("https://baraag.net/users/pumpkinnsfw/following"), ) <NEW_LINE> def items(self): <NEW_LINE> <INDENT> api = MastodonAPI(self) <NEW_LINE> account_id = api.account_id_by_username(self.item) <NEW_LINE> for account in api.account_following(account_id): <NEW_LINE> <INDENT> account["_extractor"] = MastodonUserExtractor <NEW_LINE> yield Message.Queue, account["url"], account | Extractor for followed mastodon users | 62598fdb656771135c489c2a |
class RecordThread(threading.Thread): <NEW_LINE> <INDENT> def __init__(self, pad_object): <NEW_LINE> <INDENT> threading.Thread.__init__(self) <NEW_LINE> self.pad = pad_object <NEW_LINE> self.name = "Pad {} RecordThread".format(self.pad.number) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> frames = [] <NEW_LINE> stream = self.pad.port.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK) <NEW_LINE> while self.pad.is_armed: <NEW_LINE> <INDENT> data = stream.read(CHUNK) <NEW_LINE> frames.append(data) <NEW_LINE> <DEDENT> stream.stop_stream() <NEW_LINE> stream.close() <NEW_LINE> self.pad.save(frames) <NEW_LINE> return <NEW_LINE> <DEDENT> def start_during_playback(self): <NEW_LINE> <INDENT> frames = [] <NEW_LINE> def callback(in_data, frame_count, time_info, status): <NEW_LINE> <INDENT> new_frames = wf.readframes(frame_count) <NEW_LINE> frames.append(new_frames) <NEW_LINE> return (in_data, pyaudio.paContinue) <NEW_LINE> <DEDENT> stream = self.pad.sampleportopen(format=self.pad.sampleportget_format_from_width(2), channels=CHANNELS, rate=RATE, input=True, output=True, stream_callback=callback) <NEW_LINE> stream.start_stream() <NEW_LINE> while stream.is_active(): <NEW_LINE> <INDENT> time.sleep(0.1) <NEW_LINE> <DEDENT> stream.stop_stream() <NEW_LINE> stream.close() <NEW_LINE> self.save(frames) | Spawns a new thread to open an input stream and saves input to Pad.file
Runs until pad.armed is set to False
Records by to a pad by opening the
Pad's pyAdudio port and saving to Pad.file | 62598fdb26238365f5fad11d |
class MyFavOrgView(LoginRequiredMixin,View): <NEW_LINE> <INDENT> def get(self,request): <NEW_LINE> <INDENT> user = request.user <NEW_LINE> fav_orgs = UserFavorite.objects.filter(user=user,fav_type=2) <NEW_LINE> org_list = [] <NEW_LINE> for fav_org in fav_orgs: <NEW_LINE> <INDENT> fav_id = fav_org.fav_id <NEW_LINE> org = CourseOrg.objects.get(id=fav_id) <NEW_LINE> org_list.append(org) <NEW_LINE> <DEDENT> return render(request,'usercenter-fav-org.html',{ "org_list":org_list }) | 个人中心:我的收藏,收藏机构 | 62598fdbad47b63b2c5a7e0e |
class SiteBasedHelpdeskUserPermissionsJson(object): <NEW_LINE> <INDENT> swagger_types = { 'permissions': 'list[SiteBasedHelpdeskUserPermissionJson]', 'group_not_found': 'bool', 'naming_error': 'bool' } <NEW_LINE> attribute_map = { 'permissions': 'permissions', 'group_not_found': 'groupNotFound', 'naming_error': 'namingError' } <NEW_LINE> def __init__(self, permissions=None, group_not_found=None, naming_error=None): <NEW_LINE> <INDENT> self._permissions = None <NEW_LINE> self._group_not_found = None <NEW_LINE> self._naming_error = None <NEW_LINE> self.discriminator = None <NEW_LINE> if permissions is not None: <NEW_LINE> <INDENT> self.permissions = permissions <NEW_LINE> <DEDENT> if group_not_found is not None: <NEW_LINE> <INDENT> self.group_not_found = group_not_found <NEW_LINE> <DEDENT> if naming_error is not None: <NEW_LINE> <INDENT> self.naming_error = naming_error <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def permissions(self): <NEW_LINE> <INDENT> return self._permissions <NEW_LINE> <DEDENT> @permissions.setter <NEW_LINE> def permissions(self, permissions): <NEW_LINE> <INDENT> self._permissions = permissions <NEW_LINE> <DEDENT> @property <NEW_LINE> def group_not_found(self): <NEW_LINE> <INDENT> return self._group_not_found <NEW_LINE> <DEDENT> @group_not_found.setter <NEW_LINE> def group_not_found(self, group_not_found): <NEW_LINE> <INDENT> self._group_not_found = group_not_found <NEW_LINE> <DEDENT> @property <NEW_LINE> def naming_error(self): <NEW_LINE> <INDENT> return self._naming_error <NEW_LINE> <DEDENT> @naming_error.setter <NEW_LINE> def naming_error(self, naming_error): <NEW_LINE> <INDENT> self._naming_error = naming_error <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> if issubclass(SiteBasedHelpdeskUserPermissionsJson, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, SiteBasedHelpdeskUserPermissionsJson): <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. | 62598fdb187af65679d29ed1 |
class DataProcessor(object): <NEW_LINE> <INDENT> def __init__(self, use_spm, do_lower_case): <NEW_LINE> <INDENT> super(DataProcessor, self).__init__() <NEW_LINE> self.use_spm = use_spm <NEW_LINE> self.do_lower_case = do_lower_case <NEW_LINE> <DEDENT> def get_train_examples(self, data_dir): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def get_dev_examples(self, data_dir): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def get_test_examples(self, data_dir): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def get_labels(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _read_tsv(cls, input_file, quotechar=None): <NEW_LINE> <INDENT> with tf.gfile.Open(input_file, "r") as f: <NEW_LINE> <INDENT> reader = csv.reader(f, delimiter="\t", quotechar=quotechar) <NEW_LINE> lines = [] <NEW_LINE> for line in reader: <NEW_LINE> <INDENT> lines.append(line) <NEW_LINE> <DEDENT> return lines <NEW_LINE> <DEDENT> <DEDENT> def _read_txt(self,input_file): <NEW_LINE> <INDENT> with tf.gfile.Open(input_file, "r") as f: <NEW_LINE> <INDENT> for line in f: <NEW_LINE> <INDENT> line=line.rstrip() <NEW_LINE> yield line <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def process_text(self, text): <NEW_LINE> <INDENT> if self.use_spm: <NEW_LINE> <INDENT> return tokenization.preprocess_text(text, lower=self.do_lower_case) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return tokenization.convert_to_unicode(text) | Base class for data converters for sequence classification data sets. | 62598fdbc4546d3d9def7561 |
class AsyncInit(type): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> async def init(obj, *args, **kwargs): <NEW_LINE> <INDENT> await obj.__ainit__(*args, **kwargs) <NEW_LINE> return obj <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def new(mcs, cls, *args, **kwargs): <NEW_LINE> <INDENT> obj = cls.__cnew__(cls) <NEW_LINE> coro = mcs.init(obj, *args, **kwargs) <NEW_LINE> return coro <NEW_LINE> <DEDENT> def __new__(mcs, name, bases, attrs, **kwargs): <NEW_LINE> <INDENT> if '__new__' in attrs: <NEW_LINE> <INDENT> attrs['__cnew__'] = attrs['__new__'] <NEW_LINE> <DEDENT> elif len(bases): <NEW_LINE> <INDENT> if hasattr(bases[0], '__cnew__'): <NEW_LINE> <INDENT> attrs['__cnew__'] = bases[0].__cnew__ <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> attrs['__cnew__'] = bases[0].__new__ <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> attrs['__cnew__'] = object.__new__ <NEW_LINE> <DEDENT> attrs['__new__'] = mcs.new <NEW_LINE> return super().__new__(mcs, name, bases, attrs) <NEW_LINE> <DEDENT> def __init__(cls, name, bases, attrs, **kwargs): <NEW_LINE> <INDENT> super().__init__(name, bases, attrs) <NEW_LINE> <DEDENT> def __call__(cls, *args, **kwargs): <NEW_LINE> <INDENT> return super().__call__(*args, **kwargs) | Metaclass to support asynchronous __init__ (replaced with __ainit__) | 62598fdb3617ad0b5ee06703 |
class BaseFairseqModel(nn.Module): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self._is_generation_fast = False <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def add_args(parser): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def build_model(cls, args, task): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def get_targets(self, sample, net_output): <NEW_LINE> <INDENT> return sample['target'] <NEW_LINE> <DEDENT> def get_normalized_probs(self, net_output, log_probs, sample=None): <NEW_LINE> <INDENT> if hasattr(self, 'decoder'): <NEW_LINE> <INDENT> return self.decoder.get_normalized_probs(net_output, log_probs, sample) <NEW_LINE> <DEDENT> elif torch.is_tensor(net_output): <NEW_LINE> <INDENT> logits = net_output.float() <NEW_LINE> if log_probs: <NEW_LINE> <INDENT> return F.log_softmax(logits, dim=-1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return F.softmax(logits, dim=-1) <NEW_LINE> <DEDENT> <DEDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def max_positions(self): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> def max_decoder_positions(self): <NEW_LINE> <INDENT> return self.decoder.max_positions() <NEW_LINE> <DEDENT> def load_state_dict(self, state_dict, strict=True): <NEW_LINE> <INDENT> self.upgrade_state_dict(state_dict) <NEW_LINE> super().load_state_dict(state_dict, strict) <NEW_LINE> <DEDENT> def upgrade_state_dict(self, state_dict): <NEW_LINE> <INDENT> self.upgrade_state_dict_named(state_dict, '') <NEW_LINE> <DEDENT> def upgrade_state_dict_named(self, state_dict, name): <NEW_LINE> <INDENT> assert state_dict is not None <NEW_LINE> def do_upgrade(m, prefix): <NEW_LINE> <INDENT> if len(prefix) > 0: <NEW_LINE> <INDENT> prefix += '.' <NEW_LINE> <DEDENT> for n, c in m.named_children(): <NEW_LINE> <INDENT> name = prefix + n <NEW_LINE> if hasattr(c, 'upgrade_state_dict_named'): <NEW_LINE> <INDENT> c.upgrade_state_dict_named(state_dict, name) <NEW_LINE> <DEDENT> elif hasattr(c, 'upgrade_state_dict'): <NEW_LINE> <INDENT> c.upgrade_state_dict(state_dict) <NEW_LINE> <DEDENT> do_upgrade(c, name) <NEW_LINE> <DEDENT> <DEDENT> do_upgrade(self, name) <NEW_LINE> <DEDENT> def make_generation_fast_(self, **kwargs): <NEW_LINE> <INDENT> if self._is_generation_fast: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self._is_generation_fast = True <NEW_LINE> def apply_remove_weight_norm(module): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> nn.utils.remove_weight_norm(module) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> self.apply(apply_remove_weight_norm) <NEW_LINE> def apply_make_generation_fast_(module): <NEW_LINE> <INDENT> if module != self and hasattr(module, 'make_generation_fast_'): <NEW_LINE> <INDENT> module.make_generation_fast_(**kwargs) <NEW_LINE> <DEDENT> <DEDENT> self.apply(apply_make_generation_fast_) <NEW_LINE> def train(mode): <NEW_LINE> <INDENT> if mode: <NEW_LINE> <INDENT> raise RuntimeError('cannot train after make_generation_fast') <NEW_LINE> <DEDENT> <DEDENT> self.eval() <NEW_LINE> self.train = train <NEW_LINE> <DEDENT> def prepare_for_onnx_export_(self, **kwargs): <NEW_LINE> <INDENT> def apply_prepare_for_onnx_export_(module): <NEW_LINE> <INDENT> if module != self and hasattr(module, 'prepare_for_onnx_export_'): <NEW_LINE> <INDENT> module.prepare_for_onnx_export_(**kwargs) <NEW_LINE> <DEDENT> <DEDENT> self.apply(apply_prepare_for_onnx_export_) | Base class for fairseq models. | 62598fdb656771135c489c2e |
class Casa(): <NEW_LINE> <INDENT> def __init__(self, tabuleiro, posicao): <NEW_LINE> <INDENT> self.tabuleiro, self.posicao = tabuleiro, posicao <NEW_LINE> self.pino = None <NEW_LINE> <DEDENT> def joga(self, tipo): <NEW_LINE> <INDENT> self.pino = Pino(tipo, self) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return str(self.pino) | Local onde se pode colocar um pino.
:param tabuleiro: a referencia do tabuleiro.
:param posicao: Uma tupla com a ordem da coluna e da linha. | 62598fdbab23a570cc2d504c |
class somsc: <NEW_LINE> <INDENT> def __init__(self, data, amount_clusters, epouch = 100, ccore = True): <NEW_LINE> <INDENT> self.__data_pointer = data; <NEW_LINE> self.__amount_clusters = amount_clusters; <NEW_LINE> self.__epouch = epouch; <NEW_LINE> self.__ccore = ccore; <NEW_LINE> self.__network = None; <NEW_LINE> <DEDENT> def process(self): <NEW_LINE> <INDENT> self.__network = som(1, self.__amount_clusters, type_conn.grid_four, None, self.__ccore); <NEW_LINE> self.__network.train(self.__data_pointer, self.__epouch, True); <NEW_LINE> <DEDENT> def get_clusters(self): <NEW_LINE> <INDENT> return self.__network.capture_objects; <NEW_LINE> <DEDENT> def get_cluster_encoding(self): <NEW_LINE> <INDENT> return type_encoding.CLUSTER_INDEX_LIST_SEPARATION; | !
@brief Class represents simple clustering algorithm based on self-organized feature map.
@details This algorithm uses amount of clusters that should be allocated as a size of SOM map. Captured objects by neurons are clusters.
Algorithm is able to process data with Gaussian distribution that has spherical forms.
CCORE option can be used to use the pyclustering core - C/C++ shared library for processing that significantly increases performance.
Example:
@code
# load list of points for cluster analysis
sample = read_sample(path);
# create instance of SOM-SC algorithm to allocated two clusters
somsc_instance = somsc(sample, 2);
# run cluster analysis and obtain results
somsc_instance.process();
somsc_instance.get_clusters();
@endcode | 62598fdbab23a570cc2d504d |
class QubesNoSuchPropertyError(QubesException, AttributeError): <NEW_LINE> <INDENT> def __init__(self, holder, prop_name, msg=None): <NEW_LINE> <INDENT> super(QubesNoSuchPropertyError, self).__init__( msg or 'Invalid property {!r} of {!s}'.format( prop_name, holder)) <NEW_LINE> self.holder = holder <NEW_LINE> self.prop = prop_name | Requested property does not exist
| 62598fdbfbf16365ca79467f |
@dataclass(frozen=True) <NEW_LINE> class Tag(Base): <NEW_LINE> <INDENT> label: str <NEW_LINE> id: int | User-applied metadata.
Attribute of Series. | 62598fdbad47b63b2c5a7e13 |
class BindPluginRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.PluginInstanceList = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> if params.get("PluginInstanceList") is not None: <NEW_LINE> <INDENT> self.PluginInstanceList = [] <NEW_LINE> for item in params.get("PluginInstanceList"): <NEW_LINE> <INDENT> obj = GatewayPluginBoundParam() <NEW_LINE> obj._deserialize(item) <NEW_LINE> self.PluginInstanceList.append(obj) <NEW_LINE> <DEDENT> <DEDENT> memeber_set = set(params.keys()) <NEW_LINE> for name, value in vars(self).items(): <NEW_LINE> <INDENT> if name in memeber_set: <NEW_LINE> <INDENT> memeber_set.remove(name) <NEW_LINE> <DEDENT> <DEDENT> if len(memeber_set) > 0: <NEW_LINE> <INDENT> warnings.warn("%s fileds are useless." % ",".join(memeber_set)) | BindPlugin请求参数结构体
| 62598fdbab23a570cc2d504e |
class Receiver(ABC): <NEW_LINE> <INDENT> @abstractmethod <NEW_LINE> def receive(self, transportable): <NEW_LINE> <INDENT> pass | Anything that can receive a transportable object e.g. a pipe | 62598fdbd8ef3951e32c813c |
@ns.response(200, "Success") <NEW_LINE> @ns.response(401, "Not logged in") <NEW_LINE> @ns.response(403, "Not authorized") <NEW_LINE> @ns.response(404, "User not found") <NEW_LINE> @ns.route("/<string:user_id>/export") <NEW_LINE> class UserDataExport(Resource): <NEW_LINE> <INDENT> @require_admin <NEW_LINE> def get(self, user_id): <NEW_LINE> <INDENT> user_data = api.user.get_user(uid=user_id) <NEW_LINE> if not user_data: <NEW_LINE> <INDENT> raise PicoException("User not found", status_code=404) <NEW_LINE> <DEDENT> submissions = api.submissions.get_submissions(uid=user_id) <NEW_LINE> feedbacks = api.problem_feedback.get_problem_feedback(uid=user_id) <NEW_LINE> return jsonify( {"user": user_data, "submissions": submissions, "feedback": feedbacks} ) | Export all data of a given user. | 62598fdbc4546d3d9def7564 |
class ResPartnerBank(orm.Model, BankCommon): <NEW_LINE> <INDENT> _inherit = 'res.partner.bank' <NEW_LINE> _columns = { 'name': fields.char('Description', size=128, required=True), 'bvr_adherent_num': fields.char('Bank BVR adherent number', size=11, help=("Your Bank adherent number to be printed in references of your BVR." "This is not a postal account number.")), 'acc_number': fields.char('Account/IBAN Number', size=64, required=True), 'ccp': fields.related('bank', 'ccp', type='char', string='CCP', readonly=True), } <NEW_LINE> def get_account_number(self, cursor, uid, bid, context=None): <NEW_LINE> <INDENT> if isinstance(bid, list): <NEW_LINE> <INDENT> bid = bid[0] <NEW_LINE> <DEDENT> current = self.browse(cursor, uid, bid, context=context) <NEW_LINE> if current.state not in ('bv', 'bvr'): <NEW_LINE> <INDENT> return current.acc_number <NEW_LINE> <DEDENT> if current.bank and current.bank.ccp: <NEW_LINE> <INDENT> return current.bank.ccp <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return current.acc_number <NEW_LINE> <DEDENT> <DEDENT> def _check_postal_num(self, cursor, uid, ids): <NEW_LINE> <INDENT> p_banks = self.browse(cursor, uid, ids) <NEW_LINE> for p_bank in p_banks: <NEW_LINE> <INDENT> if not p_bank.state in ('bv', 'bvr'): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if not p_bank.get_account_number(p_bank.id): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if not (self._check_9_pos_postal_num(p_bank.get_account_number(p_bank.id)) or self._check_5_pos_postal_num(p_bank.get_account_number(p_bank.id))): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True <NEW_LINE> <DEDENT> def _check_ccp_duplication(self, cursor, uid, ids): <NEW_LINE> <INDENT> p_banks = self.browse(cursor, uid, ids) <NEW_LINE> for p_bank in p_banks: <NEW_LINE> <INDENT> if not p_bank.state in ('bv', 'bvr'): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> bank_ccp = p_bank.bank.ccp if p_bank.bank else False <NEW_LINE> if not bank_ccp: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> part_bank_check = (self._check_5_pos_postal_num(p_bank.acc_number) or self._check_9_pos_postal_num(p_bank.acc_number)) <NEW_LINE> bank_check = (self._check_5_pos_postal_num(p_bank.bank.ccp) or self._check_9_pos_postal_num(p_bank.bank.ccp)) <NEW_LINE> if part_bank_check and bank_check: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True <NEW_LINE> <DEDENT> _constraints = [(_check_postal_num, 'Please enter a correct postal number. (01-23456-1 or 12345)', ['acc_number']), (_check_ccp_duplication, 'You can not enter a ccp both on the bank and on an account' ' of type BV, BVR', ['acc_number', 'bank'])] <NEW_LINE> _sql_constraints = [('bvr_adherent_uniq', 'unique (bvr_adherent_num)', 'The BVR adherent number must be unique !')] | Inherit res.partner.bank class in order to add swiss specific fields and state controls | 62598fdb4c3428357761a86f |
class TestFunction2(TestFunction): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.y0 = 1 <NEW_LINE> <DEDENT> def evaluate(self, t, y): <NEW_LINE> <INDENT> return y + t <NEW_LINE> <DEDENT> def exact(self, t): <NEW_LINE> <INDENT> return -1 + 2*np.exp(t) - t | y' = y + t
y(0) = 1
y(t) = -1 + 2 e^t - t | 62598fdbab23a570cc2d504f |
class RPLidarProcessor(threading.Thread): <NEW_LINE> <INDENT> def __init__(self, rplidar): <NEW_LINE> <INDENT> logging.debug("Initializing rplidar_processor thread.") <NEW_LINE> threading.Thread.__init__(self) <NEW_LINE> self.name = "rplidar_processor" <NEW_LINE> self.rplidar = rplidar <NEW_LINE> self.serial_port = rplidar.serial_port <NEW_LINE> self.raw_frames = rplidar.raw_frames <NEW_LINE> self.curFrame = rplidar.curFrame <NEW_LINE> self.alive = threading.Event() <NEW_LINE> self.alive.set() <NEW_LINE> logging.debug("rplidar_processor thread initialized.") <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> while self.alive.isSet(): <NEW_LINE> <INDENT> if self.curFrame.timestamp < self.raw_frames[-1].timestamp: <NEW_LINE> <INDENT> raw_frame = self.raw_frames[-1] <NEW_LINE> self.curFrame = RPLidarFrame(raw_frame) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def join(self, timeout=None): <NEW_LINE> <INDENT> self.alive.clear() <NEW_LINE> threading.Thread.join(self, timeout) <NEW_LINE> logging.debug("rplidar_processor thread closed.") | A thread for processing data from rplidar_monitor
| 62598fdc283ffb24f3cf3e47 |
class IsAdminUser(BasePermission): <NEW_LINE> <INDENT> def has_permission(self, request): <NEW_LINE> <INDENT> return request.user and request.user.is_staff | Allows access only to admin users. | 62598fdc091ae356687051e2 |
class SubRows(object): <NEW_LINE> <INDENT> def __init__(self, numCols): <NEW_LINE> <INDENT> self.numCols = numCols <NEW_LINE> self.rows = [] <NEW_LINE> <DEDENT> def addRow(self, row): <NEW_LINE> <INDENT> assert(len(row) == self.numCols) <NEW_LINE> self.rows.append(row) <NEW_LINE> <DEDENT> def getNumRows(self): <NEW_LINE> <INDENT> return len(self.rows) <NEW_LINE> <DEDENT> def toTdRow(self, iRow): <NEW_LINE> <INDENT> if iRow < len(self.rows): <NEW_LINE> <INDENT> return "<td>" + "<td>".join([str(c) for c in self.rows[iRow]]) <NEW_LINE> <DEDENT> elif self.numCols > 1: <NEW_LINE> <INDENT> return "<td colspan={}>".format(self.numCols) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "<td>" | Object used to specify a set of sub-rows. Indicates number of columns
occupied, which is need for laying out. | 62598fdc4c3428357761a873 |
class c12(nn.Module): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(c12, self).__init__() <NEW_LINE> self.conv1 = nn.Conv2d(3, 64, 3, padding=1) <NEW_LINE> self.conv2 = nn.Conv2d(64, 64, 3, padding=1) <NEW_LINE> self.conv3 = nn.Conv2d(64, 128, 3, padding=1) <NEW_LINE> self.conv4 = nn.Conv2d(128, 128, 3, padding=1) <NEW_LINE> self.conv5 = nn.Conv2d(128, 196, 3, padding=1) <NEW_LINE> self.conv6 = nn.Conv2d(196, 196, 3, padding=1) <NEW_LINE> self.fc1 = nn.Linear(196 * 4 * 4, 256) <NEW_LINE> self.fc2 = nn.Linear(256, 10) <NEW_LINE> self.pool = nn.MaxPool2d(2, 2) <NEW_LINE> <DEDENT> def per_image_standardization(self, x): <NEW_LINE> <INDENT> _dim = x.shape[1] * x.shape[2] * x.shape[3] <NEW_LINE> mean = torch.mean(x, dim=(1,2,3), keepdim = True) <NEW_LINE> stddev = torch.std(x, dim=(1,2,3), keepdim = True) <NEW_LINE> adjusted_stddev = torch.max(stddev, (1./np.sqrt(_dim)) * torch.ones_like(stddev)) <NEW_LINE> return (x - mean) / adjusted_stddev <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> stdard_x = self.per_image_standardization(x) <NEW_LINE> conv_1 = self.conv1(stdard_x) <NEW_LINE> relu_1 = F.relu(conv_1) <NEW_LINE> conv_2 = self.conv2(relu_1) <NEW_LINE> relu_2 = F.relu(conv_2) <NEW_LINE> pool_1 = self.pool(relu_2) <NEW_LINE> conv_3 = self.conv3(pool_1) <NEW_LINE> relu_3 = F.relu(conv_3) <NEW_LINE> conv_4 = self.conv4(relu_3) <NEW_LINE> relu_4 = F.relu(conv_4) <NEW_LINE> pool_2 = self.pool(relu_4) <NEW_LINE> conv_5 = self.conv5(pool_2) <NEW_LINE> relu_5 = F.relu(conv_5) <NEW_LINE> conv_6 = self.conv6(relu_5) <NEW_LINE> relu_6 = F.relu(conv_6) <NEW_LINE> pool_3 = self.pool(relu_6) <NEW_LINE> flatten = pool_3.view(-1, 196 * 4 * 4) <NEW_LINE> fc = self.fc1(flatten) <NEW_LINE> relu_7 = F.relu(fc) <NEW_LINE> fc_2 = self.fc2(relu_7) <NEW_LINE> intermediate = {"conv_1":conv_1, "relu_1":relu_1, "conv_2":conv_2, "relu_2":relu_2, "pool_1":pool_1, "conv_3":conv_3, "relu_3":relu_3, "conv_4":conv_4, "relu_4":relu_4, "pool_2":pool_2, "conv_5":conv_5, "relu_5":relu_5, "conv_6":conv_6, "relu_6":relu_6, "pool_3":pool_3, "flatten":flatten, "fc":fc, "relu_7":relu_7, "fc_2":fc_2} <NEW_LINE> return fc_2, intermediate | The 8-layer conv net model used in: https://github.com/YisenWang/dynamic_adv_training/blob/master/models.py.
BN removed | 62598fdc656771135c489c38 |
class CSSSlimmer(Slimmer): <NEW_LINE> <INDENT> name = 'css_slimmer' <NEW_LINE> def output(self, _in, out, **kw): <NEW_LINE> <INDENT> out.write(self.slimmer.css_slimmer(_in.read())) | Minifies CSS by removing whitespace, comments etc., using the Python
`slimmer <http://pypi.python.org/pypi/slimmer/>`_ library. | 62598fdc187af65679d29ed7 |
class ZeroOperator(LinearOperator): <NEW_LINE> <INDENT> def __init__(self, nargin, nargout, **kwargs): <NEW_LINE> <INDENT> if "matvec" in kwargs: <NEW_LINE> <INDENT> kwargs.pop("matvec") <NEW_LINE> <DEDENT> if "matvec_transp" in kwargs: <NEW_LINE> <INDENT> kwargs.pop("matvec_transp") <NEW_LINE> <DEDENT> def matvec(x): <NEW_LINE> <INDENT> if x.shape != (nargin,): <NEW_LINE> <INDENT> msg = "Input has shape " + str(x.shape) <NEW_LINE> msg += " instead of (%d,)" % self.nargin <NEW_LINE> raise ValueError(msg) <NEW_LINE> <DEDENT> result_type = np.result_type(self.dtype, x.dtype) <NEW_LINE> return np.zeros(nargout, dtype=result_type) <NEW_LINE> <DEDENT> def matvec_transp(x): <NEW_LINE> <INDENT> if x.shape != (nargout,): <NEW_LINE> <INDENT> msg = "Input has shape " + str(x.shape) <NEW_LINE> msg += " instead of (%d,)" % self.nargout <NEW_LINE> raise ValueError(msg) <NEW_LINE> <DEDENT> result_type = np.result_type(self.dtype, x.dtype) <NEW_LINE> return np.zeros(nargin, dtype=result_type) <NEW_LINE> <DEDENT> super(ZeroOperator, self).__init__( nargin, nargout, symmetric=(nargin == nargout), matvec=matvec, matvec_transp=matvec_transp, matvec_adj=matvec_transp, **kwargs, ) <NEW_LINE> <DEDENT> def __abs__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def _sqrt(self): <NEW_LINE> <INDENT> return self | The zero linear operator of shape `nargout`-by-`nargin`. | 62598fdc26238365f5fad12b |
class Certificate(BaseCertificate): <NEW_LINE> <INDENT> def load_context(self, cert_string=None, cert_file=None, key_string=None, key_file=None, passphrase=None, context_method=OpenSSL.SSL.TLSv1_METHOD): <NEW_LINE> <INDENT> context = OpenSSL.SSL.Context(context_method) <NEW_LINE> if passphrase is not None and not isinstance(passphrase, six.binary_type): <NEW_LINE> <INDENT> passphrase = six.b(passphrase) <NEW_LINE> <DEDENT> if cert_file: <NEW_LINE> <INDENT> if LOG.isEnabledFor(logging.DEBUG): <NEW_LINE> <INDENT> LOG.debug("Certificate provided as file: %s", cert_file) <NEW_LINE> <DEDENT> with open(cert_file, 'rb') as fp: <NEW_LINE> <INDENT> cert_string = fp.read() <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if LOG.isEnabledFor(logging.DEBUG): <NEW_LINE> <INDENT> LOG.debug("Certificate provided as string") <NEW_LINE> <DEDENT> <DEDENT> cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert_string) <NEW_LINE> context.use_certificate(cert) <NEW_LINE> if not key_string and not key_file: <NEW_LINE> <INDENT> if LOG.isEnabledFor(logging.DEBUG): <NEW_LINE> <INDENT> LOG.debug("Private key provided with certificate %s %s passphrase", 'file' if cert_file else 'string', 'with' if passphrase is not None else 'without') <NEW_LINE> <DEDENT> args = [OpenSSL.crypto.FILETYPE_PEM, cert_string] <NEW_LINE> if passphrase is not None: <NEW_LINE> <INDENT> args.append(passphrase) <NEW_LINE> <DEDENT> pk = OpenSSL.crypto.load_privatekey(*args) <NEW_LINE> context.use_privatekey(pk) <NEW_LINE> <DEDENT> elif key_file and passphrase is None: <NEW_LINE> <INDENT> if LOG.isEnabledFor(logging.DEBUG): <NEW_LINE> <INDENT> LOG.debug("Private key provided as file without passphrase: %s", key_file) <NEW_LINE> <DEDENT> context.use_privatekey_file(key_file, OpenSSL.crypto.FILETYPE_PEM) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if key_file: <NEW_LINE> <INDENT> if LOG.isEnabledFor(logging.DEBUG): <NEW_LINE> <INDENT> LOG.debug("Private key provided as file withpassphrase: %s", key_file) <NEW_LINE> <DEDENT> with open(key_file, 'rb') as fp: <NEW_LINE> <INDENT> key_string = fp.read() <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if LOG.isEnabledFor(logging.DEBUG): <NEW_LINE> <INDENT> LOG.debug("Private key provided as string %s passphrase", 'with' if passphrase is not None else 'without') <NEW_LINE> <DEDENT> <DEDENT> args = [OpenSSL.crypto.FILETYPE_PEM, key_string] <NEW_LINE> if passphrase is not None: <NEW_LINE> <INDENT> args.append(passphrase) <NEW_LINE> <DEDENT> pk = OpenSSL.crypto.load_privatekey(*args) <NEW_LINE> context.use_privatekey(pk) <NEW_LINE> <DEDENT> context.check_privatekey() <NEW_LINE> return context, cert <NEW_LINE> <DEDENT> def dump_certificate(self, raw_certificate): <NEW_LINE> <INDENT> return OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, raw_certificate) <NEW_LINE> <DEDENT> def dump_digest(self, raw_certificate, digest): <NEW_LINE> <INDENT> return raw_certificate.digest(digest) | pyOpenSSL certificate implementation. | 62598fdcad47b63b2c5a7e1c |
class Print(object): <NEW_LINE> <INDENT> @abstractmethod <NEW_LINE> def print_weak(self) -> None: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def print_strong(self) -> None: <NEW_LINE> <INDENT> raise NotImplementedError | Interface
| 62598fdc099cdd3c636756c2 |
class UploadForm(FlaskForm): <NEW_LINE> <INDENT> sample = FileField('Sample image file', validators=[ FileRequired(), FileAllowed( app.samples_set, 'Not supported type : jpeg only.') ]) <NEW_LINE> smear_type = RadioField('Blood smear type', choices=[ ('thick', 'Thick'), ('thin', 'Thin') ], validators=[Required()] ) <NEW_LINE> comment = TextAreaField('Comment', render_kw={"placeholder": "URL, legend, etc...", "rows": 3, "cols": 70}) <NEW_LINE> license = RadioField('License', choices=[ ('CC0', 'CC0 / Public Domain: Freeing content globally without restrictions'), ('BY', 'CC-BY: Attribution') ], validators=[Required()], default='BY' ) <NEW_LINE> provider = TextAreaField('Provider', render_kw={"rows": 3, "cols": 70}, validators=[Required()]) <NEW_LINE> magnification =IntegerField ('Microscope magnification factor', widget=NumberInput(), render_kw={"placeholder": "e.g. 100"}, validators=[Optional()], default=None ) <NEW_LINE> patient_ref = TextField('Patient reference', validators=[Length(max=50)]) <NEW_LINE> patient_year_of_birth = IntegerField ('Patient year of birth', widget=NumberInput(), validators=[RequiredIf('patient_ref')], default=None ) <NEW_LINE> patient_gender =RadioField('Patient gender', validators=[RequiredIf('patient_ref')], default=None, choices=[ ('M', 'Male'), ('F', 'Female') ]) <NEW_LINE> patient_city = TextField('Patient city', validators=[Length(max=50), RequiredIf('patient_ref')], default=None) <NEW_LINE> patient_country = TextField('Patient country', validators=[Length(max=50), RequiredIf('patient_ref')], default=None) <NEW_LINE> submit = SubmitField('Upload new blood smear', render_kw={"class": "btn btn-info btn-lg", "id": "submit-button"}) | Form for image upload. | 62598fdc656771135c489c3a |
class BookFormRegister(Form): <NEW_LINE> <INDENT> titulo = StringField('titulo', [validators.DataRequired()]) <NEW_LINE> editorial = StringField('Editorial', [validators.DataRequired()]) <NEW_LINE> numeroPaginas = IntegerField('numero de paginas', [validators.DataRequired()]) <NEW_LINE> precio = FloatField('precio', [validators.DataRequired()]) <NEW_LINE> genero = StringField('genero', [validators.DataRequired()]) <NEW_LINE> autor = StringField('autor', [validators.DataRequired()]) <NEW_LINE> imagen = FileField() | docstring for BookFormRegister | 62598fdc091ae356687051e6 |
class Tunel(Sala): <NEW_LINE> <INDENT> def monta_ambiente(self, nome): <NEW_LINE> <INDENT> self.camara = self.cria_sala(nome=TUNEL % str(self.nome), cave=CAVEY) <NEW_LINE> self.saida = [self.cria_saida(saida, CAMARA, "50%") for saida in CAMARAS if saida in nome] | Um tunel ligando duas camaras da caverna. :ref:`tunel`
| 62598fdcad47b63b2c5a7e1e |
class PluginsManager(object): <NEW_LINE> <INDENT> def __init__(self, pluginsPath="/usr/share/whia/plugins/"): <NEW_LINE> <INDENT> self.path = pluginsPath <NEW_LINE> self.extensions = {} <NEW_LINE> for confFile in os.listdir(self.path): <NEW_LINE> <INDENT> self.__parseConf(confFile) <NEW_LINE> <DEDENT> <DEDENT> def __addExtension(self, type, values): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.extensions[type].append(values) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> self.extensions[type] = [] <NEW_LINE> self.__addExtension(type, values) <NEW_LINE> <DEDENT> <DEDENT> def __parseConf(self, file): <NEW_LINE> <INDENT> config = FallToDefConfigParser() <NEW_LINE> config.read(os.path.join(self.path, file)) <NEW_LINE> type = config.get("extension", "type") <NEW_LINE> values = {"name": config.get("extension", "name"), "version": config.getfloat("extension", "version"), "package": config.get("extension", "package"), "class": config.get("extension", "defClass")} <NEW_LINE> values["variants"] = [] <NEW_LINE> for i in range(100): <NEW_LINE> <INDENT> if not config.has_option("variant %d" % (i,), "name"): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> values["variants"].append({"name": config.get("variant %d" % (i,), "name"), "package": config.get("variant %d" % (i,), "package", values), "class": config.get("variant %d" % (i,), "class")}) <NEW_LINE> <DEDENT> self.__addExtension(type, values) <NEW_LINE> <DEDENT> def query(self, serviceType="", name="", minVersion=0, variant=None): <NEW_LINE> <INDENT> raw = [] <NEW_LINE> res = [] <NEW_LINE> for ext in self.extensions[serviceType]: <NEW_LINE> <INDENT> if ext["name"] == name and ext["version"] >= minVersion: <NEW_LINE> <INDENT> raw.append(ext) <NEW_LINE> <DEDENT> <DEDENT> if variant != None: <NEW_LINE> <INDENT> for ext in raw: <NEW_LINE> <INDENT> for v in ext["variants"]: <NEW_LINE> <INDENT> if v["name"] == variant: <NEW_LINE> <INDENT> res.append({"name": ext["name"], "package": v["package"], "class": v["class"]}) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> res = raw <NEW_LINE> <DEDENT> return res <NEW_LINE> <DEDENT> def createModuleInstanceFromQuery(self, serviceType="", name="", minVersion=0, variant=None, confFile=""): <NEW_LINE> <INDENT> res = [] <NEW_LINE> for ext in self.query(serviceType, name, minVersion, variant): <NEW_LINE> <INDENT> mod = __import__(ext["package"], fromlist=[ext["class"]]) <NEW_LINE> res.append(getattr(mod, ext["class"])(confFile)) <NEW_LINE> <DEDENT> return res | Allows discovery of available plugins through a simple query language | 62598fdc956e5f7376df5962 |
class OperationResultInfoBaseResource(OperationWorkerResponse): <NEW_LINE> <INDENT> _attribute_map = { 'status_code': {'key': 'statusCode', 'type': 'str'}, 'headers': {'key': 'headers', 'type': '{[str]}'}, 'operation': {'key': 'operation', 'type': 'OperationResultInfoBase'}, } <NEW_LINE> def __init__( self, *, status_code: Optional[Union[str, "HttpStatusCode"]] = None, headers: Optional[Dict[str, List[str]]] = None, operation: Optional["OperationResultInfoBase"] = None, **kwargs ): <NEW_LINE> <INDENT> super(OperationResultInfoBaseResource, self).__init__(status_code=status_code, headers=headers, **kwargs) <NEW_LINE> self.operation = operation | Base class for operation result info.
:ivar status_code: HTTP Status Code of the operation. Possible values include: "Continue",
"SwitchingProtocols", "OK", "Created", "Accepted", "NonAuthoritativeInformation", "NoContent",
"ResetContent", "PartialContent", "MultipleChoices", "Ambiguous", "MovedPermanently", "Moved",
"Found", "Redirect", "SeeOther", "RedirectMethod", "NotModified", "UseProxy", "Unused",
"TemporaryRedirect", "RedirectKeepVerb", "BadRequest", "Unauthorized", "PaymentRequired",
"Forbidden", "NotFound", "MethodNotAllowed", "NotAcceptable", "ProxyAuthenticationRequired",
"RequestTimeout", "Conflict", "Gone", "LengthRequired", "PreconditionFailed",
"RequestEntityTooLarge", "RequestUriTooLong", "UnsupportedMediaType",
"RequestedRangeNotSatisfiable", "ExpectationFailed", "UpgradeRequired", "InternalServerError",
"NotImplemented", "BadGateway", "ServiceUnavailable", "GatewayTimeout",
"HttpVersionNotSupported".
:vartype status_code: str or
~azure.mgmt.recoveryservicesbackup.activestamp.models.HttpStatusCode
:ivar headers: HTTP headers associated with this operation.
:vartype headers: dict[str, list[str]]
:ivar operation: OperationResultInfoBaseResource operation.
:vartype operation:
~azure.mgmt.recoveryservicesbackup.activestamp.models.OperationResultInfoBase | 62598fdcab23a570cc2d5053 |
class CoreDefinitionVersion(AWSObject): <NEW_LINE> <INDENT> resource_type = "AWS::Greengrass::CoreDefinitionVersion" <NEW_LINE> props: PropsDictType = { "CoreDefinitionId": (str, True), "Cores": ([Core], True), } | `CoreDefinitionVersion <http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-greengrass-coredefinitionversion.html>`__ | 62598fdc187af65679d29eda |
class DeviceTokenNotForTopic(APNsException): <NEW_LINE> <INDENT> pass | The device token does not match the specified topic. | 62598fdc283ffb24f3cf3e4f |
class FakeIO(object): <NEW_LINE> <INDENT> def __init__(self, path=None, callStack=None): <NEW_LINE> <INDENT> self.path = path <NEW_LINE> self.writeContent = [] <NEW_LINE> self.writeCount = 0 <NEW_LINE> self.lastWrite = '' <NEW_LINE> self.readCount = 0 <NEW_LINE> self.callStack = callStack <NEW_LINE> self.wasCleared = False <NEW_LINE> <DEDENT> def read(self, exitCode=None, returnType=None, JSONDecodeFunc=None): <NEW_LINE> <INDENT> self.readCount += 1 <NEW_LINE> if self.callStack != None: <NEW_LINE> <INDENT> return self.getFromCallStack() <NEW_LINE> <DEDENT> <DEDENT> def write(self, content, JSONEncodeClass=None): <NEW_LINE> <INDENT> self.writeContent.append(content) <NEW_LINE> self.lastWrite = content <NEW_LINE> self.writeCount += 1 <NEW_LINE> <DEDENT> def clear(self): <NEW_LINE> <INDENT> self.wasCleared = True <NEW_LINE> <DEDENT> def getFromCallStack(self): <NEW_LINE> <INDENT> response = None <NEW_LINE> self.callStack.sort(key=lambda i: i.order) <NEW_LINE> for item in self.callStack: <NEW_LINE> <INDENT> if item.message == self.lastWrite: <NEW_LINE> <INDENT> response = item.response <NEW_LINE> self.callStack.remove(item) <NEW_LINE> <DEDENT> <DEDENT> return response | A Mock IO object to use for testing purposes | 62598fdc091ae356687051ea |
class NetworkEquipmentViewset(mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet): <NEW_LINE> <INDENT> queryset = NetworkEquipment.objects.all() <NEW_LINE> serializer_class = NetworkEquipmentSerializer <NEW_LINE> authentication_classes = (JSONWebTokenAuthentication,authentication.SessionAuthentication) <NEW_LINE> permission_classes = (IsAdminOrReadOnly,) | 网络设备,交换机、路由器等 | 62598fdcfbf16365ca79468d |
class TrafficSynchTest(BaseRepeatTest): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(TrafficSynchTest, self).__init__( test_name="Traffic intersection synch problem test", test_cmds=["sys161 kernel 'sp3 1 150 1 1 0;q'", "sys161 kernel 'sp3 5 100 10 1 0;q'", "sys161 kernel 'sp3 2 300 0 1 1;q'", "sys161 kernel 'sp3 10 80 0 1 0;q'"], num_iterations=250 ) <NEW_LINE> <DEDENT> def check_output(self, output, **kwargs): <NEW_LINE> <INDENT> print(output) | Test for A1 Traffic intersection synch problem
Runs traffic_synch.c and checks the output | 62598fdcad47b63b2c5a7e22 |
class InputDialog(GenericDialog): <NEW_LINE> <INDENT> @decorate_constructor_parameter_types([str, str, str]) <NEW_LINE> def __init__(self, title='Title', message='Message', initial_value='', *args, **kwargs): <NEW_LINE> <INDENT> super(InputDialog, self).__init__(title, message, *args, **kwargs) <NEW_LINE> self.inputText = TextInput() <NEW_LINE> self.inputText.onkeydown.connect(self.on_keydown_listener) <NEW_LINE> self.add_field('textinput', self.inputText) <NEW_LINE> self.inputText.set_text(initial_value) <NEW_LINE> self.confirm_dialog.connect(self.confirm_value) <NEW_LINE> <DEDENT> def on_keydown_listener(self, widget, value, keycode): <NEW_LINE> <INDENT> if keycode=="13": <NEW_LINE> <INDENT> self.hide() <NEW_LINE> self.inputText.set_text(value) <NEW_LINE> self.confirm_value(self) <NEW_LINE> <DEDENT> <DEDENT> @decorate_set_on_listener("(self, emitter, value)") <NEW_LINE> @decorate_event <NEW_LINE> def confirm_value(self, widget): <NEW_LINE> <INDENT> return (self.inputText.get_text(),) <NEW_LINE> <DEDENT> @decorate_explicit_alias_for_listener_registration <NEW_LINE> def set_on_confirm_value_listener(self, callback, *userdata): <NEW_LINE> <INDENT> self.confirm_value.connect(callback, *userdata) | Input Dialog widget. It can be used to query simple and short textual input to the user.
The user can confirm or dismiss the dialog with the common buttons Cancel/Ok.
The Ok button click or the ENTER key pression emits the 'confirm_dialog' event. Register the listener to it
with set_on_confirm_dialog_listener.
The Cancel button emits the 'cancel_dialog' event. Register the listener to it with set_on_cancel_dialog_listener. | 62598fdc656771135c489c40 |
class RingData(object): <NEW_LINE> <INDENT> def __init__(self, replica2part2dev_id, devs, part_shift): <NEW_LINE> <INDENT> self.devs = devs <NEW_LINE> self._replica2part2dev_id = replica2part2dev_id <NEW_LINE> self._part_shift = part_shift <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def deserialize_v1(cls, gz_file): <NEW_LINE> <INDENT> json_len, = struct.unpack('!I', gz_file.read(4)) <NEW_LINE> ring_dict = json.loads(gz_file.read(json_len)) <NEW_LINE> ring_dict['replica2part2dev_id'] = [] <NEW_LINE> partition_count = 1 << (32 - ring_dict['part_shift']) <NEW_LINE> for _ in range(ring_dict['replica_count']): <NEW_LINE> <INDENT> x = array.array('H', gz_file.read(2 * partition_count)) <NEW_LINE> ring_dict['replica2part2dev_id'].append(x) <NEW_LINE> <DEDENT> return ring_dict <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def load(cls, filename): <NEW_LINE> <INDENT> gz_file = GzipFile(filename, 'rb') <NEW_LINE> if hasattr(gz_file, '_checkReadable'): <NEW_LINE> <INDENT> gz_file = BufferedReader(gz_file) <NEW_LINE> <DEDENT> magic = gz_file.read(4) <NEW_LINE> if magic == 'R1NG': <NEW_LINE> <INDENT> version, = struct.unpack('!H', gz_file.read(2)) <NEW_LINE> if version == 1: <NEW_LINE> <INDENT> ring_data = cls.deserialize_v1(gz_file) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception('Unknown ring format version %d' % version) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> gz_file.seek(0) <NEW_LINE> ring_data = pickle.load(gz_file) <NEW_LINE> <DEDENT> if not hasattr(ring_data, 'devs'): <NEW_LINE> <INDENT> ring_data = RingData( ring_data['replica2part2dev_id'], ring_data['devs'], ring_data['part_shift'] ) <NEW_LINE> <DEDENT> return ring_data | Partitioned consistent hashing ring data (used for serialization). | 62598fdcab23a570cc2d5055 |
class Add(Instruction): <NEW_LINE> <INDENT> def __init__(self, *operands, machine): <NEW_LINE> <INDENT> super().__init__('add', *operands, machine=machine) <NEW_LINE> <DEDENT> def exec(self): <NEW_LINE> <INDENT> logexec(self) <NEW_LINE> self.pc += 1 <NEW_LINE> self.machine.registers[self.operands[0]] += self.rm1 | `add X Y` increases register X by the value of Y. | 62598fdcab23a570cc2d5056 |
class Poem(db.Model): <NEW_LINE> <INDENT> title = db.TextProperty(default="Untitled") <NEW_LINE> poet = db.StringProperty(default="Unknown") <NEW_LINE> poem = db.TextProperty(required=True) <NEW_LINE> created = db.DateTimeProperty(auto_now_add=True) | DB model class for an individual poetry post | 62598fdcadb09d7d5dc0ab49 |
class RegistrationForm(forms.Form): <NEW_LINE> <INDENT> username = forms.RegexField(regex=r'^[\w.@+-]+$', max_length=30, widget=forms.TextInput(attrs=attrs_dict), label=_("Username"), error_messages={ 'invalid': _("This value must contain " "only letters, numbers and " "underscores.") }) <NEW_LINE> email1 = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict, maxlength=75)), label=_("E-mail")) <NEW_LINE> email2 = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict, maxlength=75)), label=_("E-mail (again)")) <NEW_LINE> def clean_username(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> User.objects.get(username__iexact=self.cleaned_data['username']) <NEW_LINE> <DEDENT> except User.DoesNotExist: <NEW_LINE> <INDENT> return self.cleaned_data['username'] <NEW_LINE> <DEDENT> raise forms.ValidationError(_( "A user with that username already exists.")) <NEW_LINE> <DEDENT> def clean(self): <NEW_LINE> <INDENT> if 'email1' in self.cleaned_data and 'email2' in self.cleaned_data: <NEW_LINE> <INDENT> if self.cleaned_data['email1'] != self.cleaned_data['email2']: <NEW_LINE> <INDENT> raise forms.ValidationError(_( "The two email fields didn't match.")) <NEW_LINE> <DEDENT> <DEDENT> return self.cleaned_data | Form for registration a user account.
Validates that the requested username is not already in use, and requires
the email to be entered twice to catch typos.
Subclasses should feel free to add any additional validation they need, but
should avoid defining a ``save()`` method -- the actual saving of collected
user data is delegated to the active registration backend. | 62598fdc26238365f5fad135 |
class TimeSeriesDataType(models.Model): <NEW_LINE> <INDENT> foods = 0 <NEW_LINE> activities = 1 <NEW_LINE> sleep = 2 <NEW_LINE> body = 3 <NEW_LINE> CATEGORY_CHOICES = ( (foods, 'foods'), (activities, 'activities'), (sleep, 'sleep'), (body, 'body'), ) <NEW_LINE> intraday_support = models.BooleanField(default=False) <NEW_LINE> category = models.IntegerField( choices=CATEGORY_CHOICES, help_text='The category of the time series data, one of: {}'.format( ', '.join(['{}({})'.format(ci, cs) for ci, cs in CATEGORY_CHOICES]) )) <NEW_LINE> resource = models.CharField( max_length=128, help_text=( 'The specific time series resource. This is the string that will ' 'be used for the [resource-path] of the API url referred to in ' 'the Fitbit documentation' )) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.path() <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> unique_together = ('category', 'resource',) <NEW_LINE> ordering = ['category', 'resource'] <NEW_LINE> <DEDENT> def path(self): <NEW_LINE> <INDENT> return '/'.join([self.get_category_display(), self.resource]) | This model is intended to store information about Fitbit's time series
resources, documentation for which can be found here:
https://dev.fitbit.com/docs/food-logging/#food-or-water-time-series
https://dev.fitbit.com/docs/activity/#activity-time-series
https://dev.fitbit.com/docs/sleep/#sleep-time-series
https://dev.fitbit.com/docs/body/#body-time-series | 62598fdcc4546d3d9def756d |
class JavaProtobufContext(object): <NEW_LINE> <INDENT> def __init__(self, classpath, build_response, java_main): <NEW_LINE> <INDENT> self.classpath = resolve_classpath(classpath) <NEW_LINE> self.build_response = build_response <NEW_LINE> self.java_main = java_main <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> self.pipe = subprocess.Popen(["java", "-cp", self.classpath, self.java_main, "-multiple"], stdin=subprocess.PIPE, stdout=subprocess.PIPE) <NEW_LINE> return self <NEW_LINE> <DEDENT> def __exit__(self, type, value, traceback): <NEW_LINE> <INDENT> if self.pipe.poll() is None: <NEW_LINE> <INDENT> self.pipe.stdin.write((0).to_bytes(4, 'big')) <NEW_LINE> self.pipe.stdin.flush() <NEW_LINE> <DEDENT> <DEDENT> def process_request(self, request): <NEW_LINE> <INDENT> text = request.SerializeToString() <NEW_LINE> self.pipe.stdin.write(len(text).to_bytes(4, 'big')) <NEW_LINE> self.pipe.stdin.write(text) <NEW_LINE> self.pipe.stdin.flush() <NEW_LINE> response_length = self.pipe.stdout.read(4) <NEW_LINE> if len(response_length) < 4: <NEW_LINE> <INDENT> raise RuntimeError("Could not communicate with java process!") <NEW_LINE> <DEDENT> response_length = int.from_bytes(response_length, "big") <NEW_LINE> response_text = self.pipe.stdout.read(response_length) <NEW_LINE> response = self.build_response() <NEW_LINE> response.ParseFromString(response_text) <NEW_LINE> return response | A generic context for sending requests to a java program using protobufs in a subprocess | 62598fdc656771135c489c48 |
class AlarmSensor(SmartyBinarySensor): <NEW_LINE> <INDENT> def __init__(self, name, smarty): <NEW_LINE> <INDENT> super().__init__(name=f"{name} Alarm", device_class="problem", smarty=smarty) <NEW_LINE> <DEDENT> def update(self) -> None: <NEW_LINE> <INDENT> _LOGGER.debug("Updating sensor %s", self._name) <NEW_LINE> self._state = self._smarty.alarm | Alarm Binary Sensor. | 62598fdc187af65679d29edf |
class MultiFunction(object): <NEW_LINE> <INDENT> _handlers_cache = {} <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> algorithm_class = type(self) <NEW_LINE> cache_data = MultiFunction._handlers_cache.get(algorithm_class) <NEW_LINE> if not cache_data: <NEW_LINE> <INDENT> handler_names = [None] * len(Expr._ufl_all_classes_) <NEW_LINE> for classobject in Expr._ufl_all_classes_: <NEW_LINE> <INDENT> for c in classobject.mro(): <NEW_LINE> <INDENT> handler_name = c._ufl_handler_name_ <NEW_LINE> if hasattr(self, handler_name): <NEW_LINE> <INDENT> handler_names[classobject._ufl_typecode_] = handler_name <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> is_cutoff_type = [get_num_args(getattr(self, name)) == 2 for name in handler_names] <NEW_LINE> cache_data = (handler_names, is_cutoff_type) <NEW_LINE> MultiFunction._handlers_cache[algorithm_class] = cache_data <NEW_LINE> <DEDENT> handler_names, is_cutoff_type = cache_data <NEW_LINE> self._handlers = [getattr(self, name) for name in handler_names] <NEW_LINE> self._is_cutoff_type = is_cutoff_type <NEW_LINE> self._memoized_handler_cache = {} <NEW_LINE> <DEDENT> def __call__(self, o, *args): <NEW_LINE> <INDENT> return self._handlers[o._ufl_typecode_](o, *args) <NEW_LINE> <DEDENT> def undefined(self, o, *args): <NEW_LINE> <INDENT> error("No handler defined for %s." % o._ufl_class_.__name__) <NEW_LINE> <DEDENT> def reuse_if_untouched(self, o, *ops): <NEW_LINE> <INDENT> if all(a is b for a, b in zip(o.ufl_operands, ops)): <NEW_LINE> <INDENT> return o <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return o._ufl_expr_reconstruct_(*ops) <NEW_LINE> <DEDENT> <DEDENT> expr = undefined | Base class for collections of non-recursive expression node handlers.
Subclass this (remember to call the ``__init__`` method of this class),
and implement handler functions for each ``Expr`` type, using the lower case
handler name of the type (``exprtype._ufl_handler_name_``).
This class is optimized for efficient type based dispatch in the
``__call__``
operator via typecode based lookup of the handler function bound to the
algorithm object. Of course Python's function call overhead still applies. | 62598fdc3617ad0b5ee0671f |
class BackgroundDirective(Directive): <NEW_LINE> <INDENT> required_arguments = 1 <NEW_LINE> optional_arguments = 0 <NEW_LINE> final_argument_whitespace = True <NEW_LINE> option_spec = { 'size': directives.unchanged_required, 'position': directives.unchanged_required, 'repeat': validate_boolean} <NEW_LINE> image_extensions = 'bmp', 'jpg', 'jpeg', 'png', 'gif', 'svg' <NEW_LINE> def run(self): <NEW_LINE> <INDENT> bg = self.arguments[0].strip() <NEW_LINE> details = dict(directive=self.name) <NEW_LINE> ext = bg.rsplit('.', 1) <NEW_LINE> if len(ext) > 1 and ext[-1].lower() in self.image_extensions: <NEW_LINE> <INDENT> details.update(image=bg, **self.options) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self.options: <NEW_LINE> <INDENT> self.error("color background directive accepts no options") <NEW_LINE> <DEDENT> details.update(color=bg) <NEW_LINE> <DEDENT> pending = nodes.pending(BackgroundAttribute, details, self.block_text) <NEW_LINE> self.state_machine.document.note_pending(pending) <NEW_LINE> return [pending] | Handle reveal.js data-background-* attributes in section tag. | 62598fdcad47b63b2c5a7e2c |
class RedisSessionInterface(SessionInterface): <NEW_LINE> <INDENT> serializer = pickle <NEW_LINE> session_class = RedisSession <NEW_LINE> def __init__(self, redis, key_prefix, use_signer=False, permanent=True): <NEW_LINE> <INDENT> if redis is None: <NEW_LINE> <INDENT> from redis import Redis <NEW_LINE> redis = Redis() <NEW_LINE> <DEDENT> self.redis = redis <NEW_LINE> self.key_prefix = key_prefix <NEW_LINE> self.use_signer = use_signer <NEW_LINE> self.permanent = permanent <NEW_LINE> <DEDENT> def open_session(self, app, request): <NEW_LINE> <INDENT> sid = request.cookies.get(app.session_cookie_name) <NEW_LINE> if not sid: <NEW_LINE> <INDENT> sid = self._generate_sid() <NEW_LINE> return self.session_class(sid=sid, permanent=self.permanent) <NEW_LINE> <DEDENT> if self.use_signer: <NEW_LINE> <INDENT> signer = self._get_signer(app) <NEW_LINE> if signer is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> sid_as_bytes = signer.unsign(sid) <NEW_LINE> sid = sid_as_bytes.decode() <NEW_LINE> <DEDENT> except BadSignature: <NEW_LINE> <INDENT> sid = self._generate_sid() <NEW_LINE> return self.session_class(sid=sid, permanent=self.permanent) <NEW_LINE> <DEDENT> <DEDENT> if not PY2 and not isinstance(sid, text_type): <NEW_LINE> <INDENT> sid = sid.decode('utf-8', 'strict') <NEW_LINE> <DEDENT> val = self.redis.get(self.key_prefix + sid) <NEW_LINE> if val is not None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> data = self.serializer.loads(val) <NEW_LINE> return self.session_class(data, sid=sid) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return self.session_class(sid=sid, permanent=self.permanent) <NEW_LINE> <DEDENT> <DEDENT> return self.session_class(sid=sid, permanent=self.permanent) <NEW_LINE> <DEDENT> def save_session(self, app, session, response): <NEW_LINE> <INDENT> domain = self.get_cookie_domain(app) <NEW_LINE> path = self.get_cookie_path(app) <NEW_LINE> if not session: <NEW_LINE> <INDENT> if session.modified: <NEW_LINE> <INDENT> self.redis.delete(self.key_prefix + session.sid) <NEW_LINE> response.delete_cookie(app.session_cookie_name, domain=domain, path=path) <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> httponly = self.get_cookie_httponly(app) <NEW_LINE> secure = self.get_cookie_secure(app) <NEW_LINE> samesite = self.get_cookie_samesite(app) <NEW_LINE> expires = self.get_expiration_time(app, session) <NEW_LINE> val = self.serializer.dumps(dict(session)) <NEW_LINE> self.redis.setex(name=self.key_prefix + session.sid, value=val, time=total_seconds(app.permanent_session_lifetime)) <NEW_LINE> if self.use_signer: <NEW_LINE> <INDENT> session_id = self._get_signer(app).sign(want_bytes(session.sid)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> session_id = session.sid <NEW_LINE> <DEDENT> response.set_cookie(app.session_cookie_name, session_id, expires=expires, httponly=httponly, domain=domain, path=path, secure=secure, samesite=samesite) | Uses the Redis key-value store as a session backend.
.. versionadded:: 0.2
The `use_signer` parameter was added.
:param redis: A ``redis.Redis`` instance.
:param key_prefix: A prefix that is added to all Redis store keys.
:param use_signer: Whether to sign the session id cookie or not.
:param permanent: Whether to use permanent session or not. | 62598fdc656771135c489c4c |
class CustomPowerConfigurationCluster(PowerConfigurationCluster): <NEW_LINE> <INDENT> cluster_id = PowerConfiguration.cluster_id <NEW_LINE> MIN_VOLTS = 2.1 <NEW_LINE> MAX_VOLTS = 3.0 | Custom PowerConfigurationCluster. | 62598fdc187af65679d29ee1 |
class GlobalPrivacySettings(TLObject): <NEW_LINE> <INDENT> __slots__: List[str] = ["archive_and_mute_new_noncontact_peers"] <NEW_LINE> ID = 0xbea2f424 <NEW_LINE> QUALNAME = "types.GlobalPrivacySettings" <NEW_LINE> def __init__(self, *, archive_and_mute_new_noncontact_peers: Union[None, bool] = None) -> None: <NEW_LINE> <INDENT> self.archive_and_mute_new_noncontact_peers = archive_and_mute_new_noncontact_peers <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def read(data: BytesIO, *args: Any) -> "GlobalPrivacySettings": <NEW_LINE> <INDENT> flags = Int.read(data) <NEW_LINE> archive_and_mute_new_noncontact_peers = Bool.read(data) if flags & (1 << 0) else None <NEW_LINE> return GlobalPrivacySettings(archive_and_mute_new_noncontact_peers=archive_and_mute_new_noncontact_peers) <NEW_LINE> <DEDENT> def write(self) -> bytes: <NEW_LINE> <INDENT> data = BytesIO() <NEW_LINE> data.write(Int(self.ID, False)) <NEW_LINE> flags = 0 <NEW_LINE> flags |= (1 << 0) if self.archive_and_mute_new_noncontact_peers is not None else 0 <NEW_LINE> data.write(Int(flags)) <NEW_LINE> if self.archive_and_mute_new_noncontact_peers is not None: <NEW_LINE> <INDENT> data.write(Bool(self.archive_and_mute_new_noncontact_peers)) <NEW_LINE> <DEDENT> return data.getvalue() | This object is a constructor of the base type :obj:`~pyrogram.raw.base.GlobalPrivacySettings`.
Details:
- Layer: ``122``
- ID: ``0xbea2f424``
Parameters:
archive_and_mute_new_noncontact_peers (optional): ``bool``
See Also:
This object can be returned by 2 methods:
.. hlist::
:columns: 2
- :obj:`account.GetGlobalPrivacySettings <pyrogram.raw.functions.account.GetGlobalPrivacySettings>`
- :obj:`account.SetGlobalPrivacySettings <pyrogram.raw.functions.account.SetGlobalPrivacySettings>` | 62598fdc091ae356687051f7 |
class ACNUMJUS(TipoRegistroAC): <NEW_LINE> <INDENT> mnemonico = "NUMJUS" <NEW_LINE> def __init__(self, linha: str): <NEW_LINE> <INDENT> super().__init__(linha) <NEW_LINE> self._dados = 0 <NEW_LINE> <DEDENT> def le(self): <NEW_LINE> <INDENT> reg_usi = RegistroIn(5) <NEW_LINE> self._dados = reg_usi.le_registro(self._linha, 19) <NEW_LINE> <DEDENT> @property <NEW_LINE> def linha_escrita(self) -> str: <NEW_LINE> <INDENT> linha = f"{self._dados}".rjust(5) <NEW_LINE> return linha | Registro AC específico para alteração na usina de jusante. | 62598fdc099cdd3c636756cb |
class _LocalNameIndex(Model): <NEW_LINE> <INDENT> __metaclass__ = ABCMeta <NEW_LINE> def namespace_uri(self): <NEW_LINE> <INDENT> return self._get_config_property('namespace-uri') <NEW_LINE> <DEDENT> def set_namespace_uri(self, namespace_uri): <NEW_LINE> <INDENT> self._config['namespace-uri'] = namespace_uri <NEW_LINE> return self <NEW_LINE> <DEDENT> def localname(self): <NEW_LINE> <INDENT> return self._get_config_property('localname') <NEW_LINE> <DEDENT> def set_localname(self, localname): <NEW_LINE> <INDENT> self._config['localname'] = localname <NEW_LINE> return self | A mixin for indexes that have local names.
This is an abstract class. | 62598fdcad47b63b2c5a7e2f |
class LeafletMapView(BrowserView): <NEW_LINE> <INDENT> interface.implements(ILeafletMapView) <NEW_LINE> template = ViewPageTemplateFile('map.pt') <NEW_LINE> def __call__(self, **params): <NEW_LINE> <INDENT> params = {} <NEW_LINE> return self.template(**params) | XCGUtils an image after being edited on a webservice | 62598fdcad47b63b2c5a7e30 |
class IsSuperUser(permissions.BasePermission): <NEW_LINE> <INDENT> def has_permission(self, request, view): <NEW_LINE> <INDENT> return request.user and request.user.is_superuser | Allows access only to super-users. | 62598fdc3617ad0b5ee06723 |
class AssetBubbleDetection(object): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def SortingFunction(AB): <NEW_LINE> <INDENT> interpolatedDerivative = AB.FlorenZmirou.CubicInterpolatedSigma.derivative(AB.FlorenZmirou.Stock.maxPrice) <NEW_LINE> extrapolatedDerivative = AB.fExtrapolatedSpline.derivative(AB.FlorenZmirou.Stock.maxPrice) <NEW_LINE> return abs( interpolatedDerivative - extrapolatedDerivative ) <NEW_LINE> <DEDENT> def DetermineAssetBubble(self): <NEW_LINE> <INDENT> return (self.AssetBubbleModel.m > 1) <NEW_LINE> <DEDENT> def __init__(self,FZ): <NEW_LINE> <INDENT> self.assetBubbleList = list() <NEW_LINE> self.mMax = 10 <NEW_LINE> self.nMax = 4 <NEW_LINE> mSet1 = set(range(1,self.mMax)) <NEW_LINE> mSet2 = set(frange(0.5,1,.05)) <NEW_LINE> self.mList = mSet1.union(mSet2) <NEW_LINE> for m in self.mList: <NEW_LINE> <INDENT> self.assetBubbleList.append(AssetBubble(FZ,m,1)) <NEW_LINE> <DEDENT> self.assetBubbleList = sorted(self.assetBubbleList,key=lambda AB: AssetBubbleDetection.SortingFunction(AB)) <NEW_LINE> self.AssetBubbleModel = self.assetBubbleList[0] <NEW_LINE> self.interpolatedFunction = self.AssetBubbleModel.FlorenZmirou.CubicInterpolatedSigma <NEW_LINE> self.extrapolatedFunction = self.AssetBubbleModel.fExtrapolatedSpline <NEW_LINE> self.interpolatedDomain = self.AssetBubbleModel.FlorenZmirou.InterpolatedRange <NEW_LINE> self.extrapolatedDomain = self.AssetBubbleModel.extrapolatedPlotDomain <NEW_LINE> self.inverseVariancePlot = plot(self.interpolatedFunction,self.interpolatedDomain,color=(0,0,1)) + plot(self.extrapolatedFunction,self.extrapolatedDomain,color=(1,0,0)) <NEW_LINE> self.isAssetBubble = self.DetermineAssetBubble() | This class performs asset bubble detection over a variety of asset bubble objects
Bubble Detection Strategy
2) Suppose we know alpha = (1+m)/2, and have a floren zmirou object, FZ:
assetBubbleList = list()
for m = 1,...,9
for n = 1,2,3
assetBubbleList.append(AssetBubble(FZ,m,n))
3) From the assetBubbleList, find the best assetBubble with the closest extrapolated approximation
i.e.find f_alpha such that min_{m,n in Integers} |f'(maxPrice ) - f_alpha ' (maxPrice)|
4) Determine if f_alpha from (3) goes to infinity using proposition 3, if not infinity declare not asset bubble
5) if determined matingale, do Step D
6) declare yes/no on asset bubble. | 62598fdc26238365f5fad13f |
class TOAHModel: <NEW_LINE> <INDENT> def __init__(self, number_of_stools): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_move_seq(self): <NEW_LINE> <INDENT> return self._move_seq <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def _cheese_at(self, stool_index, stool_height): <NEW_LINE> <INDENT> if 0 <= stool_height < len(self._stools[stool_index]): <NEW_LINE> <INDENT> return self._stools[stool_index][stool_height] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> all_cheeses = [] <NEW_LINE> for height in range(self.get_number_of_cheeses()): <NEW_LINE> <INDENT> for stool in range(self.get_number_of_stools()): <NEW_LINE> <INDENT> if self._cheese_at(stool, height) is not None: <NEW_LINE> <INDENT> all_cheeses.append(self._cheese_at(stool, height)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> max_cheese_size = max([c.size for c in all_cheeses]) if len(all_cheeses) > 0 else 0 <NEW_LINE> stool_str = "=" * (2 * max_cheese_size + 1) <NEW_LINE> stool_spacing = " " <NEW_LINE> stools_str = (stool_str + stool_spacing) * self.get_number_of_stools() <NEW_LINE> def _cheese_str(size): <NEW_LINE> <INDENT> if size == 0: <NEW_LINE> <INDENT> return " " * len(stool_str) <NEW_LINE> <DEDENT> cheese_part = "-" + "--" * (size - 1) <NEW_LINE> space_filler = " " * int((len(stool_str) - len(cheese_part)) / 2) <NEW_LINE> return space_filler + cheese_part + space_filler <NEW_LINE> <DEDENT> lines = "" <NEW_LINE> for height in range(self.get_number_of_cheeses() - 1, -1, -1): <NEW_LINE> <INDENT> line = "" <NEW_LINE> for stool in range(self.get_number_of_stools()): <NEW_LINE> <INDENT> c = self._cheese_at(stool, height) <NEW_LINE> if isinstance(c, Cheese): <NEW_LINE> <INDENT> s = _cheese_str(int(c.size)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> s = _cheese_str(0) <NEW_LINE> <DEDENT> line += s + stool_spacing <NEW_LINE> <DEDENT> lines += line + "\n" <NEW_LINE> <DEDENT> lines += stools_str <NEW_LINE> return lines | Model a game of Tour Of Anne Hoy.
Model stools holding stacks of cheese, enforcing the constraint
that a larger cheese may not be placed on a smaller one. | 62598fdc099cdd3c636756cc |
class Rectangle: <NEW_LINE> <INDENT> def __init__(self, width=0, height=0): <NEW_LINE> <INDENT> if type(height) != int: <NEW_LINE> <INDENT> raise TypeError("height must be an integer") <NEW_LINE> <DEDENT> if height < 0: <NEW_LINE> <INDENT> raise ValueError("height must be >= 0") <NEW_LINE> <DEDENT> if type(width) != int: <NEW_LINE> <INDENT> raise TypeError("width must be an integer") <NEW_LINE> <DEDENT> if width < 0: <NEW_LINE> <INDENT> raise ValueError("width must be >= 0") <NEW_LINE> <DEDENT> self.__height = height <NEW_LINE> self.__width = width <NEW_LINE> <DEDENT> """Getting the private __height variable""" <NEW_LINE> @property <NEW_LINE> def height(self): <NEW_LINE> <INDENT> return self.__height <NEW_LINE> <DEDENT> """Setting the private __height variable""" <NEW_LINE> @height.setter <NEW_LINE> def height(self, value): <NEW_LINE> <INDENT> if type(value) != int: <NEW_LINE> <INDENT> raise TypeError("height must be an integer") <NEW_LINE> <DEDENT> if value < 0: <NEW_LINE> <INDENT> raise ValueError("height must be >= 0") <NEW_LINE> <DEDENT> self.__height = value <NEW_LINE> <DEDENT> """Getting the private __width variable""" <NEW_LINE> @property <NEW_LINE> def width(self): <NEW_LINE> <INDENT> return self.__width <NEW_LINE> <DEDENT> """Setting the private __width variable""" <NEW_LINE> @width.setter <NEW_LINE> def width(self, value): <NEW_LINE> <INDENT> if type(value) != int: <NEW_LINE> <INDENT> raise TypeError("width must be an integer") <NEW_LINE> <DEDENT> if value < 0: <NEW_LINE> <INDENT> raise ValueError("width must be >= 0") <NEW_LINE> <DEDENT> self.__width = value <NEW_LINE> <DEDENT> """Calculate the area of the rectangle""" <NEW_LINE> def area(self): <NEW_LINE> <INDENT> return self.__height * self.__width <NEW_LINE> <DEDENT> """Calculate the perimiter of the rectangle class""" <NEW_LINE> def perimeter(self): <NEW_LINE> <INDENT> if self.__height == 0 or self.__width == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> return (self.__height + self.__height) + (self.__width + self.__width) <NEW_LINE> <DEDENT> """String Representation of rectangle class""" <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> if self.__height == 0 or self.__width == 0: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> rect_r = (('#' * self.__width) + '\n') * (self.__height - 1) <NEW_LINE> return rect_r + ('#' * self.__width) <NEW_LINE> <DEDENT> """Representation of rectangle class""" <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return "Rectangle({:d}, {:d})".format(self.__width, self.__height) | Initializing the Rectangle class | 62598fdcad47b63b2c5a7e32 |
class Solution: <NEW_LINE> <INDENT> def jump(self, A): <NEW_LINE> <INDENT> if A is None or len(A) == 0: <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> step = [sys.maxsize for i in range(len(A))] <NEW_LINE> step[0] = 0 <NEW_LINE> for i in range(1, len(A)): <NEW_LINE> <INDENT> for j in range(i): <NEW_LINE> <INDENT> if step[j] != sys.maxsize and A[j] + j >= i: <NEW_LINE> <INDENT> step[i] = min(step[i], step[j] + 1) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return step[len(A) - 1] | @param A: A list of integers
@return: An integer | 62598fdc656771135c489c50 |
class ProgressBar(DisplayObject): <NEW_LINE> <INDENT> def __init__(self, total): <NEW_LINE> <INDENT> self.total = total <NEW_LINE> self._progress = 0 <NEW_LINE> self.html_width = '60ex' <NEW_LINE> self.text_width = 60 <NEW_LINE> self._display_id = hexlify(os.urandom(8)).decode('ascii') <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> fraction = self.progress / self.total <NEW_LINE> filled = '=' * int(fraction * self.text_width) <NEW_LINE> rest = ' ' * (self.text_width - len(filled)) <NEW_LINE> return '[{}{}] {}/{}'.format( filled, rest, self.progress, self.total, ) <NEW_LINE> <DEDENT> def _repr_html_(self): <NEW_LINE> <INDENT> return "<progress style='width:{}' max='{}' value='{}'></progress>".format( self.html_width, self.total, self.progress) <NEW_LINE> <DEDENT> def display(self): <NEW_LINE> <INDENT> display(self, display_id=self._display_id) <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> display(self, display_id=self._display_id, update=True) <NEW_LINE> <DEDENT> @property <NEW_LINE> def progress(self): <NEW_LINE> <INDENT> return self._progress <NEW_LINE> <DEDENT> @progress.setter <NEW_LINE> def progress(self, value): <NEW_LINE> <INDENT> self._progress = value <NEW_LINE> self.update() <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> self.display() <NEW_LINE> self._progress = -1 <NEW_LINE> return self <NEW_LINE> <DEDENT> def __next__(self): <NEW_LINE> <INDENT> self.progress += 1 <NEW_LINE> if self.progress < self.total: <NEW_LINE> <INDENT> return self.progress <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise StopIteration() | Progressbar supports displaying a progressbar like element
| 62598fdc099cdd3c636756cd |
class TestAmenity(unittest.TestCase): <NEW_LINE> <INDENT> def test_docstrings(self): <NEW_LINE> <INDENT> self.assertGreater(len(amenity.__doc__), 1) <NEW_LINE> self.assertGreater(len(Amenity.__doc__), 1) <NEW_LINE> <DEDENT> def test_pep8(self): <NEW_LINE> <INDENT> pep8_val = pep8.StyleGuide(quiet=True) <NEW_LINE> amenity_path = 'models/amenity.py' <NEW_LINE> result_amenity = pep8_val.check_files([amenity_path]) <NEW_LINE> self.assertEqual(result_amenity.total_errors, 0) <NEW_LINE> test_amenity_path = 'tests/test_models/test_amenity.py' <NEW_LINE> result_test_amenity = pep8_val.check_files([test_amenity_path]) <NEW_LINE> self.assertEqual(result_test_amenity.total_errors, 0) <NEW_LINE> <DEDENT> def test_new_object(self): <NEW_LINE> <INDENT> amenity_obj = Amenity() <NEW_LINE> self.assertIsInstance(amenity_obj, Amenity) <NEW_LINE> self.assertEqual(type(amenity_obj.id), str) <NEW_LINE> self.assertEqual(type(amenity_obj.created_at), datetime.datetime) <NEW_LINE> self.assertEqual(type(amenity_obj.updated_at), datetime.datetime) <NEW_LINE> pattern = '[0-9]*, [0-9]*, [0-9]*, [0-9]*, [0-9]*, [0-9]*, [0-9]*' <NEW_LINE> pattern_t = '[0-9]*-[0-9]*-[0-9]*T[0-9]*:[0-9]*:[0-9]*.[0-9]*' <NEW_LINE> datetime_patt = 'datetime.datetime(' + pattern_t + ')' <NEW_LINE> self.assertIsNotNone(re.match(pattern, amenity_obj.id)) <NEW_LINE> self.assertIsNotNone(re.match(datetime_patt, amenity_obj.created_at)) <NEW_LINE> self.assertIsNotNone(re.match(datetime_patt, amenity_obj.updated_at)) | Class for testing with unit test the Amenity class | 62598fdcad47b63b2c5a7e33 |
class CkanInternationalizationExtension(ext.InternationalizationExtension): <NEW_LINE> <INDENT> def parse(self, parser): <NEW_LINE> <INDENT> node = ext.InternationalizationExtension.parse(self, parser) <NEW_LINE> args = getattr(node.nodes[0], 'args', None) <NEW_LINE> if args: <NEW_LINE> <INDENT> for arg in args: <NEW_LINE> <INDENT> if isinstance(arg, nodes.Const): <NEW_LINE> <INDENT> value = arg.value <NEW_LINE> if isinstance(value, unicode): <NEW_LINE> <INDENT> arg.value = regularise_html(value) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return node | Custom translation to allow cleaned up html | 62598fdcd8ef3951e32c814b |
class PluginBuilder: <NEW_LINE> <INDENT> def __init__(self, context: 'core.context.Context'): <NEW_LINE> <INDENT> self._context = context <NEW_LINE> <DEDENT> def build(self, config) -> AbstractPlugin: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> plugin = self._context.getPluginByName(config["name"], config["type"]) <NEW_LINE> plugin.setup(PluginConfig.Option.Builder().build(config["config"])) <NEW_LINE> return plugin <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self._context.logger().debug("Error building plugin:") <NEW_LINE> self._context.logger().debug("> {}".format(config)) <NEW_LINE> self._context.logger().exception(e) <NEW_LINE> return NullPlugin(self._context) | Builds a plugin from a configuration item. | 62598fdc283ffb24f3cf3e65 |
class SCSDisplayMethods(_ToolShelfBlDefs, Panel): <NEW_LINE> <INDENT> bl_context = "objectmode" <NEW_LINE> bl_label = "Display Methods" <NEW_LINE> def draw(self, context): <NEW_LINE> <INDENT> layout = self.layout <NEW_LINE> scene = context.scene <NEW_LINE> if scene: <NEW_LINE> <INDENT> col = layout.column(align=True) <NEW_LINE> col.label(text='Glass Objects', icon_value=get_icon(_ICON_TYPES.mesh_glass)) <NEW_LINE> row = col.row(align=True) <NEW_LINE> row.operator('object.glass_objects_in_wireframes', text='Wires') <NEW_LINE> row.operator('object.glass_objects_textured', text='Textured') <NEW_LINE> col = layout.column(align=True) <NEW_LINE> col.label(text='Shadow Casters', icon_value=get_icon(_ICON_TYPES.mesh_shadow_caster)) <NEW_LINE> row = col.row(align=True) <NEW_LINE> row.operator('object.shadow_caster_objects_in_wireframes', text='Wires') <NEW_LINE> row.operator('object.shadow_caster_objects_textured', text='Textured') <NEW_LINE> col = layout.column(align=True) <NEW_LINE> col.label(text='Collision Locators', icon_value=get_icon(_ICON_TYPES.loc_collider)) <NEW_LINE> row = col.row(align=True) <NEW_LINE> row.operator('object.all_collision_locators_wires', text='All Wires') <NEW_LINE> row.operator('object.no_collision_locators_wires', text='No Wires') <NEW_LINE> row = col.row(align=True) <NEW_LINE> row.operator('object.all_collision_locators_faces', text='All Faces') <NEW_LINE> row.operator('object.no_collision_locators_faces', text='No Faces') | Creates a Display Methods panel in the SCS Tools tab. | 62598fdc099cdd3c636756cf |
class dim_red: <NEW_LINE> <INDENT> def __init__(self, X, Ntraj, expects_sampled, name, obs_indices=None): <NEW_LINE> <INDENT> self.X = X <NEW_LINE> self.Ntraj = Ntraj <NEW_LINE> self.expects_sampled = np.concatenate(expects_sampled, axis = 0) <NEW_LINE> if obs_indices is None: <NEW_LINE> <INDENT> self.obs_indices = range(expects_sampled.shape[-1]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.obs_indices = obs_indices <NEW_LINE> <DEDENT> self.name = name <NEW_LINE> <DEDENT> def plot_obs_v_diffusion(self, observable_names = None, s=5, which_obs = None): <NEW_LINE> <INDENT> if which_obs is None: <NEW_LINE> <INDENT> which_obs = range(self.expects_sampled.shape[-1]) <NEW_LINE> <DEDENT> make_density_scatterplts(self.X, self.expects_sampled[:,which_obs], label_shift = 0, observable_names = observable_names, s=s) <NEW_LINE> <DEDENT> def plot_diffusion_v_diffusion(self, color='percentile', max_coord1=4, max_coord2=4, observable_names=None): <NEW_LINE> <INDENT> if observable_names is None: <NEW_LINE> <INDENT> observable_names = [str(i) for i in self.obs_indices] <NEW_LINE> <DEDENT> for l in self.obs_indices: <NEW_LINE> <INDENT> fig = plt.figure(figsize=(max_coord2*10,max_coord1*10)) <NEW_LINE> if color == 'percentile': <NEW_LINE> <INDENT> cols = rankdata(self.expects_sampled[:,l], "average") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert color == 'density' <NEW_LINE> <DEDENT> for k in range(max_coord1): <NEW_LINE> <INDENT> for i in range(k+1,max_coord2): <NEW_LINE> <INDENT> x,y = self.X[:,k],self.X[:,i] <NEW_LINE> ax = fig.add_subplot(max_coord1, max_coord2, k*max_coord2+i+1) <NEW_LINE> if color == 'density': <NEW_LINE> <INDENT> xy = np.vstack([x,y]) <NEW_LINE> z = gaussian_kde(xy)(xy) <NEW_LINE> cols = np.log(z) <NEW_LINE> plt.title("Log(density). Phi" + str(i+1) + " versus Phi" + str(k+1) ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> plt.title("Observable: " + observable_names[l] + "; Coordinates: Phi" + str(i+1) + " versus Phi" + str(k+1) ) <NEW_LINE> <DEDENT> plt.scatter(x,y, c = cols) <NEW_LINE> plt.tight_layout() <NEW_LINE> <DEDENT> <DEDENT> plt.show() <NEW_LINE> if color == 'density': <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def plot_diffusion_3d(self, color_by_percentile = True, coords = [0,1,2]): <NEW_LINE> <INDENT> if len(coords) != 3: <NEW_LINE> <INDENT> raise ValueError("number of coordinates must be 3 for 3D plot.") <NEW_LINE> <DEDENT> num_obs = len(self.obs_indices) <NEW_LINE> fig = plt.figure(figsize=(num_obs*10,10)) <NEW_LINE> for l in self.obs_indices: <NEW_LINE> <INDENT> ax = fig.add_subplot(1, num_obs, l+1, projection='3d') <NEW_LINE> expects_sampled_percentile = rankdata(self.expects_sampled[:,l], "average") <NEW_LINE> ax.scatter(self.X[:,coords[0]],self.X[:,coords[1]],self.X[:,coords[2]], c = expects_sampled_percentile) <NEW_LINE> <DEDENT> plt.show() | Minimal container for dimensionality reduction. | 62598fddc4546d3d9def7576 |
class NavButton(Styled): <NEW_LINE> <INDENT> _style = "plain" <NEW_LINE> def __init__(self, title, dest, sr_path=True, nocname=False, aliases=None, target="", use_params=False, css_class=''): <NEW_LINE> <INDENT> aliases = aliases or [] <NEW_LINE> aliases = set(_force_unicode(a.rstrip('/')) for a in aliases) <NEW_LINE> if dest: <NEW_LINE> <INDENT> aliases.add(_force_unicode(dest.rstrip('/'))) <NEW_LINE> <DEDENT> self.title = title <NEW_LINE> self.dest = dest <NEW_LINE> self.selected = False <NEW_LINE> self.sr_path = sr_path <NEW_LINE> self.nocname = nocname <NEW_LINE> self.aliases = aliases <NEW_LINE> self.target = target <NEW_LINE> self.use_params = use_params <NEW_LINE> Styled.__init__(self, self._style, css_class=css_class) <NEW_LINE> <DEDENT> def build(self, base_path=''): <NEW_LINE> <INDENT> base_path = ("%s/%s/" % (base_path, self.dest)).replace('//', '/') <NEW_LINE> self.bare_path = _force_unicode(base_path.replace('//', '/')).lower() <NEW_LINE> self.bare_path = self.bare_path.rstrip('/') <NEW_LINE> self.base_path = base_path <NEW_LINE> if self.use_params: <NEW_LINE> <INDENT> base_path += query_string(dict(request.GET)) <NEW_LINE> <DEDENT> self.path = base_path.replace('//', '/') <NEW_LINE> <DEDENT> def is_selected(self): <NEW_LINE> <INDENT> stripped_path = _force_unicode(request.path.rstrip('/').lower()) <NEW_LINE> if stripped_path == self.bare_path: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> site_path = c.site.user_path.lower() + self.bare_path <NEW_LINE> if self.sr_path and stripped_path == site_path: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if self.bare_path and stripped_path.startswith(self.bare_path): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if stripped_path in self.aliases: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> def selected_title(self): <NEW_LINE> <INDENT> return self.title <NEW_LINE> <DEDENT> def cachable_attrs(self): <NEW_LINE> <INDENT> return [ ('selected', self.selected), ('title', self.title), ('path', self.path), ('sr_path', self.sr_path), ('nocname', self.nocname), ('target', self.target), ('css_class', self.css_class), ('_id', self._id), ] | Smallest unit of site navigation. A button once constructed
must also have its build() method called with the current path to
set self.path. This step is done automatically if the button is
passed to a NavMenu instance upon its construction. | 62598fdd3617ad0b5ee0672d |
class LineArrowheadStyle(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.swaggerTypes = { } <NEW_LINE> self.attributeMap = { } | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 62598fdd656771135c489c58 |
class ScoreWarForms(messages.Message): <NEW_LINE> <INDENT> items = messages.MessageField(ScoreWarForm, 1, repeated=True) | Return multiple ScoreWarForms | 62598fdd187af65679d29ee9 |
class Template(BaseUI): <NEW_LINE> <INDENT> def create_template(self, name, template_path, custom_really, temp_type, snippet, os_list=None): <NEW_LINE> <INDENT> name = name or generate_name(6) <NEW_LINE> temp_type = temp_type <NEW_LINE> self.navigator.go_to_provisioning_templates() <NEW_LINE> self.template.create(name, template_path, custom_really, temp_type, snippet, os_list) <NEW_LINE> self.assertIsNotNone(self.template.search(name)) <NEW_LINE> <DEDENT> def test_create_template(self): <NEW_LINE> <INDENT> name = generate_name(6) <NEW_LINE> temp_type = 'provision' <NEW_LINE> template_path = get_data_file(OS_TEMPLATE_DATA_FILE) <NEW_LINE> self.login.login(self.katello_user, self.katello_passwd) <NEW_LINE> self.create_template(name, template_path, True, temp_type, None) <NEW_LINE> <DEDENT> def test_create_snippet_template(self): <NEW_LINE> <INDENT> name = generate_name(6) <NEW_LINE> template_path = get_data_file(SNIPPET_DATA_FILE) <NEW_LINE> self.login.login(self.katello_user, self.katello_passwd) <NEW_LINE> self.create_template(name, template_path, True, None, True) <NEW_LINE> <DEDENT> def test_remove_template(self): <NEW_LINE> <INDENT> name = generate_name(6) <NEW_LINE> temp_type = 'provision' <NEW_LINE> template_path = get_data_file(OS_TEMPLATE_DATA_FILE) <NEW_LINE> self.login.login(self.katello_user, self.katello_passwd) <NEW_LINE> self.create_template(name, template_path, True, temp_type, None) <NEW_LINE> self.template.delete(name, True) <NEW_LINE> self.assertTrue(self.template.wait_until_element(common_locators ["notif.success"])) <NEW_LINE> self.assertIsNone(self.template.search(name)) <NEW_LINE> <DEDENT> def test_update_template(self): <NEW_LINE> <INDENT> name = generate_name(6) <NEW_LINE> new_name = generate_name(6) <NEW_LINE> temp_type = 'provision' <NEW_LINE> new_temp_type = 'PXELinux' <NEW_LINE> template_path = get_data_file(OS_TEMPLATE_DATA_FILE) <NEW_LINE> self.login.login(self.katello_user, self.katello_passwd) <NEW_LINE> self.create_template(name, template_path, True, temp_type, None) <NEW_LINE> self.template.update(name, False, new_name, None, new_temp_type) <NEW_LINE> self.assertIsNotNone(self.template.search(new_name)) <NEW_LINE> <DEDENT> def test_update_template_os(self): <NEW_LINE> <INDENT> name = generate_name(6) <NEW_LINE> new_name = generate_name(6) <NEW_LINE> temp_type = 'provision' <NEW_LINE> os_name1 = generate_name(6) <NEW_LINE> os_name2 = generate_name(6) <NEW_LINE> os_list = [os_name1, os_name2] <NEW_LINE> major_version = generate_string('numeric', 1) <NEW_LINE> template_path = get_data_file(OS_TEMPLATE_DATA_FILE) <NEW_LINE> self.login.login(self.katello_user, self.katello_passwd) <NEW_LINE> for os_name in os_list: <NEW_LINE> <INDENT> self.navigator.go_to_operating_systems() <NEW_LINE> self.operatingsys.create(os_name, major_version) <NEW_LINE> self.assertIsNotNone(self.operatingsys.search(os_name)) <NEW_LINE> <DEDENT> self.create_template(name, template_path, True, temp_type, None) <NEW_LINE> self.template.update(name, False, new_name, new_os_list=os_list) <NEW_LINE> self.assertIsNotNone(self.template.search(new_name)) | Implements Provisioning Template tests from UI | 62598fdd3617ad0b5ee06731 |
class SubtractSquare: <NEW_LINE> <INDENT> current_state: SubtractSquareState <NEW_LINE> def __init__(self, is_p1_turn: bool) -> None: <NEW_LINE> <INDENT> self.current_state = SubtractSquareState(is_p1_turn) <NEW_LINE> <DEDENT> def __eq__(self, other: Any) -> bool: <NEW_LINE> <INDENT> return (type(self) == type(other) and self.current_state.is_game_over == other.current_state.is_game_over and self.current_state.starting_number == other.current_state.starting_number and self.current_state.is_p1_turn == other.current_state.is_p1_turn) <NEW_LINE> <DEDENT> def __str__(self) -> str: <NEW_LINE> <INDENT> return "The current player is: {}, and the current value is: " "{}".format(self.current_state.get_current_player_name(), self.current_state.starting_number) <NEW_LINE> <DEDENT> def get_instructions(self) -> str: <NEW_LINE> <INDENT> instruction = 'Players take turns subtracting square numbers ' 'from the starting number. The winner is the person ' 'who subtracts to 0' <NEW_LINE> return instruction <NEW_LINE> <DEDENT> def is_over(self, current_state: SubtractSquareState) -> bool: <NEW_LINE> <INDENT> return current_state.is_game_over <NEW_LINE> <DEDENT> def str_to_move(self, move: str) -> int: <NEW_LINE> <INDENT> return int(move) <NEW_LINE> <DEDENT> def is_winner(self, player: str) -> bool: <NEW_LINE> <INDENT> if not self.current_state.is_game_over: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self.current_state.is_p1_turn: <NEW_LINE> <INDENT> if player == 'p1': <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if player == 'p2': <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False | class game SubtractSquare | 62598fddd8ef3951e32c8151 |
class WordCount(Experiment): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def setup(self): <NEW_LINE> <INDENT> self.wordcount_in = "%s/text" % get_hdfs_address() <NEW_LINE> self.wordcount_out = "%s/tmp/wc_out" % get_hdfs_address() <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> def code(): <NEW_LINE> <INDENT> run_jar("%s/examples/batch/" % get_flink_dist_path(), "WordCount.jar", args = ["--input", self.wordcount_in, "--output", self.wordcount_out], clazz = "org.apache.flink.examples.java.wordcount.WordCount") <NEW_LINE> <DEDENT> master(code) <NEW_LINE> <DEDENT> def shutdown(self): <NEW_LINE> <INDENT> master(lambda: delete_from_hdfs(self.wordcount_out)) | params: <text path> <result path> | 62598fdd26238365f5fad14f |
class ProgressService(object): <NEW_LINE> <INDENT> def __init__(self, target_instance): <NEW_LINE> <INDENT> self.target_instance = target_instance <NEW_LINE> <DEDENT> def get_pages_daily_target(self): <NEW_LINE> <INDENT> end_date = self.target_instance.end_date <NEW_LINE> today_date = datetime.datetime.today().date() <NEW_LINE> if isinstance(end_date, datetime.datetime): <NEW_LINE> <INDENT> end_date = end_date.date() <NEW_LINE> <DEDENT> if end_date < today_date: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> date_diff = end_date - datetime.datetime.today().date() <NEW_LINE> pages_diff = (self.target_instance.book.page_count - self.target_instance.current_page_progress) <NEW_LINE> daily_target = pages_diff / date_diff.days <NEW_LINE> return round(daily_target, 1) | Logic to calculate common operation for target's progress | 62598fdd4c3428357761a899 |
class FlavorsAdminNegativeTestJSON(base.BaseV2ComputeAdminTest): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setUpClass(cls): <NEW_LINE> <INDENT> super(FlavorsAdminNegativeTestJSON, cls).setUpClass() <NEW_LINE> if not test.is_extension_enabled('FlavorExtraData', 'compute'): <NEW_LINE> <INDENT> msg = "FlavorExtraData extension not enabled." <NEW_LINE> raise cls.skipException(msg) <NEW_LINE> <DEDENT> cls.client = cls.os_adm.flavors_client <NEW_LINE> cls.user_client = cls.os.flavors_client <NEW_LINE> cls.flavor_name_prefix = 'test_flavor_' <NEW_LINE> cls.ram = 512 <NEW_LINE> cls.vcpus = 1 <NEW_LINE> cls.disk = 10 <NEW_LINE> cls.ephemeral = 10 <NEW_LINE> cls.swap = 1024 <NEW_LINE> cls.rxtx = 2 <NEW_LINE> <DEDENT> @test.attr(type=['negative', 'gate']) <NEW_LINE> def test_get_flavor_details_for_deleted_flavor(self): <NEW_LINE> <INDENT> flavor_name = data_utils.rand_name(self.flavor_name_prefix) <NEW_LINE> resp, flavor = self.client.create_flavor(flavor_name, self.ram, self.vcpus, self.disk, '', ephemeral=self.ephemeral, swap=self.swap, rxtx=self.rxtx) <NEW_LINE> new_flavor_id = flavor['id'] <NEW_LINE> resp_delete, body = self.client.delete_flavor(new_flavor_id) <NEW_LINE> self.assertEqual(200, resp.status) <NEW_LINE> self.assertEqual(202, resp_delete.status) <NEW_LINE> resp, flavor = self.client.get_flavor_details(new_flavor_id) <NEW_LINE> self.assertEqual(resp.status, 200) <NEW_LINE> self.assertEqual(flavor['name'], flavor_name) <NEW_LINE> resp, flavors = self.client.list_flavors_with_detail() <NEW_LINE> self.assertEqual(resp.status, 200) <NEW_LINE> flag = True <NEW_LINE> for flavor in flavors: <NEW_LINE> <INDENT> if flavor['name'] == flavor_name: <NEW_LINE> <INDENT> flag = False <NEW_LINE> <DEDENT> <DEDENT> self.assertTrue(flag) <NEW_LINE> <DEDENT> @test.attr(type=['negative', 'gate']) <NEW_LINE> def test_create_flavor_as_user(self): <NEW_LINE> <INDENT> flavor_name = data_utils.rand_name(self.flavor_name_prefix) <NEW_LINE> new_flavor_id = str(uuid.uuid4()) <NEW_LINE> self.assertRaises(exceptions.Unauthorized, self.user_client.create_flavor, flavor_name, self.ram, self.vcpus, self.disk, new_flavor_id, ephemeral=self.ephemeral, swap=self.swap, rxtx=self.rxtx) <NEW_LINE> <DEDENT> @test.attr(type=['negative', 'gate']) <NEW_LINE> def test_delete_flavor_as_user(self): <NEW_LINE> <INDENT> self.assertRaises(exceptions.Unauthorized, self.user_client.delete_flavor, self.flavor_ref_alt) | Tests Flavors API Create and Delete that require admin privileges | 62598fddadb09d7d5dc0ab65 |
class ConductorWireLink(Base): <NEW_LINE> <INDENT> __tablename__ = 'conductor_wire_links' <NEW_LINE> conductor_id = Column(Integer, ForeignKey('conductors.id'), primary_key = True) <NEW_LINE> wire_id = Column(Integer, ForeignKey('wires.id'), primary_key = True) <NEW_LINE> conductor = relationship('Conductor', back_populates='wire_links') <NEW_LINE> wire = relationship('Wire', back_populates='conductor_links') <NEW_LINE> segment = Column(Integer) <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return "<ConductorWireLink segment:%s [%s %s]> " % (self.segment, self.conductor, self.wire) | A join table for conductor-wire association. | 62598fddc4546d3d9def757b |
class DataBoxDiskJobSecrets(JobSecrets): <NEW_LINE> <INDENT> _validation = { 'job_secrets_type': {'required': True}, 'dc_access_security_code': {'readonly': True}, 'error': {'readonly': True}, 'disk_secrets': {'readonly': True}, 'pass_key': {'readonly': True}, 'is_passkey_user_defined': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'job_secrets_type': {'key': 'jobSecretsType', 'type': 'str'}, 'dc_access_security_code': {'key': 'dcAccessSecurityCode', 'type': 'DcAccessSecurityCode'}, 'error': {'key': 'error', 'type': 'CloudError'}, 'disk_secrets': {'key': 'diskSecrets', 'type': '[DiskSecret]'}, 'pass_key': {'key': 'passKey', 'type': 'str'}, 'is_passkey_user_defined': {'key': 'isPasskeyUserDefined', 'type': 'bool'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(DataBoxDiskJobSecrets, self).__init__(**kwargs) <NEW_LINE> self.job_secrets_type = 'DataBoxDisk' <NEW_LINE> self.disk_secrets = None <NEW_LINE> self.pass_key = None <NEW_LINE> self.is_passkey_user_defined = None | The secrets related to disk job.
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 job_secrets_type: Required. Used to indicate what type of job secrets object.Constant
filled by server. Possible values include: "DataBox", "DataBoxDisk", "DataBoxHeavy".
:type job_secrets_type: str or ~azure.mgmt.databox.models.ClassDiscriminator
:ivar dc_access_security_code: Dc Access Security Code for Customer Managed Shipping.
:vartype dc_access_security_code: ~azure.mgmt.databox.models.DcAccessSecurityCode
:ivar error: Error while fetching the secrets.
:vartype error: ~azure.mgmt.databox.models.CloudError
:ivar disk_secrets: Contains the list of secrets object for that device.
:vartype disk_secrets: list[~azure.mgmt.databox.models.DiskSecret]
:ivar pass_key: PassKey for the disk Job.
:vartype pass_key: str
:ivar is_passkey_user_defined: Whether passkey was provided by user.
:vartype is_passkey_user_defined: bool | 62598fddad47b63b2c5a7e44 |
class CloudBaseRunImageSecretInfo(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.RegistryServer = None <NEW_LINE> self.UserName = None <NEW_LINE> self.Password = None <NEW_LINE> self.Email = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.RegistryServer = params.get("RegistryServer") <NEW_LINE> self.UserName = params.get("UserName") <NEW_LINE> self.Password = params.get("Password") <NEW_LINE> self.Email = params.get("Email") <NEW_LINE> memeber_set = set(params.keys()) <NEW_LINE> for name, value in vars(self).items(): <NEW_LINE> <INDENT> if name in memeber_set: <NEW_LINE> <INDENT> memeber_set.remove(name) <NEW_LINE> <DEDENT> <DEDENT> if len(memeber_set) > 0: <NEW_LINE> <INDENT> warnings.warn("%s fileds are useless." % ",".join(memeber_set)) | ImageSecretInfo的信息
| 62598fdd26238365f5fad153 |
class Poisson_s( Prior_s ): <NEW_LINE> <INDENT> _hyperparameter_names_s = [] <NEW_LINE> _bounds_s = [] <NEW_LINE> _default_theta_s0 = [] <NEW_LINE> @cached <NEW_LINE> def Lsi( T ): <NEW_LINE> <INDENT> raise TypeError('should not get to this point') <NEW_LINE> <DEDENT> @cached <NEW_LINE> def dLsi_dtheta(): <NEW_LINE> <INDENT> raise TypeError('should not get to this point') <NEW_LINE> <DEDENT> def _reproject_to_s_vec( self, *a, **kw ): <NEW_LINE> <INDENT> return A([]) <NEW_LINE> <DEDENT> @property <NEW_LINE> def _required_s_star_length( self ): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> @property <NEW_LINE> def _required_w_star_length( self ): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> @property <NEW_LINE> def H__sw( self ): <NEW_LINE> <INDENT> return zeros( (self.T, self.M) ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def G__sw( self ): <NEW_LINE> <INDENT> return ones( (self.T, self.M) ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def MAP_G__sw( self ): <NEW_LINE> <INDENT> return self.G__sw <NEW_LINE> <DEDENT> @property <NEW_LINE> def MAP_H__sw( self ): <NEW_LINE> <INDENT> return self.H__sw <NEW_LINE> <DEDENT> @property <NEW_LINE> def expected_G__sw( self ): <NEW_LINE> <INDENT> return self.G__sw <NEW_LINE> <DEDENT> @property <NEW_LINE> def expected_H__sw( self ): <NEW_LINE> <INDENT> return self.H__sw <NEW_LINE> <DEDENT> def calc_posterior_s( self, **kw ): <NEW_LINE> <INDENT> return self._calc_degenerate_posterior_s() <NEW_LINE> <DEDENT> def calc_posterior_w( self, **kw ): <NEW_LINE> <INDENT> return self._calc_degenerate_posterior_w() <NEW_LINE> <DEDENT> def calc_posterior_sw( self, **kw ): <NEW_LINE> <INDENT> self._calc_degenerate_posterior_sw() <NEW_LINE> p = self.posterior_sw <NEW_LINE> p._is_posterior = False <NEW_LINE> p.posterior_s = p <NEW_LINE> p.posterior_w = p <NEW_LINE> p._is_posterior = True <NEW_LINE> self.posterior_s = p <NEW_LINE> self.posterior_w = p <NEW_LINE> <DEDENT> @property <NEW_LINE> def S_is_degenerate( self ): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> @property <NEW_LINE> def W_is_degenerate( self ): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> @property <NEW_LINE> def S( self ): <NEW_LINE> <INDENT> return zeros( (self.T, self.rank) ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def W( self ): <NEW_LINE> <INDENT> return zeros( (self.M, self.rank) ) | No gain. | 62598fdd4c3428357761a89d |
class ConnectivityCheckResponse(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'hops': {'readonly': True}, 'connection_status': {'readonly': True}, 'avg_latency_in_ms': {'readonly': True}, 'min_latency_in_ms': {'readonly': True}, 'max_latency_in_ms': {'readonly': True}, 'probes_sent': {'readonly': True}, 'probes_failed': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'hops': {'key': 'hops', 'type': '[ConnectivityHop]'}, 'connection_status': {'key': 'connectionStatus', 'type': 'str'}, 'avg_latency_in_ms': {'key': 'avgLatencyInMs', 'type': 'long'}, 'min_latency_in_ms': {'key': 'minLatencyInMs', 'type': 'long'}, 'max_latency_in_ms': {'key': 'maxLatencyInMs', 'type': 'long'}, 'probes_sent': {'key': 'probesSent', 'type': 'long'}, 'probes_failed': {'key': 'probesFailed', 'type': 'long'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(ConnectivityCheckResponse, self).__init__(**kwargs) <NEW_LINE> self.hops = None <NEW_LINE> self.connection_status = None <NEW_LINE> self.avg_latency_in_ms = None <NEW_LINE> self.min_latency_in_ms = None <NEW_LINE> self.max_latency_in_ms = None <NEW_LINE> self.probes_sent = None <NEW_LINE> self.probes_failed = None | Information on the connectivity status.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar hops: List of hops between the source and the destination.
:vartype hops: list[~api_management_client.models.ConnectivityHop]
:ivar connection_status: The connection status. Possible values include: "Unknown",
"Connected", "Disconnected", "Degraded".
:vartype connection_status: str or ~api_management_client.models.ConnectionStatus
:ivar avg_latency_in_ms: Average latency in milliseconds.
:vartype avg_latency_in_ms: long
:ivar min_latency_in_ms: Minimum latency in milliseconds.
:vartype min_latency_in_ms: long
:ivar max_latency_in_ms: Maximum latency in milliseconds.
:vartype max_latency_in_ms: long
:ivar probes_sent: Total number of probes sent.
:vartype probes_sent: long
:ivar probes_failed: Number of failed probes.
:vartype probes_failed: long | 62598fddab23a570cc2d5066 |
class NoJunitHtmlReport(JUnitHtmlReportInterface): <NEW_LINE> <INDENT> def report(self, output_dir): <NEW_LINE> <INDENT> return None | JUnit html reporter that never produces a report. | 62598fdd50812a4eaa620ed9 |
class LiveTestBambooAPI: <NEW_LINE> <INDENT> def __init__( self, server_url: str = None, username: str = None, password: str = None, verbose: bool = False ) -> None: <NEW_LINE> <INDENT> self.__bamboo_api_client = BambooAPIClient( server_url=server_url, username=username, password=password, verbose=verbose ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def bamboo_api_client(self) -> object: <NEW_LINE> <INDENT> return self.__bamboo_api_client | Test the API against a live Bamboo server. | 62598fdd099cdd3c636756d6 |
class ThisClassSharedPtrParameter(CppClassSharedPtrParameter): <NEW_LINE> <INDENT> CTYPES = [] <NEW_LINE> cpp_class = self | Register this C++ class as pass-by-pointer parameter | 62598fddd8ef3951e32c8154 |
class UserProfile(models.Model): <NEW_LINE> <INDENT> user = models.OneToOneField(User) <NEW_LINE> name = models.CharField(max_length=64) <NEW_LINE> brief = models.CharField(max_length=140, blank=True, null=True) <NEW_LINE> sex_type = ((1, 'Male'), (0, 'Female')) <NEW_LINE> sex = models.IntegerField(choices=sex_type, default=1) <NEW_LINE> age = models.PositiveSmallIntegerField(blank=True, null=True) <NEW_LINE> email = models.EmailField() <NEW_LINE> tags = models.ManyToManyField(Tags) <NEW_LINE> head_img = models.ImageField(upload_to='statics/images') <NEW_LINE> follow_list = models.ManyToManyField('self', blank=True, related_name="my_followers", symmetrical=False) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name | 用户信息 | 62598fdd091ae3566870520f |
class Admin(object): <NEW_LINE> <INDENT> def __init__(self, company_name, ceo, email, password, contact, gst_no, _id=None): <NEW_LINE> <INDENT> self.company_name = company_name <NEW_LINE> self.ceo = ceo <NEW_LINE> self.email = email <NEW_LINE> self.password = password <NEW_LINE> self.contact = contact <NEW_LINE> self.gst_no = gst_no <NEW_LINE> self._id = uuid.uuid4().hex if _id is None else _id <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<User {}>".format(self.email) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def register(company_name, ceo, email, password, contact, gst_no): <NEW_LINE> <INDENT> company_data = Database.find_one(adminConstant.COLLECTION, {"company_name":company_name}) <NEW_LINE> admin_data = Database.find_one(adminConstant.COLLECTION, {"email": email}) <NEW_LINE> if company_data is not None: <NEW_LINE> <INDENT> raise adminErrors.CompanyAlreadyRegisteredError("Your company is already registered") <NEW_LINE> <DEDENT> if admin_data is not None: <NEW_LINE> <INDENT> raise adminErrors.AdminAlreadyRegisteredError("You are already registered") <NEW_LINE> <DEDENT> if not Utils.email_is_valid(email): <NEW_LINE> <INDENT> raise adminErrors.InvalidEmailError("You entered wrong email") <NEW_LINE> <DEDENT> Admin(company_name, ceo, email, Utils.hash_password(password), contact, gst_no).save_to_db() <NEW_LINE> return True <NEW_LINE> <DEDENT> def is_login_valid(email, password): <NEW_LINE> <INDENT> admin_data = Database.find_one(adminConstant.COLLECTION, {"email":email}) <NEW_LINE> if admin_data is None: <NEW_LINE> <INDENT> raise adminErrors.AdminNotExistsError("You are not registered") <NEW_LINE> <DEDENT> if not Utils.check_hashed_password(password, admin_data['password']): <NEW_LINE> <INDENT> raise adminErrors.IncorrectPasswordError("Your password is wrong") <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> def save_to_db(self): <NEW_LINE> <INDENT> Database.insert(adminConstant.COLLECTION, self.json()) <NEW_LINE> <DEDENT> def json(self): <NEW_LINE> <INDENT> return { "company_name": self.company_name, "ceo": self.ceo, "email": self.email, "password": self.password, "contact": self.contact, "gst_no": self.gst_no } <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def is_reset_password_valid(cls, email, old_password): <NEW_LINE> <INDENT> admin_data = Database.find_one(adminConstant.COLLECTION, {'email': email}) <NEW_LINE> if not Utils.check_hashed_password(old_password, admin_data['password']): <NEW_LINE> <INDENT> raise adminErrors.IncorrectPasswordError("Password does not match") <NEW_LINE> <DEDENT> return cls(**admin_data) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_by_email(cls, email): <NEW_LINE> <INDENT> company_id = Database.find_one(adminConstant.COLLECTION, {'email':email})['_id'] <NEW_LINE> return company_id | Class to perform admin specific functionality | 62598fdd656771135c489c64 |
class HighCard(WinPattern): <NEW_LINE> <INDENT> def __init__(self, hand): <NEW_LINE> <INDENT> super().__init__(hand) <NEW_LINE> <DEDENT> def criterion(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def values(self): <NEW_LINE> <INDENT> return self.cards[0] <NEW_LINE> <DEDENT> def trumps(self, other): <NEW_LINE> <INDENT> for i, card in enumerate(self.cards): <NEW_LINE> <INDENT> if card != other.cards[i]: <NEW_LINE> <INDENT> return other.cards[i] < card <NEW_LINE> <DEDENT> <DEDENT> raise NotImplementedError | The highest-ranking card in a hand. | 62598fddab23a570cc2d5067 |
class InstructionBase(object): <NEW_LINE> <INDENT> global_frame = GlobalFrame() <NEW_LINE> local_frame = LocalFrame() <NEW_LINE> temp_frame = TemporaryFrame() <NEW_LINE> instr_counter = -1 <NEW_LINE> instr_pointer = 1 <NEW_LINE> call_stack = [] <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> InstructionBase.instr_counter += 1 <NEW_LINE> self.frame_dict = { 'GF' : InstructionBase.global_frame, 'LF' : InstructionBase.local_frame, 'TF' : InstructionBase.temp_frame, } <NEW_LINE> <DEDENT> def ip_increment(self): <NEW_LINE> <INDENT> InstructionBase.instr_pointer += 1 <NEW_LINE> <DEDENT> def ip_set(self, value): <NEW_LINE> <INDENT> InstructionBase.instr_pointer = value <NEW_LINE> <DEDENT> def ip_get(self): <NEW_LINE> <INDENT> return InstructionBase.instr_pointer <NEW_LINE> <DEDENT> def ic_get(self): <NEW_LINE> <INDENT> return InstructionBase.instr_counter | Base class for every instruction | 62598fddab23a570cc2d5068 |
class Node(object): <NEW_LINE> <INDENT> def __init__(self, item, **kwargs): <NEW_LINE> <INDENT> self.item = item <NEW_LINE> self.parent = None <NEW_LINE> self.metadata = dict(kwargs) <NEW_LINE> self._children = [] <NEW_LINE> self._frozen = False <NEW_LINE> <DEDENT> def _frozen_add(self, child): <NEW_LINE> <INDENT> raise FrozenNode("Frozen node(s) can't be modified") <NEW_LINE> <DEDENT> def freeze(self): <NEW_LINE> <INDENT> if not self._frozen: <NEW_LINE> <INDENT> for n in self: <NEW_LINE> <INDENT> n.freeze() <NEW_LINE> <DEDENT> self.add = self._frozen_add <NEW_LINE> self._frozen = True <NEW_LINE> <DEDENT> <DEDENT> def add(self, child): <NEW_LINE> <INDENT> child.parent = self <NEW_LINE> self._children.append(child) <NEW_LINE> <DEDENT> def empty(self): <NEW_LINE> <INDENT> return self.child_count() == 0 <NEW_LINE> <DEDENT> def path_iter(self, include_self=True): <NEW_LINE> <INDENT> if include_self: <NEW_LINE> <INDENT> node = self <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> node = self.parent <NEW_LINE> <DEDENT> while node is not None: <NEW_LINE> <INDENT> yield node <NEW_LINE> node = node.parent <NEW_LINE> <DEDENT> <DEDENT> def find(self, item): <NEW_LINE> <INDENT> for n in self.dfs_iter(include_self=True): <NEW_LINE> <INDENT> if n.item == item: <NEW_LINE> <INDENT> return n <NEW_LINE> <DEDENT> <DEDENT> return None <NEW_LINE> <DEDENT> def __contains__(self, item): <NEW_LINE> <INDENT> return self.find(item) is not None <NEW_LINE> <DEDENT> def __getitem__(self, index): <NEW_LINE> <INDENT> return self._children[index] <NEW_LINE> <DEDENT> def pformat(self): <NEW_LINE> <INDENT> def _inner_pformat(node, level): <NEW_LINE> <INDENT> if level == 0: <NEW_LINE> <INDENT> yield six.text_type(node.item) <NEW_LINE> prefix = "" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> yield "__%s" % six.text_type(node.item) <NEW_LINE> prefix = " " * 2 <NEW_LINE> <DEDENT> children = list(node) <NEW_LINE> for (i, child) in enumerate(children): <NEW_LINE> <INDENT> for (j, text) in enumerate(_inner_pformat(child, level + 1)): <NEW_LINE> <INDENT> if j == 0 or i + 1 < len(children): <NEW_LINE> <INDENT> text = prefix + "|" + text <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> text = prefix + " " + text <NEW_LINE> <DEDENT> yield text <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> expected_lines = self.child_count(only_direct=False) <NEW_LINE> accumulator = six.StringIO() <NEW_LINE> for i, line in enumerate(_inner_pformat(self, 0)): <NEW_LINE> <INDENT> accumulator.write(line) <NEW_LINE> if i < expected_lines: <NEW_LINE> <INDENT> accumulator.write('\n') <NEW_LINE> <DEDENT> <DEDENT> return accumulator.getvalue() <NEW_LINE> <DEDENT> def child_count(self, only_direct=True): <NEW_LINE> <INDENT> if not only_direct: <NEW_LINE> <INDENT> count = 0 <NEW_LINE> for _node in self.dfs_iter(): <NEW_LINE> <INDENT> count += 1 <NEW_LINE> <DEDENT> return count <NEW_LINE> <DEDENT> return len(self._children) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> for c in self._children: <NEW_LINE> <INDENT> yield c <NEW_LINE> <DEDENT> <DEDENT> def index(self, item): <NEW_LINE> <INDENT> index_at = None <NEW_LINE> for (i, child) in enumerate(self._children): <NEW_LINE> <INDENT> if child.item == item: <NEW_LINE> <INDENT> index_at = i <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if index_at is None: <NEW_LINE> <INDENT> raise ValueError("%s is not contained in any child" % (item)) <NEW_LINE> <DEDENT> return index_at <NEW_LINE> <DEDENT> def dfs_iter(self, include_self=False): <NEW_LINE> <INDENT> return _DFSIter(self, include_self=include_self) | A n-ary node class that can be used to create tree structures. | 62598fdd3617ad0b5ee0673d |
class icontains(ColumnOperator): <NEW_LINE> <INDENT> def compare(self, value): <NEW_LINE> <INDENT> return self.column.ilike('%{0}%'.format(value)) | Return ``icontains`` filter function using ORM column field. | 62598fddad47b63b2c5a7e4b |
class ValueSetComposeIncludeFilter(backboneelement.BackboneElement): <NEW_LINE> <INDENT> resource_name = "ValueSetComposeIncludeFilter" <NEW_LINE> def __init__(self, jsondict=None, strict=True): <NEW_LINE> <INDENT> self.op = None <NEW_LINE> self.property = None <NEW_LINE> self.value = None <NEW_LINE> super(ValueSetComposeIncludeFilter, self).__init__(jsondict=jsondict, strict=strict) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> def elementProperties(self): <NEW_LINE> <INDENT> js = super(ValueSetComposeIncludeFilter, self).elementProperties() <NEW_LINE> js.extend([ ("op", "op", str, False, None, True), ("property", "property", str, False, None, True), ("value", "value", str, False, None, True), ]) <NEW_LINE> return js | Select codes/concepts by their properties (including relationships).
Select concepts by specify a matching criteria based on the properties
(including relationships) defined by the system. If multiple filters are
specified, they SHALL all be true. | 62598fdd3617ad0b5ee0673f |
class RemoveEmptyInlines(Stage): <NEW_LINE> <INDENT> def __call__(self, context): <NEW_LINE> <INDENT> nodes = 'a b i sup sub'.split() <NEW_LINE> xpath = ' | '.join(f'//{n}' for n in nodes) <NEW_LINE> for node in context.html.xpath(xpath): <NEW_LINE> <INDENT> if not list(node) and (not node.text or not node.text.strip()): <NEW_LINE> <INDENT> unwrap_element(node) | Remove inline elements that are empty (no children, no text or just whitespace).
Reads: context.html
Writes: context.html | 62598fddab23a570cc2d506a |
class RegisterCallbackResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.RequestId = params.get("RequestId") | RegisterCallback返回参数结构体
| 62598fdd50812a4eaa620edd |
class SessionClient(TensorFlowClient): <NEW_LINE> <INDENT> def __init__(self, session, signature_map): <NEW_LINE> <INDENT> self._session = session <NEW_LINE> super(SessionClient, self).__init__(signature_map) <NEW_LINE> <DEDENT> def predict(self, inputs, stats=None, signature_name=None, **unused_kwargs): <NEW_LINE> <INDENT> stats = stats or Stats() <NEW_LINE> stats[ENGINE] = "SessionRun" <NEW_LINE> stats[FRAMEWORK] = TENSORFLOW_FRAMEWORK_NAME <NEW_LINE> with stats.time(UNALIAS_TIME): <NEW_LINE> <INDENT> _, signature = self.get_signature(signature_name) <NEW_LINE> fetches = [output.name for output in signature.outputs.values()] <NEW_LINE> try: <NEW_LINE> <INDENT> unaliased = { signature.inputs[key].name: val for key, val in six.iteritems(inputs) } <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> raise PredictionError(PredictionError.INVALID_INPUTS, "Input mismatch: " + str(e)) <NEW_LINE> <DEDENT> <DEDENT> with stats.time(SESSION_RUN_TIME): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> outputs = self._session.run(fetches=fetches, feed_dict=unaliased) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logging.error("Exception during running the graph: " + str(e)) <NEW_LINE> raise PredictionError(PredictionError.FAILED_TO_RUN_MODEL, "Exception during running the graph: " + str(e)) <NEW_LINE> <DEDENT> <DEDENT> with stats.time(ALIAS_TIME): <NEW_LINE> <INDENT> return dict(zip(six.iterkeys(signature.outputs), outputs)) | A client for Prediction that uses Session.run. | 62598fdd187af65679d29ef1 |
class AirQualityTarget(Enum): <NEW_LINE> <INDENT> GOOD = "0004" <NEW_LINE> SENSITIVE = "0003" <NEW_LINE> DEFAULT = "0002" <NEW_LINE> VERY_SENSITIVE = "0001" | Air Quality Target. | 62598fdd26238365f5fad15d |
class CT_Orientation(BaseOxmlElement): <NEW_LINE> <INDENT> val = OptionalAttribute("val", ST_Orientation, default=ST_Orientation.MIN_MAX) | `c:xAx/c:scaling/c:orientation` element, defining category order.
Used to reverse the order categories appear in on a bar chart so they start at the
top rather than the bottom. Because we read top-to-bottom, the default way looks odd
to many and perhaps most folks. Also applicable to value and date axes. | 62598fddab23a570cc2d506b |
class JSONField(JSONFieldBase, models.TextField): <NEW_LINE> <INDENT> def dumps_for_display(self, value): <NEW_LINE> <INDENT> kwargs = {"indent": 2} <NEW_LINE> kwargs.update(self.dump_kwargs) <NEW_LINE> return json.dumps(value, **kwargs) | JSONField is a generic textfield that serializes/deserializes JSON objects
| 62598fddc4546d3d9def7581 |
class includedRiskFactorProp(SchemaProperty): <NEW_LINE> <INDENT> _prop_schema = 'includedRiskFactor' <NEW_LINE> _expected_schema = 'MedicalRiskFactor' <NEW_LINE> _enum = False <NEW_LINE> _format_as = "ForeignKey" | SchemaField for includedRiskFactor
Usage: Include in SchemaObject SchemaFields as your_django_field = includedRiskFactorProp()
schema.org description:A modifiable or non-modifiable risk factor included in the calculation, e.g. age, coexisting condition.
prop_schema returns just the property without url#
format_as is used by app templatetags based upon schema.org datatype
used to reference MedicalRiskFactor | 62598fdd656771135c489c6e |
class Office(Room): <NEW_LINE> <INDENT> def __init__(self, name): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.type = "office" <NEW_LINE> self.maximum_people = 6 <NEW_LINE> self.occupants = [] | Creates Offices for the Dojo Facility | 62598fdd50812a4eaa620edf |
@description("Detach a device from the boot pool") <NEW_LINE> class BootPoolDetachDiskCommand(Command): <NEW_LINE> <INDENT> def run(self, context, args, kwargs, opargs): <NEW_LINE> <INDENT> if not args: <NEW_LINE> <INDENT> raise CommandException('Not enough arguments provided') <NEW_LINE> <DEDENT> disk = args.pop(0) <NEW_LINE> disk = correct_disk_path(disk) <NEW_LINE> tid = context.submit_task('boot.disk.detach', disk) <NEW_LINE> return TaskPromise(context, tid) | Usage: detach_disk <disk>
Example: detach_disk ada1p2
Detach the specified device(s) from the boot pool,
reducing the number of devices in the N-way mirror. If
only one device remains, it has no redundancy. At least
one device must remain in the pool.
See 'show_disks' for a list of disks that can be detached from the pool. | 62598fdd3617ad0b5ee06744 |
class TokenLexer: <NEW_LINE> <INDENT> def __init__(self, page): <NEW_LINE> <INDENT> if not isinstance(page, Page): <NEW_LINE> <INDENT> raise TypeError('The specified page must be an instance of Page') <NEW_LINE> <DEDENT> self.__page = page <NEW_LINE> <DEDENT> def tokens(self): <NEW_LINE> <INDENT> tokens = self.__get_tokens() <NEW_LINE> for token in tokens: <NEW_LINE> <INDENT> token = TokenNormalizer.normalize(token) <NEW_LINE> if self.__is_stopword(token): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> yield token <NEW_LINE> <DEDENT> <DEDENT> def __get_tokens(self): <NEW_LINE> <INDENT> content = self.__page.content <NEW_LINE> tokens = re.split('[\s\.,!\-?:;]', content) <NEW_LINE> return tokens <NEW_LINE> <DEDENT> def __is_stopword(self, token): <NEW_LINE> <INDENT> return StopWords.is_stop_word(token) | Split a given page into a sequence of normalized tokens.
and omit stop words. | 62598fdd26238365f5fad161 |
class ConnectHandler(webapp2.RequestHandler): <NEW_LINE> <INDENT> def get(self): <NEW_LINE> <INDENT> redirect_uri = self.request.get('redirect_uri') <NEW_LINE> if redirect_uri and redirect_uri != 'deleted': <NEW_LINE> <INDENT> self.response.headers['Set-Cookie'] = 'redirect_uri=' + redirect_uri <NEW_LINE> <DEDENT> url = 'http://www.last.fm/api/auth/?api_key=' + config.LASTFM_APP_KEY + '&cb=' + config.LASTFM_REDIRECT_URL <NEW_LINE> self.redirect(url) | Initiate the Last.fm authentication dance | 62598fdd4c3428357761a8ad |
class RequestsHttpSignatureException(RequestException): <NEW_LINE> <INDENT> pass | An error occurred while constructing the HTTP Signature for your request. | 62598fddab23a570cc2d506e |
class TestTeamsApi(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.api = opendota_client.api.teams_api.TeamsApi() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_teams_get(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_teams_team_id_get(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_teams_team_id_heroes_get(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_teams_team_id_matches_get(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_teams_team_id_players_get(self): <NEW_LINE> <INDENT> pass | TeamsApi unit test stubs | 62598fdd099cdd3c636756de |
class ItemFactory(factory.Factory): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = Item <NEW_LINE> <DEDENT> name = factory.Faker( 'word', ext_word_list=random_wordlist(max_length=40, prefix='Item_') ) <NEW_LINE> quantity = factory.Faker('random_int', min=1, max=10000) <NEW_LINE> weight = factory.Faker('random_int', min=0, max=10000) <NEW_LINE> cost = factory.Faker('random_int', min=0, max=10000) <NEW_LINE> currency_denomination = factory.Faker( 'random_element', elements=Fixtures['general']['currencyDenominationList'] ) <NEW_LINE> description = factory.Faker( 'text', max_nb_chars=150 ) | Definition of item factory. | 62598fdd4c3428357761a8af |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.