code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
class ConcreteHandlerA(Handler): <NEW_LINE> <INDENT> def handle_request(self, content): <NEW_LINE> <INDENT> if (content > 0) and (content < 10): <NEW_LINE> <INDENT> print('A正在处理:%s' % content) <NEW_LINE> <DEDENT> elif self.successor is not None: <NEW_LINE> <INDENT> self.successor.handle_request(content) | 目体处理者类 | 625990bbc4546d3d9def83c5 |
class SetToDictField(z3c.form.datamanager.AttributeField): <NEW_LINE> <INDENT> key_attr = 'name' <NEW_LINE> def get(self): <NEW_LINE> <INDENT> context = self.context <NEW_LINE> if self.field.interface is not None: <NEW_LINE> <INDENT> context = self.field.interface(context) <NEW_LINE> <DEDENT> return getattr(context, self.field.__name__).values() <NEW_LINE> <DEDENT> def set(self, value): <NEW_LINE> <INDENT> if self.field.readonly: <NEW_LINE> <INDENT> raise TypeError("Can't set values on read-only fields " "(name=%s, class=%s.%s)" % (self.field.__name__, self.context.__class__.__module__, self.context.__class__.__name__)) <NEW_LINE> <DEDENT> context = self.context <NEW_LINE> if self.field.interface is not None: <NEW_LINE> <INDENT> context = self.field.interface(context) <NEW_LINE> <DEDENT> dict = {} <NEW_LINE> for item in value: <NEW_LINE> <INDENT> dict[getattr(item, self.key_attr)] = item <NEW_LINE> <DEDENT> setattr(context, self.field.__name__, dict) | Puts a Set into a Dict field. | 625990bb627d3e7fe0e090c0 |
class Optimizer(EventHandler): <NEW_LINE> <INDENT> __name__ = 'optimizer' <NEW_LINE> def __init__(self, model, optimizer_class_name, accumulate_gradients=False, **kwargs): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.optimizer = s2c(optimizer_class_name)(model.parameters(), **kwargs) <NEW_LINE> self.accumulate_gradients = accumulate_gradients <NEW_LINE> <DEDENT> def load_state_dict(self, state_dict): <NEW_LINE> <INDENT> self.optimizer.load_state_dict(state_dict) <NEW_LINE> <DEDENT> def on_fit_start(self, state): <NEW_LINE> <INDENT> if 'optimizer_state' in state: <NEW_LINE> <INDENT> self.optimizer.load_state_dict(state.optimizer_state) <NEW_LINE> <DEDENT> <DEDENT> def on_training_epoch_start(self, state): <NEW_LINE> <INDENT> if self.accumulate_gradients: <NEW_LINE> <INDENT> self.optimizer.zero_grad() <NEW_LINE> <DEDENT> <DEDENT> def on_training_batch_start(self, state): <NEW_LINE> <INDENT> if not self.accumulate_gradients: <NEW_LINE> <INDENT> self.optimizer.zero_grad() <NEW_LINE> <DEDENT> <DEDENT> def on_training_batch_end(self, state): <NEW_LINE> <INDENT> if not self.accumulate_gradients: <NEW_LINE> <INDENT> self.optimizer.step() <NEW_LINE> <DEDENT> <DEDENT> def on_training_epoch_end(self, state): <NEW_LINE> <INDENT> if self.accumulate_gradients: <NEW_LINE> <INDENT> self.optimizer.step() <NEW_LINE> <DEDENT> <DEDENT> def on_epoch_end(self, state): <NEW_LINE> <INDENT> state.update(optimizer_state=copy.deepcopy(self.optimizer.state_dict())) | Optimizer is the main event handler for optimizers. Just pass a PyTorch scheduler together with its arguments in the
configuration file. | 625990bbc4546d3d9def83c8 |
class TestFooBar(TestCase): <NEW_LINE> <INDENT> def test_blah(self): <NEW_LINE> <INDENT> self.assertTrue(1) | Foo Bar test. | 625990bbc4546d3d9def83c9 |
class EquipmentObdEngineState(object): <NEW_LINE> <INDENT> openapi_types = { 'time': 'str', 'value': 'str' } <NEW_LINE> attribute_map = { 'time': 'time', 'value': 'value' } <NEW_LINE> def __init__(self, time=None, value=None, local_vars_configuration=None): <NEW_LINE> <INDENT> if local_vars_configuration is None: <NEW_LINE> <INDENT> local_vars_configuration = Configuration() <NEW_LINE> <DEDENT> self.local_vars_configuration = local_vars_configuration <NEW_LINE> self._time = None <NEW_LINE> self._value = None <NEW_LINE> self.discriminator = None <NEW_LINE> self.time = time <NEW_LINE> self.value = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def time(self): <NEW_LINE> <INDENT> return self._time <NEW_LINE> <DEDENT> @time.setter <NEW_LINE> def time(self, time): <NEW_LINE> <INDENT> if self.local_vars_configuration.client_side_validation and time is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `time`, must not be `None`") <NEW_LINE> <DEDENT> self._time = time <NEW_LINE> <DEDENT> @property <NEW_LINE> def value(self): <NEW_LINE> <INDENT> return self._value <NEW_LINE> <DEDENT> @value.setter <NEW_LINE> def value(self, value): <NEW_LINE> <INDENT> if self.local_vars_configuration.client_side_validation and value is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `value`, must not be `None`") <NEW_LINE> <DEDENT> allowed_values = ["Off", "On", "Idle"] <NEW_LINE> if self.local_vars_configuration.client_side_validation and value not in allowed_values: <NEW_LINE> <INDENT> raise ValueError( "Invalid value for `value` ({0}), must be one of {1}" .format(value, allowed_values) ) <NEW_LINE> <DEDENT> self._value = value <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.openapi_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, EquipmentObdEngineState): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.to_dict() == other.to_dict() <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, EquipmentObdEngineState): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.to_dict() != other.to_dict() | NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually. | 625990bc187af65679d2ad14 |
class UreyBradley(BondStretch): <NEW_LINE> <INDENT> pass | A urey-bradley term -- functionally identical to a bond-stretch | 625990bcc4546d3d9def83d3 |
class ExDeploymentParams(models.Model): <NEW_LINE> <INDENT> ipAddress = CharField(max_length=16, primary_key=True) <NEW_LINE> fqdn = CharField(max_length=128, null=True) <NEW_LINE> netmask = CharField(max_length=16, default='255.255.255.0') <NEW_LINE> adminPasswd = CharField(max_length=128, null=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return '{ipAddress:' + str(self.ipAddress) + ', fqdn:' + str(self.fqdn) + ', netmask:' + str(self.netmask) + ', adminPasswd:' + str(self.adminPasswd) + '}' <NEW_LINE> <DEDENT> def export_json(self): <NEW_LINE> <INDENT> return {'ipAddress': self.ipAddress, 'fqdn': self.fqdn, 'netmask': self.netmask, 'adminPasswd': self.adminPasswd} | Parameter model class | 625990bc627d3e7fe0e090da |
class BaseDeserializer(Field): <NEW_LINE> <INDENT> __slots__ = () <NEW_LINE> empty_values = (None, "") <NEW_LINE> def __init__(self, data=None, **kwargs): <NEW_LINE> <INDENT> super(BaseDeserializer, self).__init__(**kwargs) <NEW_LINE> self._init_data(data) <NEW_LINE> <DEDENT> def _init_data(self, data): <NEW_LINE> <INDENT> self._data = data <NEW_LINE> self._errors = None <NEW_LINE> self._cleaned_data = None <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def fields(cls): <NEW_LINE> <INDENT> for name in cls.declared_fields: <NEW_LINE> <INDENT> yield name, cls.declared_fields[name] <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def errors(self): <NEW_LINE> <INDENT> if self._errors is None: <NEW_LINE> <INDENT> self.full_clean() <NEW_LINE> <DEDENT> return self._errors <NEW_LINE> <DEDENT> def is_valid(self): <NEW_LINE> <INDENT> return not self.errors <NEW_LINE> <DEDENT> def _get_error_dict(self, field_name, error): <NEW_LINE> <INDENT> if not hasattr(error, "error_dict"): <NEW_LINE> <INDENT> return {field_name or NON_FIELD_ERRORS: error.messages} <NEW_LINE> <DEDENT> return {field_name: dict(error)} <NEW_LINE> <DEDENT> def add_error(self, field_name, error): <NEW_LINE> <INDENT> error = self._get_error_dict(field_name, error) <NEW_LINE> for field_name, errors in error.items(): <NEW_LINE> <INDENT> self._errors[field_name] = errors <NEW_LINE> <DEDENT> <DEDENT> def full_clean(self): <NEW_LINE> <INDENT> self._errors = ErrorDict() <NEW_LINE> self._cleaned_data = {} <NEW_LINE> self._clean_fields() <NEW_LINE> <DEDENT> def _clean_fields(self): <NEW_LINE> <INDENT> if self._data in self.empty_values: <NEW_LINE> <INDENT> self._cleaned_data = self._data <NEW_LINE> return <NEW_LINE> <DEDENT> if not isinstance(self._data, dict): <NEW_LINE> <INDENT> error_list = ErrorList(["This field should be an object."]) <NEW_LINE> raise ValidationError(error_list) <NEW_LINE> <DEDENT> for name, field in self.declared_fields.items(): <NEW_LINE> <INDENT> value = self._data.get(name) <NEW_LINE> try: <NEW_LINE> <INDENT> value = field.clean(value) <NEW_LINE> self._cleaned_data[name] = value <NEW_LINE> if hasattr(self, "post_clean_{}".format(name)): <NEW_LINE> <INDENT> value = getattr(self, "post_clean_{}".format(name))(value) <NEW_LINE> self._cleaned_data[name] = value <NEW_LINE> <DEDENT> <DEDENT> except ValidationError as e: <NEW_LINE> <INDENT> if field.required: <NEW_LINE> <INDENT> self.add_error(name, e) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def clean(self, data): <NEW_LINE> <INDENT> self.validate(data) <NEW_LINE> self._init_data(data) <NEW_LINE> if self.errors: <NEW_LINE> <INDENT> raise ValidationError(self.errors) <NEW_LINE> <DEDENT> return self._cleaned_data <NEW_LINE> <DEDENT> @property <NEW_LINE> def data(self): <NEW_LINE> <INDENT> if not self._cleaned_data: <NEW_LINE> <INDENT> self.full_clean() <NEW_LINE> <DEDENT> return self._cleaned_data | The main implementation of Deserializers logic. Note that this class is
slightly different from the classic Form. | 625990bc627d3e7fe0e090e6 |
class WxApi(object): <NEW_LINE> <INDENT> WECHAT_CONFIG = settings.WECHAT_CONFIG <NEW_LINE> def __init__(self, ): <NEW_LINE> <INDENT> self.client = WeChatClient( app_id=self.WECHAT_CONFIG["app_id"], secret=self.WECHAT_CONFIG["secret"], ) <NEW_LINE> self.pay = WeChatPay( app_id=self.WECHAT_CONFIG["app_id"], api_key_path=self.WECHAT_CONFIG["api_key_path"], mch_id=self.WECHAT_CONFIG["mch_id"], debug=self.WECHAT_CONFIG["debug"] ) <NEW_LINE> self.oauth = WeChatOAuth( app_id=self.WECHAT_CONFIG["extra"].get("app_id", self.WECHAT_CONFIG["app_id"]), secret=self.WECHAT_CONFIG["extra"].get("secret", self.WECHAT_CONFIG["secret"]), redirect_uri=self.WECHAT_CONFIG["extra"].get( "redirect_uri", self.WECHAT_CONFIG["redirect_uri"] ) ) | 封装接口, 使用直接调用 | 625990bc627d3e7fe0e090e8 |
class FrozenInstanceError(AttributeError): <NEW_LINE> <INDENT> msg = "can't set attribute" <NEW_LINE> args = [msg] | A frozen/immutable instance has been attempted to be modified.
It mirrors the behavior of ``namedtuples`` by using the same error message
and subclassing :exc:`AttributeError`.
.. versionadded:: 16.1.0 | 625990bd187af65679d2ad23 |
class AttributeFilter(Type): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def pyre_harvest(cls, attributes, descriptor): <NEW_LINE> <INDENT> for name, attribute in attributes.items(): <NEW_LINE> <INDENT> if isinstance(attribute, descriptor) and not cls.pyre_isReserved(name): <NEW_LINE> <INDENT> yield name, attribute <NEW_LINE> <DEDENT> <DEDENT> return <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def pyre_isReserved(cls, name): <NEW_LINE> <INDENT> return name in cls.pyre_reservedNames <NEW_LINE> <DEDENT> pyre_reservedNames = set() | A base metaclass that enables attribute classification.
A common pattern in pyre is to define classes that contain special attributes that collect
declarative metadata. These attributes are processed by special purpose metaclasses and
are converted into appropriate behavior. For example, components have properties, which are
decorated descriptors that enable external configuration of component state. Similarly, XML
parsing happens with the aid of classes that capture the syntax, semantics and processing
behavior of tags by employing descriptors to capture the layout of an XML document. | 625990bd627d3e7fe0e090f6 |
class ConfiguredDoorbird(): <NEW_LINE> <INDENT> def __init__(self, device, name, events=None, custom_url=None): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> self._device = device <NEW_LINE> self._custom_url = custom_url <NEW_LINE> self._monitored_events = events <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @property <NEW_LINE> def device(self): <NEW_LINE> <INDENT> return self._device <NEW_LINE> <DEDENT> @property <NEW_LINE> def custom_url(self): <NEW_LINE> <INDENT> return self._custom_url <NEW_LINE> <DEDENT> @property <NEW_LINE> def monitored_events(self): <NEW_LINE> <INDENT> if self._monitored_events is None: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> return self._monitored_events | Attach additional information to pass along with configured device. | 625990bd627d3e7fe0e090fa |
class ValidationError(SigningError): <NEW_LINE> <INDENT> pass | Validation related errors
Usage:
raise ValidationError("error message") | 625990bd627d3e7fe0e090fc |
class ItemNotificationTextExtender(ExtenderBase): <NEW_LINE> <INDENT> layer = IShopExtensionLayer <NEW_LINE> fields = [ XTextField( name='order_text', schemata='Shop', default_content_type="text/plain", allowable_content_types=('text/plain',), default_output_type="text/plain", widget=TextAreaWidget( label=_( u'label_order_notification_text', u'Order Notification Text' ), ), ), XTextField( name='overbook_text', schemata='Shop', default_content_type="text/plain", allowable_content_types=('text/plain',), default_output_type="text/plain", widget=TextAreaWidget( label=_( u'label_overbook_notification_text', u'Overbooked Notification Text' ), ), ), ] | Schema extender for notification text.
| 625990bd627d3e7fe0e09102 |
class CreateGid(Method): <NEW_LINE> <INDENT> interfaces = ['registry'] <NEW_LINE> accepts = [ Mixed(Parameter(str, "Credential string"), Parameter(type([str]), "List of credentials")), Parameter(str, "URN or HRN of certificate owner"), Parameter(str, "Certificate string"), ] <NEW_LINE> returns = Parameter(int, "String representation of gid object") <NEW_LINE> def call(self, creds, xrn, cert=None): <NEW_LINE> <INDENT> valid_creds = self.api.auth.checkCredentials(creds, 'update') <NEW_LINE> hrn, type = urn_to_hrn(xrn) <NEW_LINE> self.api.auth.verify_object_permission(hrn) <NEW_LINE> origin_hrn = Credential(string=valid_creds[0]).get_gid_caller().get_hrn() <NEW_LINE> origin_hrn = Credential(string=valid_creds[0]).get_gid_caller().get_hrn() <NEW_LINE> self.api.logger.info("interface: %s\tcaller-hrn: %s\ttarget-hrn: %s\tmethod-name: %s"%(self.api.interface, origin_hrn, xrn, self.name)) <NEW_LINE> manager = self.api.get_interface_manager() <NEW_LINE> return manager.create_gid(self.api, xrn, cert) | Create a signed credential for the s object with the registry. In addition to being stored in the
SFA database, the appropriate records will also be created in the
PLC databases
@param xrn urn or hrn of certificate owner
@param cert caller's certificate
@param cred credential string
@return gid string representation | 625990be187af65679d2ad35 |
class IndexView(View): <NEW_LINE> <INDENT> template_name = 'pages/index.html' <NEW_LINE> context = {} <NEW_LINE> def get(self, request, *args, **kwargs): <NEW_LINE> <INDENT> if request.user.is_authenticated: <NEW_LINE> <INDENT> return redirect('/activity-feed/') <NEW_LINE> <DEDENT> return render(request, self.template_name, self.context) | view to render the index page | 625990be627d3e7fe0e09120 |
class Individual: <NEW_LINE> <INDENT> def __init__(self, bools_array): <NEW_LINE> <INDENT> self.solution = bools_array <NEW_LINE> self.fitness = -1 <NEW_LINE> <DEDENT> def get_fitness(self, problem): <NEW_LINE> <INDENT> fitness = 0 <NEW_LINE> for clause in problem["clauses"]: <NEW_LINE> <INDENT> check = False <NEW_LINE> for literal in clause: <NEW_LINE> <INDENT> if literal > 0: <NEW_LINE> <INDENT> check = check or self.solution[literal - 1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> check = check or not self.solution[abs(literal) - 1] <NEW_LINE> <DEDENT> <DEDENT> if check: <NEW_LINE> <INDENT> fitness += 1 <NEW_LINE> <DEDENT> <DEDENT> self.fitness = fitness <NEW_LINE> return fitness | Purpose: individual class that includes a get_fitness method to calculate
the fitness of an individual. | 625990bf187af65679d2ad44 |
class Vault(object): <NEW_LINE> <INDENT> def __init__(self, password): <NEW_LINE> <INDENT> self.password = password <NEW_LINE> self.vault = VaultLib(password) <NEW_LINE> <DEDENT> def load(self, stream): <NEW_LINE> <INDENT> return yaml.load(self.vault.decrypt(stream)) [0] | R/W an ansible-vault yaml file | 625990bf187af65679d2ad45 |
class BooleanProperty(ndb.BooleanProperty, _SetFromDictPropertyMixin): <NEW_LINE> <INDENT> def _set_from_dict(self, value): <NEW_LINE> <INDENT> def cast(val): <NEW_LINE> <INDENT> if val in ['false', 'False']: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return bool(val) <NEW_LINE> <DEDENT> if self._repeated: <NEW_LINE> <INDENT> check_list(value) <NEW_LINE> value = [cast(val) for val in value] <NEW_LINE> return [self._do_validate(v) for v in value] <NEW_LINE> <DEDENT> return self._do_validate(cast(value)) | BooleanProperty modified. | 625990bf627d3e7fe0e09138 |
class Macro(IPyAutocall): <NEW_LINE> <INDENT> def __init__(self,data): <NEW_LINE> <INDENT> self.value = ''.join(data).rstrip()+'\n' <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.value <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'IPython.macro.Macro(%s)' % repr(self.value) <NEW_LINE> <DEDENT> def __call__(self,*args): <NEW_LINE> <INDENT> IPython.utils.io.Term.cout.flush() <NEW_LINE> self._ip.user_ns['_margv'] = args <NEW_LINE> self._ip.run_cell(self.value) <NEW_LINE> <DEDENT> def __getstate__(self): <NEW_LINE> <INDENT> return {'value': self.value} | Simple class to store the value of macros as strings.
Macro is just a callable that executes a string of IPython
input when called.
Args to macro are available in _margv list if you need them. | 625990bf627d3e7fe0e0913e |
class CT_ShapeProperties(Fillable): <NEW_LINE> <INDENT> child_tagnames = ChildTagnames.from_nested_sequence( 'a:xfrm', EG_Geometry.__member_names__, EG_FillProperties.__member_names__, 'a:ln', EG_EffectProperties.__member_names__, 'a:scene3d', 'a:sp3d', 'a:extLst', ) <NEW_LINE> @property <NEW_LINE> def cx(self): <NEW_LINE> <INDENT> cx_str_lst = self.xpath('./a:xfrm/a:ext/@cx', namespaces=_nsmap) <NEW_LINE> if not cx_str_lst: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return Emu(cx_str_lst[0]) <NEW_LINE> <DEDENT> @property <NEW_LINE> def cy(self): <NEW_LINE> <INDENT> cy_str_lst = self.xpath('./a:xfrm/a:ext/@cy', namespaces=_nsmap) <NEW_LINE> if not cy_str_lst: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return Emu(cy_str_lst[0]) <NEW_LINE> <DEDENT> @property <NEW_LINE> def fill_element(self): <NEW_LINE> <INDENT> return self.first_child_found_in( *EG_FillProperties.__member_names__ ) <NEW_LINE> <DEDENT> def get_or_add_ln(self): <NEW_LINE> <INDENT> ln = self.ln <NEW_LINE> if ln is None: <NEW_LINE> <INDENT> ln = self._add_ln() <NEW_LINE> <DEDENT> return ln <NEW_LINE> <DEDENT> def get_or_add_xfrm(self): <NEW_LINE> <INDENT> xfrm = self.xfrm <NEW_LINE> if xfrm is None: <NEW_LINE> <INDENT> xfrm = self._add_xfrm() <NEW_LINE> <DEDENT> return xfrm <NEW_LINE> <DEDENT> @property <NEW_LINE> def ln(self): <NEW_LINE> <INDENT> return self.find(qn('a:ln')) <NEW_LINE> <DEDENT> def remove_fill_element(self): <NEW_LINE> <INDENT> self.remove_if_present(*EG_FillProperties.__member_names__) <NEW_LINE> <DEDENT> @property <NEW_LINE> def x(self): <NEW_LINE> <INDENT> x_str_lst = self.xpath('./a:xfrm/a:off/@x', namespaces=_nsmap) <NEW_LINE> if not x_str_lst: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return Emu(x_str_lst[0]) <NEW_LINE> <DEDENT> @property <NEW_LINE> def xfrm(self): <NEW_LINE> <INDENT> return self.find(qn('a:xfrm')) <NEW_LINE> <DEDENT> @property <NEW_LINE> def y(self): <NEW_LINE> <INDENT> y_str_lst = self.xpath('./a:xfrm/a:off/@y', namespaces=_nsmap) <NEW_LINE> if not y_str_lst: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return Emu(y_str_lst[0]) <NEW_LINE> <DEDENT> def _add_ln(self): <NEW_LINE> <INDENT> ln = Element('a:ln') <NEW_LINE> successor_tagnames = self.child_tagnames_after('a:ln') <NEW_LINE> self.insert_element_before(ln, *successor_tagnames) <NEW_LINE> return ln <NEW_LINE> <DEDENT> def _add_xfrm(self): <NEW_LINE> <INDENT> xfrm = Element('a:xfrm') <NEW_LINE> successor_tagnames = self.child_tagnames_after('a:xfrm') <NEW_LINE> self.insert_element_before(xfrm, *successor_tagnames) <NEW_LINE> return xfrm | Custom element class for <p:spPr> element. Shared by ``<p:sp>``,
``<p:pic>``, and ``<p:cxnSp>`` elements as well as a few more obscure
ones. | 625990bf187af65679d2ad4b |
class CFBMode(CipherMode): <NEW_LINE> <INDENT> name = "CFB" <NEW_LINE> def __init__(self, block_cipher, block_size): <NEW_LINE> <INDENT> CipherMode.__init__(self, block_cipher, block_size) <NEW_LINE> <DEDENT> def encrypt_block(self, plaintext): <NEW_LINE> <INDENT> cipher_iv = self._block_cipher.cipher_block(self._iv) <NEW_LINE> ciphertext = [i ^ j for i,j in zip (plaintext, cipher_iv)] <NEW_LINE> self._iv = ciphertext <NEW_LINE> return ciphertext <NEW_LINE> <DEDENT> def decrypt_block(self, ciphertext): <NEW_LINE> <INDENT> cipher_iv = self._block_cipher.cipher_block(self._iv) <NEW_LINE> plaintext = [i ^ j for i,j in zip (cipher_iv, ciphertext)] <NEW_LINE> self._iv = ciphertext <NEW_LINE> return plaintext | Perform CFB operation on a block and retain IV information for next operation | 625990bf187af65679d2ad4c |
class E2ETriples(SparqlQuery): <NEW_LINE> <INDENT> def __str__(self): <NEW_LINE> <INDENT> return 'SELECT DISTINCT ?subject ?object ?predicate' + self.graph + 'WHERE {?subject ?predicate ?object . FILTER isIRI(?object) }' | A class for the sparql query that returns the number of triples | 625990c0627d3e7fe0e09154 |
class DefaultBranchForm(wtf.Form): <NEW_LINE> <INDENT> branches = wtforms.SelectField( 'default_branch', [wtforms.validators.Required()], choices=[(item, item) for item in []] ) <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(DefaultBranchForm, self).__init__(*args, **kwargs) <NEW_LINE> if 'branches' in kwargs: <NEW_LINE> <INDENT> self.branches.choices = [ (branch, branch) for branch in kwargs['branches'] ] | Form to change the default branh for a repository | 625990c0627d3e7fe0e0915c |
class IotHubNameAvailabilityInfo(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'name_available': {'readonly': True}, 'reason': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'name_available': {'key': 'nameAvailable', 'type': 'bool'}, 'reason': {'key': 'reason', 'type': 'str'}, 'message': {'key': 'message', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, message: Optional[str] = None, **kwargs ): <NEW_LINE> <INDENT> super(IotHubNameAvailabilityInfo, self).__init__(**kwargs) <NEW_LINE> self.name_available = None <NEW_LINE> self.reason = None <NEW_LINE> self.message = message | The properties indicating whether a given IoT hub name is available.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar name_available: The value which indicates whether the provided name is available.
:vartype name_available: bool
:ivar reason: The reason for unavailability. Possible values include: "Invalid",
"AlreadyExists".
:vartype reason: str or ~azure.mgmt.iothub.v2018_04_01.models.IotHubNameUnavailabilityReason
:ivar message: The detailed reason message.
:vartype message: str | 625990c0627d3e7fe0e09164 |
class ApplicationGatewayAvailableSslOptions(Resource): <NEW_LINE> <INDENT> _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'predefined_policies': {'key': 'properties.predefinedPolicies', 'type': '[SubResource]'}, 'default_policy': {'key': 'properties.defaultPolicy', 'type': 'str'}, 'available_cipher_suites': {'key': 'properties.availableCipherSuites', 'type': '[str]'}, 'available_protocols': {'key': 'properties.availableProtocols', 'type': '[str]'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(ApplicationGatewayAvailableSslOptions, self).__init__(**kwargs) <NEW_LINE> self.predefined_policies = kwargs.get('predefined_policies', None) <NEW_LINE> self.default_policy = kwargs.get('default_policy', None) <NEW_LINE> self.available_cipher_suites = kwargs.get('available_cipher_suites', None) <NEW_LINE> self.available_protocols = kwargs.get('available_protocols', None) | Response for ApplicationGatewayAvailableSslOptions API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param predefined_policies: List of available Ssl predefined policy.
:type predefined_policies: list[~azure.mgmt.network.v2018_10_01.models.SubResource]
:param default_policy: Name of the Ssl predefined policy applied by default to application
gateway. Possible values include: "AppGwSslPolicy20150501", "AppGwSslPolicy20170401",
"AppGwSslPolicy20170401S".
:type default_policy: str or
~azure.mgmt.network.v2018_10_01.models.ApplicationGatewaySslPolicyName
:param available_cipher_suites: List of available Ssl cipher suites.
:type available_cipher_suites: list[str or
~azure.mgmt.network.v2018_10_01.models.ApplicationGatewaySslCipherSuite]
:param available_protocols: List of available Ssl protocols.
:type available_protocols: list[str or
~azure.mgmt.network.v2018_10_01.models.ApplicationGatewaySslProtocol] | 625990c0627d3e7fe0e09166 |
class QuickTemplateCommand(sublime_plugin.TextCommand): <NEW_LINE> <INDENT> def run(self, edit): <NEW_LINE> <INDENT> view = self.view <NEW_LINE> command_titles = [ 'QuickTemplate: Apply template', 'QuickTemplate: Create new template file', 'QuickTemplate: Create new data file', 'QuickTemplate: Open template file', 'QuickTemplate: Open data file'] <NEW_LINE> commands = [ 'quick_template_apply_template', 'quick_template_create_template', 'quick_template_create_data', 'quick_template_open_template', 'quick_template_open_data'] <NEW_LINE> view.window().show_quick_panel(command_titles, lambda index: view.run_command(commands[index]) if index >= 0 else None) | List and execute various commands | 625990c0627d3e7fe0e0916a |
class PrintingDocument(AstNode): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> AstNode.__init__(self) | The printing document class. | 625990c0187af65679d2ad60 |
class ThreadLocalCassandraSession(object): <NEW_LINE> <INDENT> def __init__(self, keyspace): <NEW_LINE> <INDENT> self.keyspace = keyspace <NEW_LINE> self.client = db.get_client(keyspace) <NEW_LINE> self._tl = threading.local() <NEW_LINE> self._tl.column_families = dict() <NEW_LINE> <DEDENT> def in_session(self, name): <NEW_LINE> <INDENT> return name in self._tl.column_families <NEW_LINE> <DEDENT> __contains__ = in_session <NEW_LINE> def __getitem__(self, name): <NEW_LINE> <INDENT> return self.get_column_family(name) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self._tl.column_families.keys()) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> for name, cf in self._tl.column_families.iteritems(): <NEW_LINE> <INDENT> yield cf <NEW_LINE> <DEDENT> <DEDENT> def flush(self): <NEW_LINE> <INDENT> for cf in self: <NEW_LINE> <INDENT> cf.flush() <NEW_LINE> <DEDENT> <DEDENT> def clear(self): <NEW_LINE> <INDENT> for cf in self: <NEW_LINE> <INDENT> cf.clear() <NEW_LINE> <DEDENT> <DEDENT> def get_column_family(self, name): <NEW_LINE> <INDENT> cf = self._tl.column_families.get(name, None) <NEW_LINE> if cf is None: <NEW_LINE> <INDENT> cf = ColumnFamily(self, name) <NEW_LINE> self._tl.column_families[name] = cf <NEW_LINE> <DEDENT> return cf <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<ThreadLocalCassandraSession keyspace=%s id=%s>" %(self.keyspace, id(self)) | A per-keyspace cassandra session | 625990c0187af65679d2ad61 |
class TestPredictionResourceRelationshipsAlertsLinks(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testPredictionResourceRelationshipsAlertsLinks(self): <NEW_LINE> <INDENT> pass | PredictionResourceRelationshipsAlertsLinks unit test stubs | 625990c1187af65679d2ad6c |
class CSAError(Exception): <NEW_LINE> <INDENT> pass | An error occurred when interfacing with CSA | 625990c1187af65679d2ad6d |
class Agent_HI_RDT_IEC_Learned(HI_RCT_Agent): <NEW_LINE> <INDENT> def __init__ (self, training_model, actors, IEC_TOL): <NEW_LINE> <INDENT> HI_RCT_Agent.__init__(self, training_model, actors) <NEW_LINE> self.IEC_TOL = IEC_TOL <NEW_LINE> self.rel_hist = dict() <NEW_LINE> self.last_choices = None <NEW_LINE> <DEDENT> def give_feedback (self, i, x, y): <NEW_LINE> <INDENT> self.history.tell(i, x, y) <NEW_LINE> rh = self.rel_hist <NEW_LINE> if (self.last_choices != None): <NEW_LINE> <INDENT> for iec_combo, iec_act in self.last_choices.items(): <NEW_LINE> <INDENT> iec_intents = [i[a] for a in iec_combo] <NEW_LINE> rel_key = iec_combo <NEW_LINE> if (not rel_key in rh): <NEW_LINE> <INDENT> rh[rel_key] = 0 <NEW_LINE> <DEDENT> rh[rel_key] += ((x == iec_act) and y == 1) or ((x != iec_act) and y == 0) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def choose (self, i): <NEW_LINE> <INDENT> self.intents.append(i) <NEW_LINE> self.iecs = iecs = HI_RCT_Hist.find_iecs(np.transpose(np.array(self.intents)), self.history, self.IEC_TOL) <NEW_LINE> iec_pluralities = [get_plurality(iec_i) for iec_i in [[i[a] for a in iec] for iec in self.iecs]] <NEW_LINE> possible_dist_combs = list(itertools.product(*iecs)) <NEW_LINE> iec_samples = [] <NEW_LINE> confidence = [] <NEW_LINE> combo_report = dict() <NEW_LINE> votes = np.zeros(len(self.X_DOM)) <NEW_LINE> for d in possible_dist_combs: <NEW_LINE> <INDENT> d = sorted(d) <NEW_LINE> rel_dist = self.history.get_actor_comb_dist(d).dist <NEW_LINE> iec_samp = np.argmax([(np.random.dirichlet(rel_dist[tuple(iec_pluralities + [x])] + 1)[1]) for x in self.X_DOM]) <NEW_LINE> iec_samples.append(iec_samp) <NEW_LINE> combo_report[tuple(d)] = iec_samp <NEW_LINE> vote_weight = 1 <NEW_LINE> rel_key = tuple(d) <NEW_LINE> if (rel_key in self.rel_hist): <NEW_LINE> <INDENT> vote_weight = self.rel_hist[rel_key] <NEW_LINE> <DEDENT> votes[iec_samp] += vote_weight <NEW_LINE> confidence.append((vote_weight, iec_samp)) <NEW_LINE> <DEDENT> self.last_choices = combo_report <NEW_LINE> confidence.sort() <NEW_LINE> most_reliable = [x[1] for x in confidence[-7:]] <NEW_LINE> return get_plurality(most_reliable) | Agent that maximizes by the intents of those known (a priori) to
be the relevant IECs of actors in the environment | 625990c1187af65679d2ad72 |
class Company(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=80, unique=True) <NEW_LINE> logo = models.ImageField(upload_to='uploads', blank=True, null=True) <NEW_LINE> slug = models.CharField(max_length=80, unique=True, blank=True) <NEW_LINE> visible = models.BooleanField(default=True) <NEW_LINE> date_added = models.DateTimeField(default=timezone.now) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<Company {name}>'.format(name=self.name) <NEW_LINE> <DEDENT> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> self.full_clean() <NEW_LINE> return super(Company, self).save(*args, **kwargs) | Company model | 625990c1627d3e7fe0e09191 |
class RedisError(ServerException): <NEW_LINE> <INDENT> def __init__(self, e): <NEW_LINE> <INDENT> super(RedisError, self).__init__( code=ResultCode.REDIS_ERROR.value, message=f"{self.__class__.__name__}: {e}" ) | Redis 发生错误时抛出此异常, e 为字符串或某异常, 当为异常实例时
使用 f-string 相当于 str(e) | 625990c2187af65679d2ad75 |
class MultiApp: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.apps = [] <NEW_LINE> <DEDENT> def add_app(self, title, func): <NEW_LINE> <INDENT> self.apps.append({ "title": title, "function": func }) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> image = 'data/logo01.png' <NEW_LINE> st.sidebar.image(image) <NEW_LINE> st.sidebar.title("Navigation") <NEW_LINE> app = st.sidebar.radio( 'Go to', self.apps, format_func=lambda app: app['title']) <NEW_LINE> app['function']() | Framework for combining multiple streamlit applications.
Usage:
def foo():
st.title("Hello Foo")
def bar():
st.title("Hello Bar")
app = MultiApp()
app.add_app("Foo", foo)
app.add_app("Bar", bar)
app.run()
It is also possible keep each application in a separate file.
import foo
import bar
app = MultiApp()
app.add_app("Foo", foo.app)
app.add_app("Bar", bar.app)
app.run() | 625990c2187af65679d2ad76 |
@MitsubaNodeTypes.register <NEW_LINE> class MtsNodeBsdf_diffuse(mitsuba_bsdf_node, Node): <NEW_LINE> <INDENT> bl_idname = 'MtsNodeBsdf_diffuse' <NEW_LINE> bl_label = 'Diffuse' <NEW_LINE> plugin_types = {'diffuse', 'roughdiffuse'} <NEW_LINE> def draw_buttons(self, context, layout): <NEW_LINE> <INDENT> layout.prop(self, 'useFastApprox') <NEW_LINE> <DEDENT> useFastApprox = BoolProperty( name='Use Fast Approximation', description='This parameter selects between the full version of the model or a fast approximation that still retains most qualitative features.', default=False ) <NEW_LINE> custom_inputs = [ {'type': 'MtsSocketFloat_alpha', 'name': 'Roughness'}, {'type': 'MtsSocketColor_diffuseReflectance', 'name': 'Diffuse Reflectance'}, ] <NEW_LINE> custom_outputs = [ {'type': 'MtsSocketBsdf', 'name': 'Bsdf'}, ] <NEW_LINE> def get_bsdf_dict(self, export_ctx): <NEW_LINE> <INDENT> params = { 'type': 'diffuse', 'reflectance': self.inputs['Diffuse Reflectance'].get_color_dict(export_ctx), } <NEW_LINE> alpha = self.inputs['Roughness'].get_float_dict(export_ctx) <NEW_LINE> if alpha: <NEW_LINE> <INDENT> params.update({ 'alpha': alpha, 'useFastApprox': self.useFastApprox, 'type': 'roughdiffuse', }) <NEW_LINE> <DEDENT> return params <NEW_LINE> <DEDENT> def set_from_dict(self, ntree, params): <NEW_LINE> <INDENT> if 'reflectance' in params: <NEW_LINE> <INDENT> self.inputs['Diffuse Reflectance'].set_color_socket(ntree, params['reflectance']) <NEW_LINE> <DEDENT> if params['type'] == 'roughdiffuse': <NEW_LINE> <INDENT> if 'alpha' in params: <NEW_LINE> <INDENT> self.inputs['Roughness'].set_float_socket(ntree, params['alpha']) <NEW_LINE> <DEDENT> if 'useFastApprox' in params: <NEW_LINE> <INDENT> self.useFastApprox = params['useFastApprox'] <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.inputs['Roughness'].default_value = 0 | Diffuse material node | 625990c2627d3e7fe0e0919d |
class PersistenceError(Exception): <NEW_LINE> <INDENT> pass | Raised when an error occurs in a Persist class | 625990c2627d3e7fe0e091a1 |
class LengthHeightUnit(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): <NEW_LINE> <INDENT> IN_ENUM = "IN" <NEW_LINE> CM = "CM" | Unit for the dimensions of length, height and width.
| 625990c2187af65679d2ad7c |
class AnetError(RuntimeError): <NEW_LINE> <INDENT> pass | Passes any errors received after the REST request comes back. | 625990c2627d3e7fe0e091a5 |
class MailAddr(object): <NEW_LINE> <INDENT> def __init__(self, email): <NEW_LINE> <INDENT> self.email_complete = email <NEW_LINE> self.email_address = self.__address_from_email() <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.email_address <NEW_LINE> <DEDENT> def __get_complete(self): <NEW_LINE> <INDENT> return self.email_complete <NEW_LINE> <DEDENT> def __address_from_email(self): <NEW_LINE> <INDENT> address = self.email_complete <NEW_LINE> idx_start = address.find('<') <NEW_LINE> if (idx_start > 0): <NEW_LINE> <INDENT> idx_end = address.rfind('>') <NEW_LINE> address = address[idx_start+1:idx_end] <NEW_LINE> logging.debug('E-mail address for '+ self.email_complete+' is: '+ address) <NEW_LINE> <DEDENT> return address <NEW_LINE> <DEDENT> address = property(fget=__str__, doc="The e-mail address in the e-mail") <NEW_LINE> complete = property(fget=__get_complete, doc="The complete email, ie: Alessio <[email protected]>") | Mail object wrapper | 625990c2187af65679d2ad7e |
class Identifier(Node): <NEW_LINE> <INDENT> def parse(self, scope): <NEW_LINE> <INDENT> names = [] <NEW_LINE> name = [] <NEW_LINE> self._subp = ( '@media', '@keyframes', '@-moz-keyframes', '@-webkit-keyframes', '@-ms-keyframes' ) <NEW_LINE> if self.tokens and hasattr(self.tokens, 'parse'): <NEW_LINE> <INDENT> self.tokens = list(utility.flatten([id.split() + [','] for id in self.tokens.parse(scope).split(',')])) <NEW_LINE> self.tokens.pop() <NEW_LINE> <DEDENT> if self.tokens and self.tokens[0] in self._subp: <NEW_LINE> <INDENT> name = list(utility.flatten(self.tokens)) <NEW_LINE> self.subparse = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.subparse = False <NEW_LINE> for n in utility.flatten(self.tokens): <NEW_LINE> <INDENT> if n == '*': <NEW_LINE> <INDENT> name.append('* ') <NEW_LINE> <DEDENT> elif n in '>+~': <NEW_LINE> <INDENT> if name and name[-1] == ' ': <NEW_LINE> <INDENT> name.pop() <NEW_LINE> <DEDENT> name.append('?%s?' % n) <NEW_LINE> <DEDENT> elif n == ',': <NEW_LINE> <INDENT> names.append(name) <NEW_LINE> name = [] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> name.append(n) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> names.append(name) <NEW_LINE> parsed = self.root(scope, names) if scope else names <NEW_LINE> self.parsed = [[i for i, j in utility.pairwise(part) if i != ' ' or (j and '?' not in j)] for part in parsed] <NEW_LINE> return self <NEW_LINE> <DEDENT> def root(self, scope, names): <NEW_LINE> <INDENT> parent = scope.scopename <NEW_LINE> if parent: <NEW_LINE> <INDENT> parent = parent[-1] <NEW_LINE> if parent.parsed: <NEW_LINE> <INDENT> return [self._pscn(part, n) if part and part[0] not in self._subp else n for part in parent.parsed for n in names] <NEW_LINE> <DEDENT> <DEDENT> return names <NEW_LINE> <DEDENT> def _pscn(self, parent, name): <NEW_LINE> <INDENT> parsed = [] <NEW_LINE> if any((n for n in name if n == '&')): <NEW_LINE> <INDENT> for n in name: <NEW_LINE> <INDENT> if n == '&': <NEW_LINE> <INDENT> if parent[-1] == ' ': <NEW_LINE> <INDENT> parent.pop() <NEW_LINE> <DEDENT> parsed.extend(parent) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> parsed.append(n) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> parsed.extend(parent) <NEW_LINE> if parent[-1] != ' ': <NEW_LINE> <INDENT> parsed.append(' ') <NEW_LINE> <DEDENT> parsed.extend(name) <NEW_LINE> <DEDENT> return parsed <NEW_LINE> <DEDENT> def raw(self, clean=False): <NEW_LINE> <INDENT> if clean: <NEW_LINE> <INDENT> return ''.join(''.join(p) for p in self.parsed).replace('?', ' ') <NEW_LINE> <DEDENT> return '%'.join('%'.join(p) for p in self.parsed).strip().strip('%') <NEW_LINE> <DEDENT> def copy(self): <NEW_LINE> <INDENT> tokens = ([t for t in self.tokens] if isinstance(self.tokens, list) else self.tokens) <NEW_LINE> return Identifier(tokens, 0) <NEW_LINE> <DEDENT> def fmt(self, fills): <NEW_LINE> <INDENT> name = ',$$'.join(''.join(p).strip() for p in self.parsed) <NEW_LINE> name = re.sub('\?(.)\?', '%(ws)s\\1%(ws)s', name) % fills <NEW_LINE> return (name.replace('$$', fills['nl']) if len(name) > 85 else name.replace('$$', fills['ws'])).replace(' ', ' ') | Identifier node. Represents block identifier.
| 625990c2187af65679d2ad82 |
class FrankelEtAl1996MwNSHMP2008(FrankelEtAl1996MblgAB1987NSHMP2008): <NEW_LINE> <INDENT> kind = "Mw" | Extend :class:`FrankelEtAl1996MblgAB1987NSHMP2008` but assumes magnitude
to be in Mw scale and therefore no conversion is applied. | 625990c3187af65679d2ad85 |
class Permission(models.Model): <NEW_LINE> <INDENT> url = models.CharField(max_length=255, verbose_name='权限', unique=True) <NEW_LINE> title = models.CharField(max_length=32, verbose_name='标题') <NEW_LINE> name = models.CharField(max_length=32, verbose_name='URL别名', unique=True) <NEW_LINE> menu = models.ForeignKey('Menu', blank=True, null=True, verbose_name='所属菜单') <NEW_LINE> parent = models.ForeignKey('Permission', blank=True, null=True, verbose_name='父权限') <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.title | 权限表
menu_id
有 表示当前的权限是二级菜单 也是父权限
没有 就是一个普通的权限
parent_id
有 表示当前的权限是一个子权限
没有 父权限 | 625990c3627d3e7fe0e091b7 |
class IndexHandler(BaseHandler): <NEW_LINE> <INDENT> def get(self): <NEW_LINE> <INDENT> self.render("index.html", {'jobs': DEFAULT_JOBS}) | Render the index. | 625990c3627d3e7fe0e091bf |
class CityAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> def response_add(self, request, obj, add_another_url='admin:admin_custom_urls_city_changelist', **kwargs): <NEW_LINE> <INDENT> return super(CityAdmin, self).response_add(request, obj, add_another_url=add_another_url, **kwargs) | A custom ModelAdmin that redirects to the changelist when the user
presses the 'Save and add another' button when adding a model instance. | 625990c3187af65679d2ad8a |
class PostPage(BlogHandler): <NEW_LINE> <INDENT> def get(self, post_id): <NEW_LINE> <INDENT> key = db.Key.from_path('Post', int(post_id), parent=blog_key()) <NEW_LINE> post = db.get(key) <NEW_LINE> comments = Comment.all().order('-created').filter('post_id =', int(post_id)) <NEW_LINE> post_likes = post.likes <NEW_LINE> username = self.user <NEW_LINE> liked = None <NEW_LINE> if self.user: <NEW_LINE> <INDENT> liked = db.GqlQuery("SELECT * FROM Like WHERE user = :1 AND post_id = :2", username, int(post_id)).get() <NEW_LINE> <DEDENT> if not post: <NEW_LINE> <INDENT> self.error(404) <NEW_LINE> return <NEW_LINE> <DEDENT> self.render("permalink.html", post = post, post_id = int(post_id), post_likes = post_likes, liked = liked, comments = comments, username = self.user) <NEW_LINE> <DEDENT> def post(self, post_id): <NEW_LINE> <INDENT> key = db.Key.from_path('Post', int(post_id), parent=blog_key()) <NEW_LINE> post = db.get(key) <NEW_LINE> if self.request.get("like"): <NEW_LINE> <INDENT> if post and self.user: <NEW_LINE> <INDENT> post.likes += 1 <NEW_LINE> like = Like(post_id = int(post_id), user = self.user) <NEW_LINE> like.put() <NEW_LINE> post.put() <NEW_LINE> time.sleep(0.2) <NEW_LINE> <DEDENT> self.redirect("/blog/%s" % post_id) <NEW_LINE> <DEDENT> elif self.request.get("unlike"): <NEW_LINE> <INDENT> if post and self.user: <NEW_LINE> <INDENT> post.likes -= 1 <NEW_LINE> like = db.GqlQuery("SELECT * FROM Like WHERE post_id = :1 AND user = :2", int(post_id), self.user) <NEW_LINE> key = like.get() <NEW_LINE> key.delete() <NEW_LINE> post.put() <NEW_LINE> time.sleep(0.2) <NEW_LINE> <DEDENT> self.redirect("/blog/%s" % post_id) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> content = self.request.get('content') <NEW_LINE> if content: <NEW_LINE> <INDENT> c = Comment( parent = blog_key(), content = content, post_id = int(post_id), author = self.user ) <NEW_LINE> c.put() <NEW_LINE> <DEDENT> self.redirect('/blog/%s' % str(post.key().id())) | Post Page class used to show the individual post the user
submitted to the blog. Along with comments on the post by other users. | 625990c3627d3e7fe0e091c3 |
class Application(tkinter.Frame): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> logger.print(3, "Application init method was called") <NEW_LINE> tkinter.Frame.__init__(self, padx=10, pady=10) <NEW_LINE> self.grid(sticky=tkinter.W+tkinter.E+tkinter.N+tkinter.S) <NEW_LINE> self.master.title("VSFTPD Log analyser") <NEW_LINE> self.master.resizable(width=False, height=True) <NEW_LINE> self.rowconfigure(6, weight=1) <NEW_LINE> self.columnconfigure(7, weight=1) <NEW_LINE> navbar = Menu(self) <NEW_LINE> self.master.config(menu=navbar) <NEW_LINE> self.nonExistingFiles = treeviewFiles(self, File.sortFiles(File.nonExistingFiles)) <NEW_LINE> self.downloadedFiles = treeviewFiles(self, File.sortFiles(File.existingFiles)[:10]) <NEW_LINE> self.userOverview = userOverview(self) <NEW_LINE> self.clientOverview = clientOverview(self) <NEW_LINE> self.viewDownloadedFiles() <NEW_LINE> <DEDENT> def emptyScreen(self): <NEW_LINE> <INDENT> logger.print(3, "Application empytyScreen method was called") <NEW_LINE> for s in self.pack_slaves(): <NEW_LINE> <INDENT> s.pack_forget() <NEW_LINE> <DEDENT> <DEDENT> def viewUserOverview(self): <NEW_LINE> <INDENT> logger.print(3, "Application viewUserOverview method was called") <NEW_LINE> self.emptyScreen() <NEW_LINE> tkinter.Label(self, text="Overzicht van alle gebruikers").pack() <NEW_LINE> self.userOverview.pack() <NEW_LINE> <DEDENT> def viewDownloadedFiles(self): <NEW_LINE> <INDENT> logger.print(3, "Application viewDownloaddeFiles method was called") <NEW_LINE> self.emptyScreen() <NEW_LINE> tkinter.Label(self, text="Most downloaded files").pack() <NEW_LINE> self.downloadedFiles.pack() <NEW_LINE> <DEDENT> def viewNonExistingFiles(self): <NEW_LINE> <INDENT> logger.print(3, "Application viewNonExistingFiles method was called") <NEW_LINE> self.emptyScreen() <NEW_LINE> tkinter.Label(self, text="Failed download Attempts").pack() <NEW_LINE> self.nonExistingFiles.pack() <NEW_LINE> <DEDENT> def viewClientOverview(self): <NEW_LINE> <INDENT> logger.print(3, "Application viewClientOverview method was called") <NEW_LINE> self.emptyScreen() <NEW_LINE> tkinter.Label(self, text="Logged on clients").pack() <NEW_LINE> self.clientOverview.pack() <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> logger.print(3, "Application close method was called") <NEW_LINE> global closeApp <NEW_LINE> closeApp = True <NEW_LINE> self.master.destroy() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def about(): <NEW_LINE> <INDENT> logger.print(3, "Application about static method was called") <NEW_LINE> text = "This application was developed by Bart Mommers, " "student at the Hogeschool Utrecht, The Netherlands.\n\n" "Truly an amazing guy!\n\n" "(He really deserves an A!)" <NEW_LINE> tkinter.messagebox.showinfo("Title", text) | Application class is user to create the application and to have its own variablepool and methods | 625990c3627d3e7fe0e091c9 |
class ShowDashboard(webapp2.RequestHandler): <NEW_LINE> <INDENT> def get(self): <NEW_LINE> <INDENT> build_status_loader = load_build_status.BuildStatusLoader() <NEW_LINE> build_status_data = build_status_loader.load_build_status_data() <NEW_LINE> last_updated_at = build_status_loader.load_last_modified_at() <NEW_LINE> if last_updated_at is None: <NEW_LINE> <INDENT> self._show_error_page("No data has yet been uploaded to the dashboard.") <NEW_LINE> return <NEW_LINE> <DEDENT> last_updated_at = last_updated_at.strftime("%Y-%m-%d %H:%M") <NEW_LINE> lkgr = build_status_loader.compute_lkgr() <NEW_LINE> coverage_loader = load_coverage.CoverageDataLoader() <NEW_LINE> small_medium_coverage_json_data = ( coverage_loader.load_coverage_json_data('small_medium_tests')) <NEW_LINE> large_coverage_json_data = ( coverage_loader.load_coverage_json_data('large_tests')) <NEW_LINE> page_template_filename = 'templates/dashboard_template.html' <NEW_LINE> self.response.write(template.render(page_template_filename, vars())) <NEW_LINE> <DEDENT> def _show_error_page(self, error_message): <NEW_LINE> <INDENT> self.response.write('<html><body>%s</body></html>' % error_message) | Shows the dashboard page.
The page is shown by grabbing data we have stored previously
in the App Engine database using the AddCoverageData handler. | 625990c3187af65679d2ad8f |
class AdjacencyList: <NEW_LINE> <INDENT> def __init__(self, size: int): <NEW_LINE> <INDENT> self._graph: List[List[Edge]] = [[] for _ in range(size)] <NEW_LINE> self._size = size <NEW_LINE> <DEDENT> def __getitem__(self, vertex: int) -> Iterator[Edge]: <NEW_LINE> <INDENT> return iter(self._graph[vertex]) <NEW_LINE> <DEDENT> @property <NEW_LINE> def size(self): <NEW_LINE> <INDENT> return self._size <NEW_LINE> <DEDENT> def add_edge(self, from_vertex: int, to_vertex: int, weight: int): <NEW_LINE> <INDENT> if weight not in (0, 1): <NEW_LINE> <INDENT> raise ValueError("Edge weight must be either 0 or 1.") <NEW_LINE> <DEDENT> if to_vertex < 0 or to_vertex >= self.size: <NEW_LINE> <INDENT> raise ValueError("Vertex indexes must be in [0; size).") <NEW_LINE> <DEDENT> self._graph[from_vertex].append(Edge(to_vertex, weight)) <NEW_LINE> <DEDENT> def get_shortest_path(self, start_vertex: int, finish_vertex: int) -> int: <NEW_LINE> <INDENT> queue = deque([start_vertex]) <NEW_LINE> distances = [None for i in range(self.size)] <NEW_LINE> distances[start_vertex] = 0 <NEW_LINE> while queue: <NEW_LINE> <INDENT> current_vertex = queue.popleft() <NEW_LINE> current_distance = distances[current_vertex] <NEW_LINE> for edge in self[current_vertex]: <NEW_LINE> <INDENT> new_distance = current_distance + edge.weight <NEW_LINE> if ( distances[edge.destination_vertex] is not None and new_distance >= distances[edge.destination_vertex] ): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> distances[edge.destination_vertex] = new_distance <NEW_LINE> if edge.weight == 0: <NEW_LINE> <INDENT> queue.appendleft(edge.destination_vertex) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> queue.append(edge.destination_vertex) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if distances[finish_vertex] is None: <NEW_LINE> <INDENT> raise ValueError("No path from start_vertex to finish_vertex.") <NEW_LINE> <DEDENT> return distances[finish_vertex] | Graph adjacency list. | 625990c3627d3e7fe0e091cd |
class EnvelopeTwo(Envelope): <NEW_LINE> <INDENT> def __init__(self, height: int, width: int) -> None: <NEW_LINE> <INDENT> self._height = SafeProperty(EnvelopeHeight(height)) <NEW_LINE> self._width = SafeProperty(EnvelopeWidth(width)) <NEW_LINE> <DEDENT> def size(self) -> int: <NEW_LINE> <INDENT> return self._height.value() * self._width.value() <NEW_LINE> <DEDENT> def __str__(self) -> str: <NEW_LINE> <INDENT> return "{} has size {}x{}".format(self.__class__.__name__, self._height.value(), self._width.value()) | Concrete envelope object. | 625990c4187af65679d2ad95 |
class RadioButtonWidget(QWidget): <NEW_LINE> <INDENT> def __init__(self, label, instruction, button_list): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.title_label = QLabel(label) <NEW_LINE> self.radio_group_box = QGroupBox(instruction) <NEW_LINE> self.radio_button_group = QButtonGroup() <NEW_LINE> self.radio_button_list = [] <NEW_LINE> for each in button_list: <NEW_LINE> <INDENT> self.radio_button_list.append(QRadioButton(each)) <NEW_LINE> <DEDENT> self.radio_button_list[0].setChecked(True) <NEW_LINE> self.radio_button_layout = QVBoxLayout() <NEW_LINE> counter = 1 <NEW_LINE> for each in self.radio_button_list: <NEW_LINE> <INDENT> self.radio_button_layout.addWidget(each) <NEW_LINE> self.radio_button_group.addButton(each) <NEW_LINE> self.radio_button_group.setId(each, counter) <NEW_LINE> counter += 1 <NEW_LINE> <DEDENT> self.radio_group_box.setLayout(self.radio_button_layout) <NEW_LINE> self.main_layout = QVBoxLayout() <NEW_LINE> self.main_layout.addWidget(self.title_label) <NEW_LINE> self.main_layout.addWidget(self.radio_group_box) <NEW_LINE> self.setLayout(self.main_layout) <NEW_LINE> <DEDENT> def selected_button(self): <NEW_LINE> <INDENT> return self.radio_button_group.checkedId() | creates the radio button with options for crops | 625990c4187af65679d2ad97 |
class one_of: <NEW_LINE> <INDENT> def __init__(self, label, *args): <NEW_LINE> <INDENT> self.label = label <NEW_LINE> self.rules = list(args) <NEW_LINE> <DEDENT> def validate(self, dwelling): <NEW_LINE> <INDENT> passed = 0 <NEW_LINE> for r in self.rules: <NEW_LINE> <INDENT> thispassed, newmsgs = r.validate(dwelling) <NEW_LINE> if thispassed: <NEW_LINE> <INDENT> passed += 1 <NEW_LINE> <DEDENT> <DEDENT> if passed == 0: <NEW_LINE> <INDENT> return False, ["No matches found for %s" % (self.label,), ] <NEW_LINE> <DEDENT> elif passed > 1: <NEW_LINE> <INDENT> return False, ["More than one match found for %s" % (self.label,), ] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True, [] | Only one subrule is allowed to validate | 625990c4627d3e7fe0e091eb |
class FeedbackList(MyBaseHandler): <NEW_LINE> <INDENT> @token_required() <NEW_LINE> @my_async_jsonp <NEW_LINE> @my_async_paginator_list <NEW_LINE> async def get(self): <NEW_LINE> <INDENT> mongo_coon = self.get_async_mongo() <NEW_LINE> res = await mongo_coon['feedback_msg'].find({}) <NEW_LINE> list = [] <NEW_LINE> for i in res: <NEW_LINE> <INDENT> list.append(i.to_list()) <NEW_LINE> <DEDENT> return list | 查看列表 | 625990c4627d3e7fe0e091ed |
class BitField(object): <NEW_LINE> <INDENT> def __init__(self, from_bit: int, to_bit: int): <NEW_LINE> <INDENT> assert 0 <= from_bit < WORD_SIZE <NEW_LINE> assert from_bit <= to_bit <= WORD_SIZE <NEW_LINE> self.from_bit = from_bit <NEW_LINE> self.to_bit = to_bit <NEW_LINE> width = (to_bit - from_bit) + 1 <NEW_LINE> self.mask = 0 <NEW_LINE> for bit in range(width): <NEW_LINE> <INDENT> self.mask = (self.mask << 1) | 1 <NEW_LINE> <DEDENT> <DEDENT> def extract(self, word: int) -> int: <NEW_LINE> <INDENT> return (word >> self.from_bit) & self.mask <NEW_LINE> <DEDENT> def insert(self, value: int, word: int) -> int: <NEW_LINE> <INDENT> value = value & self.mask <NEW_LINE> return word | (value << self.from_bit) <NEW_LINE> <DEDENT> def extract_signed(self, word: int) -> int: <NEW_LINE> <INDENT> unsigned = self.extract(word) <NEW_LINE> return sign_extend(unsigned, 1 + self.to_bit - self.from_bit) | A BitField object extracts specified
bitfields from an integer. | 625990c4627d3e7fe0e091f1 |
class IPlaylistBlock(IBlock): <NEW_LINE> <INDENT> referenced_playlist = zope.schema.Choice( title=_("Playlist"), source=zeit.content.video.interfaces.PlaylistSource()) | A block which contains the link to a video playlist. | 625990c7627d3e7fe0e09238 |
class ContactResource(resources.ModelResource): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = Contact <NEW_LINE> fields = ( "title", "full_name", "email", "phone_number", "message", "created_at", ) | ModelResource is Resource subclass for handling Django models. | 625990c7627d3e7fe0e0924a |
class FileChecksum(_BoilerplateClass): <NEW_LINE> <INDENT> algorithm: str <NEW_LINE> bytes: str <NEW_LINE> length: int | :param algorithm: The name of the checksum algorithm.
:type algorithm: str
:param bytes: The byte sequence of the checksum in hexadecimal.
:type bytes: str
:param length: The length of the bytes (not the length of the string).
:type length: int | 625990c8627d3e7fe0e0925e |
class NikolaTaskLoader(TaskLoader): <NEW_LINE> <INDENT> def __init__(self, nikola): <NEW_LINE> <INDENT> self.nikola = nikola <NEW_LINE> <DEDENT> def load_tasks(self, cmd, opt_values, pos_args): <NEW_LINE> <INDENT> DOIT_CONFIG = { 'reporter': ExecutedOnlyReporter, 'default_tasks': ['render_site', 'post_render'], } <NEW_LINE> tasks = generate_tasks('render_site', self.nikola.gen_tasks('render_site', "Task")) <NEW_LINE> latetasks = generate_tasks('post_render', self.nikola.gen_tasks('post_render', "LateTask")) <NEW_LINE> return tasks + latetasks, DOIT_CONFIG | custom task loader to get tasks from Nikola instead of dodo.py file | 625990c8627d3e7fe0e0926a |
class ResistanceTemperatureDevice(models.Model): <NEW_LINE> <INDENT> alpha = models.FloatField(default=0.00385) <NEW_LINE> zero_resistance = models.FloatField(default=100.0) | An RTD sensor device itself. Just the electrical properties of the
device.
Attributes:
alpha: The RTD resistance coefficient. Units: Ohms/degC.
zero_resistance: The resistance of the RTD at 0degC. Units: Ohms. | 625990c8627d3e7fe0e0926c |
@api.route('/<int:cid>') <NEW_LINE> @api.response(404, 'Creator not found') <NEW_LINE> @api.param('id', 'The creator identifier') <NEW_LINE> class CreatorResource(Resource): <NEW_LINE> <INDENT> @api.doc('get_creator') <NEW_LINE> @api.marshal_with(creatorModel) <NEW_LINE> def get(self, cid): <NEW_LINE> <INDENT> c = creatorDAO.get(cid) <NEW_LINE> if c is not None: <NEW_LINE> <INDENT> return c <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> api.abort(404, "Creator {} doesn't exist".format(cid)) <NEW_LINE> <DEDENT> <DEDENT> @api.doc('delete_creator') <NEW_LINE> @api.response(204, 'Creator deleted') <NEW_LINE> def delete(self, cid): <NEW_LINE> <INDENT> creatorDAO.delete(cid) <NEW_LINE> return '', 204 <NEW_LINE> <DEDENT> @api.expect(creatorModel) <NEW_LINE> @api.marshal_with(creatorModel) <NEW_LINE> def put(self, cid): <NEW_LINE> <INDENT> return creatorDAO.update(cid, request.payload) | Show a single creator and lets you delete them | 625990c8627d3e7fe0e09270 |
class UpdateAmphoraDBCertExpiration(BaseDatabaseTask): <NEW_LINE> <INDENT> def execute(self, amphora_id, server_pem): <NEW_LINE> <INDENT> LOG.debug("Update DB cert expiry date of amphora id: %s", amphora_id) <NEW_LINE> key = utils.get_compatible_server_certs_key_passphrase() <NEW_LINE> fer = fernet.Fernet(key) <NEW_LINE> cert_expiration = cert_parser.get_cert_expiration( fer.decrypt(server_pem)) <NEW_LINE> LOG.debug("Certificate expiration date is %s ", cert_expiration) <NEW_LINE> self.amphora_repo.update(db_apis.get_session(), amphora_id, cert_expiration=cert_expiration) | Update the amphora expiration date with new cert file date. | 625990c9627d3e7fe0e0928c |
class ASTPrimary(NamedTuple): <NEW_LINE> <INDENT> name: str <NEW_LINE> values: List[str] <NEW_LINE> def evaluate(self, path: Path): <NEW_LINE> <INDENT> return PATH_OPERAND_EVALUATORS[self.name](path, *self.values) <NEW_LINE> <DEDENT> def size(self): <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_tokens(cls, tokens: List[Tuple[OperandTokens, str]]): <NEW_LINE> <INDENT> if not tokens: <NEW_LINE> <INDENT> raise ValueError("tokens is empty") <NEW_LINE> <DEDENT> name = eat_token(tokens, OperandTokens.OPERAND_NAME) <NEW_LINE> values = [] <NEW_LINE> while tokens and tokens[0][0] == OperandTokens.OPERAND_VALUE: <NEW_LINE> <INDENT> values.append(eat_token(tokens, OperandTokens.OPERAND_VALUE)) <NEW_LINE> <DEDENT> return cls(name, values) | Represents a primary expression (an operand and an optional number of values that evaluate to a boolean value) | 625990c9627d3e7fe0e0928e |
class ReaderModule(BaseModule): <NEW_LINE> <INDENT> async def setup(self, parsed_args, app, output): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> async def run(self, parsed_args: argparse.Namespace, output: Pipe): <NEW_LINE> <INDENT> assert False, "implement in child class" <NEW_LINE> <DEDENT> async def run_as_task(self, parsed_args, app): <NEW_LINE> <INDENT> if (parsed_args.pipes == "unset" and parsed_args.module_config == "unset"): <NEW_LINE> <INDENT> output = StdoutPipe() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> (pipes_in, pipes_out) = await self._build_pipes(parsed_args) <NEW_LINE> <DEDENT> except errors.ApiError as e: <NEW_LINE> <INDENT> logging.error(str(e)) <NEW_LINE> return asyncio.create_task(asyncio.sleep(0)) <NEW_LINE> <DEDENT> if len(pipes_out.keys()) != 1: <NEW_LINE> <INDENT> logging.error("Reader module must have a single output") <NEW_LINE> return asyncio.create_task(asyncio.sleep(0)) <NEW_LINE> <DEDENT> output = list(pipes_out.values())[0] <NEW_LINE> <DEDENT> await self.setup(parsed_args, app, output) <NEW_LINE> return asyncio.create_task(self.run(parsed_args, output)) | Inherit from this class and implement a :meth:`run` coroutine to create a Joule reader module.
Other methods documented below may be implemented as desired. | 625990c9627d3e7fe0e09292 |
class UserAskView(View): <NEW_LINE> <INDENT> def post(self, request): <NEW_LINE> <INDENT> userask_form = UserAskForm(request.POST) <NEW_LINE> if userask_form.is_valid(): <NEW_LINE> <INDENT> user_ask = userask_form.save(commit=True) <NEW_LINE> return HttpResponse('{"status":"success"}', content_type='application/json') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return HttpResponse('{"status":"fail", "msg":"添加出错"}', content_type='application/json') | 用户添加咨询 | 625990c9627d3e7fe0e09294 |
class DynamicLogger(object): <NEW_LINE> <INDENT> def __getattr__(self, name): <NEW_LINE> <INDENT> return getattr(_logger, name) | Dynamic logger. | 625990ca627d3e7fe0e0929c |
class LocalTracking(object): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def _get_voxel_size(affine): <NEW_LINE> <INDENT> lin = affine[:3, :3] <NEW_LINE> dotlin = np.dot(lin.T, lin) <NEW_LINE> if not np.allclose(np.triu(dotlin, 1), 0.): <NEW_LINE> <INDENT> msg = ("The affine provided seems to contain shearing, data must " "be acquired or interpolated on a regular grid to be used " "with `LocalTracking`.") <NEW_LINE> raise ValueError(msg) <NEW_LINE> <DEDENT> return np.sqrt(dotlin.diagonal()) <NEW_LINE> <DEDENT> def __init__(self, direction_getter, tissue_classifier, seeds, affine, step_size, max_cross=None, maxlen=500, fixedstep=True, return_all=True): <NEW_LINE> <INDENT> self.direction_getter = direction_getter <NEW_LINE> self.tissue_classifier = tissue_classifier <NEW_LINE> self.seeds = seeds <NEW_LINE> if affine.shape != (4, 4): <NEW_LINE> <INDENT> raise ValueError("affine should be a (4, 4) array.") <NEW_LINE> <DEDENT> self.affine = affine <NEW_LINE> self._voxel_size = self._get_voxel_size(affine) <NEW_LINE> self.step_size = step_size <NEW_LINE> self.fixed = fixedstep <NEW_LINE> self.max_cross = max_cross <NEW_LINE> self.maxlen = maxlen <NEW_LINE> self.return_all = return_all <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> track = self._generate_streamlines() <NEW_LINE> return utils.move_streamlines(track, self.affine) <NEW_LINE> <DEDENT> def _generate_streamlines(self): <NEW_LINE> <INDENT> N = self.maxlen <NEW_LINE> dg = self.direction_getter <NEW_LINE> tc = self.tissue_classifier <NEW_LINE> ss = self.step_size <NEW_LINE> fixed = self.fixed <NEW_LINE> max_cross = self.max_cross <NEW_LINE> vs = self._voxel_size <NEW_LINE> inv_A = np.linalg.inv(self.affine) <NEW_LINE> lin = inv_A[:3, :3] <NEW_LINE> offset = inv_A[:3, 3] <NEW_LINE> F = np.empty((N + 1, 3), dtype=float) <NEW_LINE> B = F.copy() <NEW_LINE> for s in self.seeds: <NEW_LINE> <INDENT> s = np.dot(lin, s) + offset <NEW_LINE> directions = dg.initial_direction(s) <NEW_LINE> directions = directions[:max_cross] <NEW_LINE> for first_step in directions: <NEW_LINE> <INDENT> stepsF, tissue_class = local_tracker(dg, tc, s, first_step, vs, F, ss, fixed) <NEW_LINE> if not (self.return_all or tissue_class == TissueTypes.ENDPOINT or tissue_class == TissueTypes.OUTSIDEIMAGE): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> first_step = -first_step <NEW_LINE> stepsB, tissue_class = local_tracker(dg, tc, s, first_step, vs, B, ss, fixed) <NEW_LINE> if not (self.return_all or tissue_class == TissueTypes.ENDPOINT or tissue_class == TissueTypes.OUTSIDEIMAGE): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if stepsB == 1: <NEW_LINE> <INDENT> streamline = F[:stepsF].copy() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> parts = (B[stepsB-1:0:-1], F[:stepsF]) <NEW_LINE> streamline = np.concatenate(parts, axis=0) <NEW_LINE> <DEDENT> yield streamline | A streamline generator for local tracking methods | 625990ca627d3e7fe0e092a6 |
class CommServerPackager(Packager): <NEW_LINE> <INDENT> def __init__(self, src): <NEW_LINE> <INDENT> Packager.__init__(self, src, "UberStrok.Realtime.Server.Comm") <NEW_LINE> <DEDENT> def pack(self, archive): <NEW_LINE> <INDENT> if not Packager.pack(self, archive): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> files = glob(os.path.join(self.path, "*.dll")) <NEW_LINE> for f in files: <NEW_LINE> <INDENT> nf = os.path.join(self.name, os.path.basename(f)) <NEW_LINE> print("\tpacking {0}".format(nf)) <NEW_LINE> archive.write(f, arcname=nf) <NEW_LINE> <DEDENT> return True | represents a packager which
packages the comm server | 625990cb627d3e7fe0e092d0 |
class Float4(object): <NEW_LINE> <INDENT> def __init__(self, x, y, z, val = 0.0): <NEW_LINE> <INDENT> self.x = x <NEW_LINE> self.y = y <NEW_LINE> self.z = z <NEW_LINE> self.val = val <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def getZeroVector(): <NEW_LINE> <INDENT> return Float4( 0.0, 0.0, 0.0, 0.0 ) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def dist(v1, v2): <NEW_LINE> <INDENT> return math.sqrt( (v1.x - v2.x) * (v1.x - v2.x) + (v1.y - v2.y) * (v1.y - v2.y) + (v1.z - v2.z) * (v1.z - v2.z) ) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def dot(v1, v2): <NEW_LINE> <INDENT> return (v1.x - v2.x) * (v1.x - v2.x) + (v1.y - v2.y) * (v1.y - v2.y) + (v1.z - v2.z) * (v1.z - v2.z) | For good vectorization on OpenCL device we need to use 4 dimension vectors | 625990cb627d3e7fe0e092d2 |
class ContinuousTableModel(QAbstractTableModel): <NEW_LINE> <INDENT> def __init__(self, banddata, bandNames, stretch, parent): <NEW_LINE> <INDENT> QAbstractTableModel.__init__(self, parent) <NEW_LINE> self.banddata = banddata <NEW_LINE> self.bandNames = bandNames <NEW_LINE> self.stretch = stretch <NEW_LINE> self.colNames = ["Band", "Name", "Value"] <NEW_LINE> self.redPixmap = QPixmap(64, 24) <NEW_LINE> self.redPixmap.fill(Qt.red) <NEW_LINE> self.greenPixmap = QPixmap(64, 24) <NEW_LINE> self.greenPixmap.fill(Qt.green) <NEW_LINE> self.bluePixmap = QPixmap(64, 24) <NEW_LINE> self.bluePixmap.fill(Qt.blue) <NEW_LINE> self.greyPixmap = QPixmap(64, 24) <NEW_LINE> self.greyPixmap.fill(Qt.gray) <NEW_LINE> <DEDENT> def doUpdate(self, updateHorizHeader=False): <NEW_LINE> <INDENT> topLeft = self.index(0, 0) <NEW_LINE> bottomRight = self.index(self.columnCount(None) - 1, self.rowCount(None) - 1) <NEW_LINE> self.dataChanged.emit(topLeft, bottomRight) <NEW_LINE> if updateHorizHeader: <NEW_LINE> <INDENT> self.headerDataChanged.emit(Qt.Horizontal, 0, self.rowCount(None) - 1) <NEW_LINE> <DEDENT> <DEDENT> def rowCount(self, parent): <NEW_LINE> <INDENT> return len(self.bandNames) <NEW_LINE> <DEDENT> def columnCount(self, parent): <NEW_LINE> <INDENT> return 3 <NEW_LINE> <DEDENT> def headerData(self, section, orientation, role): <NEW_LINE> <INDENT> if orientation == Qt.Horizontal and role == Qt.DisplayRole: <NEW_LINE> <INDENT> name = self.colNames[section] <NEW_LINE> return name <NEW_LINE> <DEDENT> elif orientation == Qt.Vertical and role == Qt.DisplayRole: <NEW_LINE> <INDENT> return "%s" % (section + 1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def data(self, index, role): <NEW_LINE> <INDENT> if not index.isValid(): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> column = index.column() <NEW_LINE> row = index.row() <NEW_LINE> if column == 0 and role == Qt.DecorationRole: <NEW_LINE> <INDENT> band = row + 1 <NEW_LINE> if (self.stretch.mode == VIEWER_MODE_RGB and band in self.stretch.bands): <NEW_LINE> <INDENT> if band == self.stretch.bands[0]: <NEW_LINE> <INDENT> return self.redPixmap <NEW_LINE> <DEDENT> elif band == self.stretch.bands[1]: <NEW_LINE> <INDENT> return self.greenPixmap <NEW_LINE> <DEDENT> elif band == self.stretch.bands[2]: <NEW_LINE> <INDENT> return self.bluePixmap <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> elif (self.stretch.mode == VIEWER_MODE_GREYSCALE and band == self.stretch.bands[0]): <NEW_LINE> <INDENT> return self.greyPixmap <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> elif column == 1 and role == Qt.DisplayRole: <NEW_LINE> <INDENT> return self.bandNames[row] <NEW_LINE> <DEDENT> elif (column == 2 and role == Qt.DisplayRole and self.banddata is not None): <NEW_LINE> <INDENT> return "%s" % self.banddata[row] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None | This class is the 'model' that drives the continuous table.
QTableView asks it for the data etc | 625990cb627d3e7fe0e092d4 |
class MaskingEditException(Exception): <NEW_LINE> <INDENT> pass | Custom exception. | 625990cb627d3e7fe0e092d8 |
@final <NEW_LINE> @dataclass <NEW_LINE> class Ok(Result[E, A]): <NEW_LINE> <INDENT> __slots__ = "success" <NEW_LINE> success: A | The result of a successful computation. | 625990cc627d3e7fe0e092fa |
class GSS_Verifier(BaseObj): <NEW_LINE> <INDENT> flavor = RPCSEC_GSS <NEW_LINE> _itemlist = ("flavor", "size", "gss_token") <NEW_LINE> def __init__(self, unpack): <NEW_LINE> <INDENT> self.gss_token = unpack.unpack_opaque() <NEW_LINE> self.size = len(self.gss_token) | GSS_Verifier object | 625990cd627d3e7fe0e0930f |
class TestDOS(BaseTests.BrainFuckTestBase): <NEW_LINE> <INDENT> exe = "build16/dos/dos_test.com" <NEW_LINE> def run_bf_proc(self, exe, file, input=None): <NEW_LINE> <INDENT> tmp_dir = tempfile.gettempdir() <NEW_LINE> out_file_name = hex(random.getrandbits(64))[2:] + ".out" <NEW_LINE> out_file_path = os.path.join(tmp_dir, out_file_name) <NEW_LINE> quoted_input = "" <NEW_LINE> if input is not None: <NEW_LINE> <INDENT> input_suffix = '\\\\r\\\\^Z\\\\r"' <NEW_LINE> quoted_input = f"-input \"{input.decode('ascii')}{input_suffix}" <NEW_LINE> <DEDENT> cmdln = ( "dosemu", "-dumb", quoted_input, self.exe, '"' + _dos_prep_rel_path(file), ">", f"E:{_dos_prep_path(out_file_path)}", '"', ) <NEW_LINE> res = sp.run(" ".join(cmdln), stdout=sp.PIPE, stderr=sp.PIPE, shell=True) <NEW_LINE> with open(out_file_path, "rb") as f: <NEW_LINE> <INDENT> stdout = f.read() <NEW_LINE> <DEDENT> stdout = stdout.replace(b" ", b"\t") <NEW_LINE> if input is not None and stdout.endswith(b"\r\n"): <NEW_LINE> <INDENT> stdout = stdout[:-2] <NEW_LINE> <DEDENT> return BrainFuckOutput(output=stdout, ret_code=res.returncode) | Emulated DOS tests | 625990cd627d3e7fe0e09313 |
class MongoDbFinishCommand(CommandProperties): <NEW_LINE> <INDENT> _validation = { 'errors': {'readonly': True}, 'state': {'readonly': True}, 'command_type': {'required': True}, } <NEW_LINE> _attribute_map = { 'errors': {'key': 'errors', 'type': '[ODataError]'}, 'state': {'key': 'state', 'type': 'str'}, 'command_type': {'key': 'commandType', 'type': 'str'}, 'input': {'key': 'input', 'type': 'MongoDbFinishCommandInput'}, } <NEW_LINE> def __init__(self, *, input=None, **kwargs) -> None: <NEW_LINE> <INDENT> super(MongoDbFinishCommand, self).__init__(**kwargs) <NEW_LINE> self.input = input <NEW_LINE> self.command_type = 'finish' | Properties for the command that finishes a migration in whole or in part.
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.
:ivar errors: Array of errors. This is ignored if submitted.
:vartype errors: list[~azure.mgmt.datamigration.models.ODataError]
:ivar state: The state of the command. This is ignored if submitted.
Possible values include: 'Unknown', 'Accepted', 'Running', 'Succeeded',
'Failed'
:vartype state: str or ~azure.mgmt.datamigration.models.CommandState
:param command_type: Required. Constant filled by server.
:type command_type: str
:param input: Command input
:type input: ~azure.mgmt.datamigration.models.MongoDbFinishCommandInput | 625990cd627d3e7fe0e0931b |
class IDonationPage(form.Schema, IImageScaleTraversable): <NEW_LINE> <INDENT> form.widget(header_text="plone.app.z3cform.wysiwyg.WysiwygFieldWidget") <NEW_LINE> header_text = schema.Text(title=_(u'Header text'), description=_(u'This text will appear above the donation form'), required=False ) <NEW_LINE> form.widget(footer_text="plone.app.z3cform.wysiwyg.WysiwygFieldWidget") <NEW_LINE> footer_text = schema.Text(title=_(u'Footer text'), description=_(u'This text will appear beneath the donation form'), required=False ) <NEW_LINE> form.widget(categories=DataGridFieldFactory) <NEW_LINE> categories = schema.List(title=_(u'Donation Categories'), description=_(u'One category per line'), value_type=DictRow(schema=IDonationCategory), ) | Donation page | 625990ce627d3e7fe0e0931d |
class SetPasswordView(APIView): <NEW_LINE> <INDENT> http_method_names = ["post"] <NEW_LINE> def post(self, request, *args, **kwargs): <NEW_LINE> <INDENT> user = request.user <NEW_LINE> if user.check_password(request.data["old_password"]): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> validate_password(request.data.get("new_password"), user=user) <NEW_LINE> <DEDENT> except DjangoValidationError as errors: <NEW_LINE> <INDENT> raise ValidationError({"detail": " ".join(errors)}) <NEW_LINE> <DEDENT> user.set_password(request.data["new_password"]) <NEW_LINE> user.save() <NEW_LINE> update_session_auth_hash(request, user) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValidationError({"detail": "Old password does not match."}) <NEW_LINE> <DEDENT> return super().post(request, *args, **kwargs) | Users can set a new password for themselves. | 625990ce627d3e7fe0e0932d |
class TestCrudServiceBase: <NEW_LINE> <INDENT> @pytest.fixture(autouse=True) <NEW_LINE> def transact(self, request, registry_rest_api_1): <NEW_LINE> <INDENT> transaction = registry_rest_api_1.begin_nested() <NEW_LINE> request.addfinalizer(transaction.rollback) <NEW_LINE> return <NEW_LINE> <DEDENT> def create_example(self, registry, name="plop"): <NEW_LINE> <INDENT> return registry.Example.insert(name=name) <NEW_LINE> <DEDENT> def test_example_service_get(self, registry_rest_api_1, webserver): <NEW_LINE> <INDENT> ex = self.create_example(registry_rest_api_1) <NEW_LINE> response = webserver.get('/anothers/%s' % ex.id) <NEW_LINE> assert response.status_code == 200 <NEW_LINE> assert response.json_body.get('name') == "plop" <NEW_LINE> <DEDENT> def test_example_service_put(self, registry_rest_api_1, webserver): <NEW_LINE> <INDENT> ex = self.create_example(registry_rest_api_1) <NEW_LINE> response = webserver.put_json( '/anothers/%s' % ex.id, {'name': 'plip'}) <NEW_LINE> assert response.status_code == 200 <NEW_LINE> assert response.json_body.get('name') == "plip" <NEW_LINE> <DEDENT> def test_example_service_put_schema_fail_bad_path( self, registry_rest_api_1, webserver ): <NEW_LINE> <INDENT> fail = webserver.put_json( '/anothers/x', {'name': 'plip'}, status=400) <NEW_LINE> assert fail.status_code == 400 <NEW_LINE> assert fail.json_body.get('status') == 'error' <NEW_LINE> assert fail.json_body.get('errors')[0].get('location') == 'path' <NEW_LINE> <DEDENT> def test_example_service_put_schema_fail_bad_value_type( self, registry_rest_api_1, webserver ): <NEW_LINE> <INDENT> ex = self.create_example(registry_rest_api_1) <NEW_LINE> fail = webserver.put_json( '/anothers/%s' % ex.id, {'name': 0}, status=400) <NEW_LINE> assert fail.status_code == 400 <NEW_LINE> assert fail.json_body.get('status') == 'error' <NEW_LINE> assert fail.json_body.get('errors')[0].get('location') == 'body' <NEW_LINE> <DEDENT> def test_example_service_post(self, registry_rest_api_1, webserver): <NEW_LINE> <INDENT> response = webserver.post_json('/anothers', {'name': 'plip'}) <NEW_LINE> assert response.status_code == 200 <NEW_LINE> assert response.json_body.get('name') == "plip" <NEW_LINE> <DEDENT> def test_example_service_post_schema_fail_bad_column_name( self, registry_rest_api_1, webserver ): <NEW_LINE> <INDENT> fail = webserver.post_json( '/anothers', {'badcolumn': 'plip'}, status=400) <NEW_LINE> assert fail.status_code == 400 <NEW_LINE> assert fail.json_body.get('status') == 'error' <NEW_LINE> assert fail.json_body.get('errors')[0].get('location') == 'body' <NEW_LINE> <DEDENT> def test_example_service_post_schema_fail_bad_value_type( self, registry_rest_api_1, webserver ): <NEW_LINE> <INDENT> fail = webserver.post_json( '/anothers', {'name': 0}, status=400) <NEW_LINE> assert fail.status_code == 400 <NEW_LINE> assert fail.json_body.get('status') == 'error' <NEW_LINE> assert fail.json_body.get('errors')[0].get('location') == 'body' | Test Service from test_bloks/test_1/views.py:example_service
This is the basic case, no validators, no schema. | 625990cf627d3e7fe0e0934b |
class LinkedStack(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.top = None <NEW_LINE> self.size = 0 <NEW_LINE> <DEDENT> def isempty(self): <NEW_LINE> <INDENT> return self.size == 0 <NEW_LINE> <DEDENT> def push(self,val): <NEW_LINE> <INDENT> self.size += 1 <NEW_LINE> if(self.isempty()): <NEW_LINE> <INDENT> n = Node(val) <NEW_LINE> self.top = n <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> n = Node(val) <NEW_LINE> n.next = self.top <NEW_LINE> self.top = n <NEW_LINE> <DEDENT> <DEDENT> def pop(self): <NEW_LINE> <INDENT> if(self.isempty()): <NEW_LINE> <INDENT> raise IndexError('Stack is empty') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> n = self.top <NEW_LINE> self.top = self.top.next <NEW_LINE> self.size -= 1 <NEW_LINE> return n.val <NEW_LINE> <DEDENT> <DEDENT> def peek(self): <NEW_LINE> <INDENT> if(self.isempty()): <NEW_LINE> <INDENT> raise IndexError('Stack is empty') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.top.val | Implementation of a stack using linked list. | 625990cf627d3e7fe0e09353 |
class _LayoutShapeTree(BaseShapeTree): <NEW_LINE> <INDENT> def _shape_factory(self, shape_elm): <NEW_LINE> <INDENT> parent = self <NEW_LINE> return _LayoutShapeFactory(shape_elm, parent) | Sequence of shapes appearing on a slide layout. The first shape in the
sequence is the backmost in z-order and the last shape is topmost.
Supports indexed access, len(), index(), and iteration. | 625990cf627d3e7fe0e09355 |
@datatype <NEW_LINE> class Program: <NEW_LINE> <INDENT> files: List[SourceFile] | # Multi-File "Netlist Program"
The name of this type is a bit misleading, but borrowed from more typical compiler-parsers.
Spice-culture generally lacks a term for "the totality of a simulator invocation input",
or even "a pile of source-files to be used together".
So, `Program` it is. | 625990d0627d3e7fe0e09363 |
class MultiDict(_MultiDict[KT, VT], serializable.Serializable): <NEW_LINE> <INDENT> def __init__(self, fields=()): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.fields = tuple( tuple(i) for i in fields ) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _reduce_values(values): <NEW_LINE> <INDENT> return values[0] <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _kconv(key): <NEW_LINE> <INDENT> return key <NEW_LINE> <DEDENT> def get_state(self): <NEW_LINE> <INDENT> return self.fields <NEW_LINE> <DEDENT> def set_state(self, state): <NEW_LINE> <INDENT> self.fields = tuple(tuple(x) for x in state) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_state(cls, state): <NEW_LINE> <INDENT> return cls(state) | A concrete MultiDict, storing its own data. | 625990d0627d3e7fe0e0937b |
class Job(AbstractJob): <NEW_LINE> <INDENT> @property <NEW_LINE> def job_id(self): <NEW_LINE> <INDENT> return self.raw_model["jobId"] <NEW_LINE> <DEDENT> @property <NEW_LINE> def status(self): <NEW_LINE> <INDENT> return self.raw_model["status"] <NEW_LINE> <DEDENT> @property <NEW_LINE> def statistics(self): <NEW_LINE> <INDENT> return self.raw_model["statistics"] | Job Model. | 625990d1627d3e7fe0e09389 |
class File: <NEW_LINE> <INDENT> name = None <NEW_LINE> priority = None <NEW_LINE> __metaclass__ = _FiletypeMetaclass <NEW_LINE> def __init__(self, app, a_file): <NEW_LINE> <INDENT> self.app = app <NEW_LINE> self.file = a_file <NEW_LINE> self.conf = app.conf.setdefault('file', dict()).setdefault(self.name, dict()) <NEW_LINE> self.size = self.__get_size() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def is_compatible(cls, filename): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def anonymize(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def discover(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def __get_size(self): <NEW_LINE> <INDENT> statinfo = os.stat(os.path.join(self.app.project.input, self.file)) <NEW_LINE> nbytes = statinfo.st_size <NEW_LINE> suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'] <NEW_LINE> if nbytes == 0: <NEW_LINE> <INDENT> return '0 B' <NEW_LINE> <DEDENT> i = 0 <NEW_LINE> while nbytes >= 1024 and i < len(suffixes) - 1: <NEW_LINE> <INDENT> nbytes /= 1024. <NEW_LINE> i += 1 <NEW_LINE> <DEDENT> f = ('%.2f' % nbytes).rstrip('0').rstrip('.') <NEW_LINE> return '%s %s' % (f, suffixes[i]) | Superclass for all actions | 625990d2627d3e7fe0e093a1 |
class RC4Test(unittest.TestCase): <NEW_LINE> <INDENT> def test_rc4_key_plaintext(self): <NEW_LINE> <INDENT> self.assertEqual("\xBB\xF3\x16\xE8\xD9\x40\xAF\x0A\xD3", rc4.crypt(rc4.RC4Key("Key"), "Plaintext"), "RC4 bad crypt") <NEW_LINE> self.assertEqual("Plaintext", rc4.crypt(rc4.RC4Key("Key"), "\xBB\xF3\x16\xE8\xD9\x40\xAF\x0A\xD3"), "RC4 bad crypt") <NEW_LINE> <DEDENT> def test_rc4_wiki_pedia(self): <NEW_LINE> <INDENT> self.assertEqual("\x10\x21\xBF\x04\x20", rc4.crypt(rc4.RC4Key("Wiki"), "pedia"), "RC4 bad crypt") <NEW_LINE> self.assertEqual("pedia", rc4.crypt(rc4.RC4Key("Wiki"), "\x10\x21\xBF\x04\x20"), "RC4 bad crypt") <NEW_LINE> <DEDENT> def test_rc4_secret_attack_at_down(self): <NEW_LINE> <INDENT> self.assertEqual("\x45\xA0\x1F\x64\x5F\xC3\x5B\x38\x35\x52\x54\x4B\x9B\xF5", rc4.crypt(rc4.RC4Key("Secret"), "Attack at dawn"), "RC4 bad crypt") <NEW_LINE> self.assertEqual("Attack at dawn", rc4.crypt(rc4.RC4Key("Secret"), "\x45\xA0\x1F\x64\x5F\xC3\x5B\x38\x35\x52\x54\x4B\x9B\xF5"), "RC4 bad crypt") | @summary: unit tests for rc4
@see: http://fr.wikipedia.org/wiki/RC4 | 625990d2627d3e7fe0e093a9 |
class Software(models.Model): <NEW_LINE> <INDENT> SUB_ASSET_TYPE_CHOICE = ( (0, '操作系统'), (1, '办公/开发软件'), (2, '业务软件'), ) <NEW_LINE> sub_asset_type = models.PositiveSmallIntegerField(choices=SUB_ASSET_TYPE_CHOICE, default=0, verbose_name="软件类型") <NEW_LINE> license_num = models.IntegerField(default=1, verbose_name="授权数量") <NEW_LINE> version = models.CharField(max_length=64, unique=True, help_text='例如: CentOS release 6.7 (Final)', verbose_name='软件/系统版本') <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return '%s--%s' % (self.get_sub_asset_type_display(), self.version) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = '软件/系统' <NEW_LINE> verbose_name_plural = "软件/系统" | 只保存付费购买的软件 | 625990d2627d3e7fe0e093bd |
class cell_type_1: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.symbol = "K" <NEW_LINE> self.divide_rate = 1 <NEW_LINE> self.priority = 1 <NEW_LINE> self.invasive = 0 <NEW_LINE> self.divide_direction = { "left_1": [0.0000, 0.0625], "top-left": [0.0625, 0.1875], "top": [0.1875, 0.3125], "top-right": [0.3125, 0.4375], "right": [0.4375, 0.5625], "bottom-right": [0.5625, 0.6875], "bottom": [0.6875, 0.8125], "bottom-left": [0.8125, 0.9375], "left_2": [0.9375, 1.0000], } <NEW_LINE> self.tranform = [ "type_2", "type_3", "type_4", "type_5", "type_6", "type_7", "type_8", ] | Define Cell Type 1 Attributes | 625990d3627d3e7fe0e093c6 |