code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
@description("Offlines a disk in a volume") <NEW_LINE> class OfflineVdevCommand(Command): <NEW_LINE> <INDENT> def __init__(self, parent): <NEW_LINE> <INDENT> self.parent = parent <NEW_LINE> <DEDENT> def run(self, context, args, kwargs, opargs): <NEW_LINE> <INDENT> if len(args) == 0: <NEW_LINE> <INDENT> raise CommandException(_("Please specify a disk")) <NEW_LINE> <DEDENT> disk = args[0] <NEW_LINE> volume = self.parent.entity <NEW_LINE> disk = correct_disk_path(disk) <NEW_LINE> vdevs = list(iterate_vdevs(volume['topology'])) <NEW_LINE> guid = None <NEW_LINE> for vdev in vdevs: <NEW_LINE> <INDENT> if vdev['path'] == disk: <NEW_LINE> <INDENT> guid = vdev['guid'] <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if guid is None: <NEW_LINE> <INDENT> raise CommandException(_("Disk {0} is not part of the volume.".format(disk))) <NEW_LINE> <DEDENT> context.submit_task( 'volume.vdev.offline', self.parent.entity['id'], guid, callback=lambda s, t: post_save(self.parent, s, t) ) | Usage: offline <disk>
Example: offline ada1
Offlines a disk in a volume" | 625990564a966d76dd5f0450 |
class TaskRetrieveUpdateDestroyViewSet(TaskBaseViewSet, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin): <NEW_LINE> <INDENT> pass | Task retrieve, update, destroy view sets | 62599056379a373c97d9a584 |
class DescribeImageQuotaResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.ImageNumQuota = None <NEW_LINE> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.ImageNumQuota = params.get("ImageNumQuota") <NEW_LINE> self.RequestId = params.get("RequestId") | DescribeImageQuota返回参数结构体
| 6259905629b78933be26ab74 |
class RolesController(wsgi.Controller): <NEW_LINE> <INDENT> def __init__(self, options): <NEW_LINE> <INDENT> self.options = options <NEW_LINE> <DEDENT> @utils.wrap_error <NEW_LINE> def create_role(self, req): <NEW_LINE> <INDENT> role = utils.get_normalized_request_content(Role, req) <NEW_LINE> return utils.send_result(201, req, config.SERVICE.create_role(utils.get_auth_token(req), role)) <NEW_LINE> <DEDENT> @utils.wrap_error <NEW_LINE> def delete_role(self, req, role_id): <NEW_LINE> <INDENT> rval = config.SERVICE.delete_role(utils.get_auth_token(req), role_id) <NEW_LINE> return utils.send_result(204, req, rval) <NEW_LINE> <DEDENT> @utils.wrap_error <NEW_LINE> def get_roles(self, req): <NEW_LINE> <INDENT> marker, limit, url = get_marker_limit_and_url(req) <NEW_LINE> roles = config.SERVICE.get_roles( utils.get_auth_token(req), marker, limit, url) <NEW_LINE> return utils.send_result(200, req, roles) <NEW_LINE> <DEDENT> @utils.wrap_error <NEW_LINE> def get_role(self, req, role_id): <NEW_LINE> <INDENT> role = config.SERVICE.get_role(utils.get_auth_token(req), role_id) <NEW_LINE> return utils.send_result(200, req, role) <NEW_LINE> <DEDENT> @utils.wrap_error <NEW_LINE> def create_role_ref(self, req, user_id): <NEW_LINE> <INDENT> roleRef = utils.get_normalized_request_content(RoleRef, req) <NEW_LINE> return utils.send_result(201, req, config.SERVICE.create_role_ref( utils.get_auth_token(req), user_id, roleRef)) <NEW_LINE> <DEDENT> @utils.wrap_error <NEW_LINE> def get_role_refs(self, req, user_id): <NEW_LINE> <INDENT> marker, limit, url = get_marker_limit_and_url(req) <NEW_LINE> roleRefs = config.SERVICE.get_user_roles( utils.get_auth_token(req), marker, limit, url, user_id) <NEW_LINE> return utils.send_result(200, req, roleRefs) <NEW_LINE> <DEDENT> @utils.wrap_error <NEW_LINE> def delete_role_ref(self, req, user_id, role_ref_id): <NEW_LINE> <INDENT> rval = config.SERVICE.delete_role_ref(utils.get_auth_token(req), role_ref_id) <NEW_LINE> return utils.send_result(204, req, rval) <NEW_LINE> <DEDENT> @utils.wrap_error <NEW_LINE> def add_global_role_to_user(self, req, user_id, role_id): <NEW_LINE> <INDENT> config.SERVICE.add_global_role_to_user(utils.get_auth_token(req), user_id, role_id) <NEW_LINE> return utils.send_result(201, None) | Controller for Role related operations | 6259905673bcbd0ca4bcb7f1 |
class ConvertEnergy: <NEW_LINE> <INDENT> def __init__(self, temperature=None, debug=False): <NEW_LINE> <INDENT> self._deg_c = temperature <NEW_LINE> self._debug = debug <NEW_LINE> if self._debug: <NEW_LINE> <INDENT> print("*Init:", self.__class__) <NEW_LINE> print("*Init: ", self.__dict__) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def deg_c(self): <NEW_LINE> <INDENT> return self._deg_c <NEW_LINE> <DEDENT> @deg_c.setter <NEW_LINE> def deg_c(self, temperature=None): <NEW_LINE> <INDENT> self._deg_c = temperature <NEW_LINE> <DEDENT> @property <NEW_LINE> def deg_f(self): <NEW_LINE> <INDENT> if self._deg_c == None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return (((9 / 5) * self._deg_c) + 32) <NEW_LINE> <DEDENT> <DEDENT> @deg_f.setter <NEW_LINE> def deg_f(self, temperature=None): <NEW_LINE> <INDENT> self._deg_c = ((temperature - 32) * (5 / 9)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def deg_k(self): <NEW_LINE> <INDENT> if self._deg_c == None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self._deg_c + 273.15 <NEW_LINE> <DEDENT> <DEDENT> @deg_k.setter <NEW_LINE> def deg_k(self, temperature=None): <NEW_LINE> <INDENT> self._deg_c = temperature - 273.15 <NEW_LINE> <DEDENT> @property <NEW_LINE> def debug(self): <NEW_LINE> <INDENT> return self._debug <NEW_LINE> <DEDENT> @debug.setter <NEW_LINE> def debug(self, debug=False): <NEW_LINE> <INDENT> self._debug = debug <NEW_LINE> if self._debug: <NEW_LINE> <INDENT> print("*Init:", self.__class__) <NEW_LINE> print("*Init: ", self.__dict__) | energy helper class. | 6259905610dbd63aa1c72129 |
class WeboobProxy(object): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def version(): <NEW_LINE> <INDENT> return Weboob.VERSION <NEW_LINE> <DEDENT> def __init__(self): <NEW_LINE> <INDENT> self.weboob = Weboob() <NEW_LINE> self.backend = None <NEW_LINE> <DEDENT> def install_modules(self, capability=None, name=None): <NEW_LINE> <INDENT> repositories = self.weboob.repositories <NEW_LINE> repositories.update_repositories(DummyProgress()) <NEW_LINE> if name: <NEW_LINE> <INDENT> modules = {name: repositories.get_module_info(name)} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> modules = repositories.get_all_modules_info(capability) <NEW_LINE> <DEDENT> for infos in modules.values(): <NEW_LINE> <INDENT> if infos is not None and ( not infos.is_installed() or not infos.is_local() ): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> repositories.install(infos, progress=DummyProgress()) <NEW_LINE> <DEDENT> except ModuleInstallError as exception: <NEW_LINE> <INDENT> logger.info(str(exception)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return { module_name: dict(infos.dump()) for module_name, infos in modules.items() if infos.is_installed() } <NEW_LINE> <DEDENT> def list_modules(self, capability=None, name=None): <NEW_LINE> <INDENT> installed_modules = self.install_modules( capability=capability, name=name ) <NEW_LINE> for module_name in installed_modules: <NEW_LINE> <INDENT> module = self.weboob.modules_loader.get_or_load_module(module_name) <NEW_LINE> installed_modules[module_name]["config"] = ( weboob_tools.dictify_config_desc(module.config) ) <NEW_LINE> installed_modules[module_name]["website"] = module.website <NEW_LINE> <DEDENT> return { 'modules': [ dict(module, name=name) for name, module in installed_modules.items() ] } <NEW_LINE> <DEDENT> def init_backend(self, modulename, parameters): <NEW_LINE> <INDENT> self.install_modules(name=modulename) <NEW_LINE> self.backend = self.weboob.build_backend(modulename, parameters) <NEW_LINE> return self.backend | Connector is a tool that connects to common websites like bank website,
phone operator website... and that grabs personal data from there.
Credentials are required to make this operation.
Technically, connectors are weboob backend wrappers. | 62599056b830903b9686ef2e |
class Meta: <NEW_LINE> <INDENT> ordering = ['-created_date'] <NEW_LINE> verbose_name = 'Weight Entry' <NEW_LINE> verbose_name_plural = 'Weight Entries' | Meta data, in this case we instruct to order list views by due_back.
| 625990560fa83653e46f6445 |
class AvailableConnectWiseBoardManager(models.Manager): <NEW_LINE> <INDENT> def get_queryset(self): <NEW_LINE> <INDENT> return super().get_queryset().filter(inactive=False) | Return only active ConnectWise boards. | 6259905694891a1f408ba1a6 |
class ResponseBusinessUnarrangedAccountOverdraftData(object): <NEW_LINE> <INDENT> swagger_types = { 'brand': 'BusinessUnarrangedAccountOverdraftBrand' } <NEW_LINE> attribute_map = { 'brand': 'brand' } <NEW_LINE> def __init__(self, brand=None): <NEW_LINE> <INDENT> self._brand = None <NEW_LINE> self.discriminator = None <NEW_LINE> self.brand = brand <NEW_LINE> <DEDENT> @property <NEW_LINE> def brand(self): <NEW_LINE> <INDENT> return self._brand <NEW_LINE> <DEDENT> @brand.setter <NEW_LINE> def brand(self, brand): <NEW_LINE> <INDENT> if brand is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `brand`, must not be `None`") <NEW_LINE> <DEDENT> self._brand = brand <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(ResponseBusinessUnarrangedAccountOverdraftData, 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, ResponseBusinessUnarrangedAccountOverdraftData): <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. | 62599056462c4b4f79dbcf65 |
class Arc(object): <NEW_LINE> <INDENT> def __init__(self, from_node, to_node): <NEW_LINE> <INDENT> self.from_node = from_node <NEW_LINE> self.to_node = to_node <NEW_LINE> self.to_node.addArcConnection(self.from_node.getName(),self.from_node.getSize()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.name | Arc between two nodes
:Attributes:
- from_node (Node): Node where the arc starts
- to_node (Node): Node where the arc points | 625990563539df3088ecd807 |
class EncoderResnet(object): <NEW_LINE> <INDENT> def __init__(self, params, mode): <NEW_LINE> <INDENT> self.params = params <NEW_LINE> self.mode = mode <NEW_LINE> self.encoder_params = ENCODER_DEFUALT_PARAM <NEW_LINE> <DEDENT> def __call__(self, features): <NEW_LINE> <INDENT> inputs = features['image'] <NEW_LINE> with tf.variable_scope('encoder') as vsc: <NEW_LINE> <INDENT> with slim.arg_scope(resnet_v2.resnet_arg_scope()): <NEW_LINE> <INDENT> with arg_scope( [layers_lib.conv2d], activation_fn=None, normalizer_fn=None): <NEW_LINE> <INDENT> net = resnet_utils.conv2d_same(inputs, 16, 5, stride=2, scope='conv1') <NEW_LINE> <DEDENT> tf.add_to_collection(vsc.original_name_scope, net) <NEW_LINE> blocks = [] <NEW_LINE> for i in range(len(self.encoder_params['block_name'])): <NEW_LINE> <INDENT> block = resnet_v2.resnet_v2_block( scope=self.encoder_params['block_name'][i], base_depth=self.encoder_params['base_depth'][i], num_units=self.encoder_params['num_units'][i], stride=self.encoder_params['stride'][i]) <NEW_LINE> blocks.append(block) <NEW_LINE> <DEDENT> net, _ = resnet_v2.resnet_v2( net, blocks, is_training=(self.mode == ModeKeys.TRAIN), global_pool=False, output_stride=2, include_root_block=False, scope='resnet') <NEW_LINE> tf.add_to_collection(vsc.original_name_scope, net) <NEW_LINE> <DEDENT> <DEDENT> return net | Residual encoder using off-the-shelf interface.
| 62599056435de62698e9d363 |
class UserInfo(Resource): <NEW_LINE> <INDENT> @authorize <NEW_LINE> @add_default_HTTP_returns <NEW_LINE> def get(self): <NEW_LINE> <INDENT> return {"username": request.headers["Adfs-Login"], "name": request.headers["Adfs-Name"], "group": request.headers["Adfs-Group"], "email": request.headers["Adfs-Email"]} | Documentation for UserInfo
| 6259905682261d6c5273097a |
class pisaTagPDFBARCODE(pisaTag): <NEW_LINE> <INDENT> def start(self, c): <NEW_LINE> <INDENT> c.addPara() <NEW_LINE> attr = self.attr <NEW_LINE> bc = Standard39() <NEW_LINE> bc.value = attr.value <NEW_LINE> bc.barHeight = 0.5 * inch <NEW_LINE> bc.lquiet = 0 <NEW_LINE> bc.rquiet = 0 <NEW_LINE> bc.hAlign = attr.align.upper() <NEW_LINE> c.addStory(bc) <NEW_LINE> c.addPara() | <pdf:barcode value="" align=""> | 625990564e4d562566373968 |
class FederalDashboard(StateDashboard, ABC): <NEW_LINE> <INDENT> provider: str = "federal" <NEW_LINE> def _prep_df(self, df: pd.DataFrame) -> Tuple[pd.DataFrame, str]: <NEW_LINE> <INDENT> insert_op = str(uuid.uuid4()) <NEW_LINE> to_ins = df.rename(columns={"vintage": "last_updated"}).assign( insert_op=insert_op, provider=self.provider ) <NEW_LINE> if "location_type" not in list(to_ins): <NEW_LINE> <INDENT> to_ins["location_type"] = self.location_type <NEW_LINE> <DEDENT> if "source_url" not in list(to_ins): <NEW_LINE> <INDENT> to_ins["source_url"] = self.source <NEW_LINE> <DEDENT> if "source_name" not in list(to_ins): <NEW_LINE> <INDENT> to_ins["source_name"] = self.source_name <NEW_LINE> <DEDENT> return to_ins, insert_op | Parent class for scrapers working directly with federal sources
See `StateDashboard` for more information | 625990567d847024c075d93b |
class FftSpectraDataPointFftSpectra(object): <NEW_LINE> <INDENT> openapi_types = { 'frequencies': 'list[float]', 'x': 'list[float]', 'y': 'list[float]', 'z': 'list[float]' } <NEW_LINE> attribute_map = { 'frequencies': 'frequencies', 'x': 'x', 'y': 'y', 'z': 'z' } <NEW_LINE> def __init__(self, frequencies=None, x=None, y=None, z=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._frequencies = None <NEW_LINE> self._x = None <NEW_LINE> self._y = None <NEW_LINE> self._z = None <NEW_LINE> self.discriminator = None <NEW_LINE> if frequencies is not None: <NEW_LINE> <INDENT> self.frequencies = frequencies <NEW_LINE> <DEDENT> if x is not None: <NEW_LINE> <INDENT> self.x = x <NEW_LINE> <DEDENT> if y is not None: <NEW_LINE> <INDENT> self.y = y <NEW_LINE> <DEDENT> if z is not None: <NEW_LINE> <INDENT> self.z = z <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def frequencies(self): <NEW_LINE> <INDENT> return self._frequencies <NEW_LINE> <DEDENT> @frequencies.setter <NEW_LINE> def frequencies(self, frequencies): <NEW_LINE> <INDENT> self._frequencies = frequencies <NEW_LINE> <DEDENT> @property <NEW_LINE> def x(self): <NEW_LINE> <INDENT> return self._x <NEW_LINE> <DEDENT> @x.setter <NEW_LINE> def x(self, x): <NEW_LINE> <INDENT> self._x = x <NEW_LINE> <DEDENT> @property <NEW_LINE> def y(self): <NEW_LINE> <INDENT> return self._y <NEW_LINE> <DEDENT> @y.setter <NEW_LINE> def y(self, y): <NEW_LINE> <INDENT> self._y = y <NEW_LINE> <DEDENT> @property <NEW_LINE> def z(self): <NEW_LINE> <INDENT> return self._z <NEW_LINE> <DEDENT> @z.setter <NEW_LINE> def z(self, z): <NEW_LINE> <INDENT> self._z = z <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, FftSpectraDataPointFftSpectra): <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, FftSpectraDataPointFftSpectra): <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. | 62599056d7e4931a7ef3d5df |
class FocalLoss(nn.Module): <NEW_LINE> <INDENT> def __init__(self, class_num, alpha=None, gamma=2, size_average=True): <NEW_LINE> <INDENT> super(FocalLoss, self).__init__() <NEW_LINE> if alpha is None: <NEW_LINE> <INDENT> self.alpha = Variable(torch.ones(class_num, 1)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if isinstance(alpha, Variable): <NEW_LINE> <INDENT> self.alpha = alpha <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.alpha = Variable(alpha) <NEW_LINE> <DEDENT> <DEDENT> self.gamma = gamma <NEW_LINE> self.class_num = class_num <NEW_LINE> self.size_average = size_average <NEW_LINE> <DEDENT> def forward(self, inputs, targets): <NEW_LINE> <INDENT> if inputs.dim() == 4: <NEW_LINE> <INDENT> inputs = inputs.contiguous().view(inputs.size(0), inputs.size(1), -1) <NEW_LINE> inputs = inputs.transpose(1, 2) <NEW_LINE> inputs = inputs.contiguous().view(-1, inputs.size(2)).squeeze() <NEW_LINE> <DEDENT> if targets.dim() == 4: <NEW_LINE> <INDENT> targets = targets.contiguous().view(targets.size(0), targets.size(1), -1) <NEW_LINE> targets = targets.transpose(1,2) <NEW_LINE> targets = targets.contiguous().view(-1, targets.size(2)).squeeze() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> targets = targets.view(-1) <NEW_LINE> <DEDENT> P = F.softmax(inputs, dim=1) <NEW_LINE> class_mask = inputs.data.new(inputs.size()).fill_(0) <NEW_LINE> class_mask = Variable(class_mask) <NEW_LINE> ids = targets.view(-1, 1) <NEW_LINE> ids = ids.type(torch.LongTensor) <NEW_LINE> src = Variable(torch.ones(class_mask.size())) <NEW_LINE> if inputs.is_cuda: <NEW_LINE> <INDENT> src = src.cuda() <NEW_LINE> if not ids.is_cuda: <NEW_LINE> <INDENT> ids = ids.cuda() <NEW_LINE> <DEDENT> <DEDENT> class_mask.scatter_(1, ids, src) <NEW_LINE> if inputs.is_cuda and not self.alpha.is_cuda: <NEW_LINE> <INDENT> self.alpha = self.alpha.cuda() <NEW_LINE> <DEDENT> alpha = self.alpha[ids.data.view(-1)] <NEW_LINE> probs = (P * class_mask).sum(1).view(-1, 1) <NEW_LINE> log_p = probs.log() <NEW_LINE> batch_loss = -alpha * (torch.pow((1 - probs), self.gamma)) * log_p <NEW_LINE> if self.size_average: <NEW_LINE> <INDENT> loss = batch_loss.mean() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> loss = batch_loss.sum() <NEW_LINE> <DEDENT> return loss | This criterion is a implemenation of Focal Loss, which is proposed in
Focal Loss for Dense Object Detection.
Loss(x, class) = - \alpha (1-softmax(x)[class])^gamma \log(softmax(x)[class])
The losses are averaged across observations for each minibatch.
Args:
alpha(1D Tensor, Variable) : the scalar factor for this criterion
gamma(float, double) : gamma > 0; reduces the relative loss for well-classified examples (p > .5),
putting more focus on hard, misclassified examples
size_average(bool): size_average(bool): By default, the losses are averaged over observations for each minibatch.
However, if the field size_average is set to False, the losses are
instead summed for each minibatch. | 6259905621a7993f00c674cd |
class GetCcnRegionBandwidthLimitsResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.CcnBandwidthSet = None <NEW_LINE> self.TotalCount = None <NEW_LINE> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> if params.get("CcnBandwidthSet") is not None: <NEW_LINE> <INDENT> self.CcnBandwidthSet = [] <NEW_LINE> for item in params.get("CcnBandwidthSet"): <NEW_LINE> <INDENT> obj = CcnBandwidthInfo() <NEW_LINE> obj._deserialize(item) <NEW_LINE> self.CcnBandwidthSet.append(obj) <NEW_LINE> <DEDENT> <DEDENT> self.TotalCount = params.get("TotalCount") <NEW_LINE> self.RequestId = params.get("RequestId") | GetCcnRegionBandwidthLimits返回参数结构体
| 62599056adb09d7d5dc0bacb |
class EffectWalker(PropertiesWalker): <NEW_LINE> <INDENT> @property <NEW_LINE> def list(self): <NEW_LINE> <INDENT> obj = self.obj <NEW_LINE> element_effect = getattr(obj, 'element_effect', None) <NEW_LINE> effects = [] <NEW_LINE> while element_effect: <NEW_LINE> <INDENT> effects.append(element_effect) <NEW_LINE> element_effect = getattr(element_effect, 'parent', None) <NEW_LINE> <DEDENT> return effects <NEW_LINE> <DEDENT> @property <NEW_LINE> def widget(self): <NEW_LINE> <INDENT> obj = self.obj <NEW_LINE> name = getattr(obj, 'name', None) <NEW_LINE> if name: <NEW_LINE> <INDENT> name_part = name + ' ' <NEW_LINE> <DEDENT> elif hasattr(obj, 'index'): <NEW_LINE> <INDENT> name_part = '[{0}] '.format(obj.index) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> name_part = '' <NEW_LINE> <DEDENT> text = [('name', name_part), '({0})'.format(type(obj).__name__), ' → ', unicode(obj.value)] <NEW_LINE> return NonCachedText(text, wrap='clip') <NEW_LINE> <DEDENT> def wrap_child(self, item): <NEW_LINE> <INDENT> return EffectWalker(item) | TreeWalker for an effect | 625990563eb6a72ae038bbc0 |
class TestSupport(object): <NEW_LINE> <INDENT> def _generate_test_questions(self): <NEW_LINE> <INDENT> count, t = parse_test_def(self.header.test) <NEW_LINE> q = list(range(len(self.m_questions))) * count <NEW_LINE> random.shuffle(q) <NEW_LINE> return q <NEW_LINE> <DEDENT> def get_test_num_questions(self): <NEW_LINE> <INDENT> return len(self.m_questions) * parse_test_def(self.header.test)[0] <NEW_LINE> <DEDENT> def get_test_requirement(self): <NEW_LINE> <INDENT> m = re.match("([\d\.]+)%", self.header.test_requirement) <NEW_LINE> if m: <NEW_LINE> <INDENT> return float(m.groups()[0]) / 100.0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 0.9 <NEW_LINE> <DEDENT> <DEDENT> def enter_test_mode(self): <NEW_LINE> <INDENT> self.m_test_questions = self._generate_test_questions() <NEW_LINE> self.m_test_idx = -1 <NEW_LINE> <DEDENT> def next_test_question(self): <NEW_LINE> <INDENT> assert self.m_test_idx < len(self.m_test_questions) <NEW_LINE> self.m_test_idx += 1 <NEW_LINE> self._idx = self.m_test_questions[self.m_test_idx] <NEW_LINE> if self.header.random_transpose[0]: <NEW_LINE> <INDENT> old = self.m_transpose <NEW_LINE> for x in range(100): <NEW_LINE> <INDENT> self.m_transpose = self.find_random_transpose() <NEW_LINE> if old != self.m_transpose: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def is_test_complete(self): <NEW_LINE> <INDENT> return self.m_test_idx == len(self.m_test_questions) - 1 | Lessonfile classes can add this class to the list of classes it
inherits from if the exercise want to have tests. | 625990562c8b7c6e89bd4d4f |
class OnInput(AWSProperty): <NEW_LINE> <INDENT> props: PropsDictType = { "Events": ([Event], False), "TransitionEvents": ([TransitionEvent], False), } | `OnInput <http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotevents-detectormodel-oninput.html>`__ | 6259905632920d7e50bc75a7 |
class PostLike(db.Model): <NEW_LINE> <INDENT> __tablename__ = 'postlike' <NEW_LINE> author_id = db.Column(db.Integer, db.ForeignKey('user.user_id'), primary_key=True) <NEW_LINE> post_id = db.Column(db.Integer, db.ForeignKey('posts.post_id'), primary_key=True) <NEW_LINE> create_time = db.Column(db.DateTime, default=datetime.now) | 点赞关系表
| 6259905671ff763f4b5e8d11 |
class SortedDict(dict): <NEW_LINE> <INDENT> def __init__(self, data=None): <NEW_LINE> <INDENT> if data is None: <NEW_LINE> <INDENT> data = {} <NEW_LINE> <DEDENT> dict.__init__(self, data) <NEW_LINE> if isinstance(data, dict): <NEW_LINE> <INDENT> self.keyOrder = data.keys() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.keyOrder = [key for key, dummy_value in data] <NEW_LINE> <DEDENT> <DEDENT> def __deepcopy__(self, memo): <NEW_LINE> <INDENT> obj = self.__class__() <NEW_LINE> for k, v in self.items(): <NEW_LINE> <INDENT> obj[k] = deepcopy(v, memo) <NEW_LINE> <DEDENT> return obj <NEW_LINE> <DEDENT> def __setitem__(self, key, value): <NEW_LINE> <INDENT> dict.__setitem__(self, key, value) <NEW_LINE> if key not in self.keyOrder: <NEW_LINE> <INDENT> self.keyOrder.append(key) <NEW_LINE> <DEDENT> <DEDENT> def __delitem__(self, key): <NEW_LINE> <INDENT> dict.__delitem__(self, key) <NEW_LINE> self.keyOrder.remove(key) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> for k in self.keyOrder: <NEW_LINE> <INDENT> yield k <NEW_LINE> <DEDENT> <DEDENT> def pop(self, k, *args): <NEW_LINE> <INDENT> result = dict.pop(self, k, *args) <NEW_LINE> try: <NEW_LINE> <INDENT> self.keyOrder.remove(k) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def popitem(self): <NEW_LINE> <INDENT> result = dict.popitem(self) <NEW_LINE> self.keyOrder.remove(result[0]) <NEW_LINE> return result <NEW_LINE> <DEDENT> def items(self): <NEW_LINE> <INDENT> return zip(self.keyOrder, self.values()) <NEW_LINE> <DEDENT> def iteritems(self): <NEW_LINE> <INDENT> for key in self.keyOrder: <NEW_LINE> <INDENT> yield key, dict.__getitem__(self, key) <NEW_LINE> <DEDENT> <DEDENT> def keys(self): <NEW_LINE> <INDENT> return self.keyOrder[:] <NEW_LINE> <DEDENT> def iterkeys(self): <NEW_LINE> <INDENT> return iter(self.keyOrder) <NEW_LINE> <DEDENT> def values(self): <NEW_LINE> <INDENT> return [dict.__getitem__(self, k) for k in self.keyOrder] <NEW_LINE> <DEDENT> def itervalues(self): <NEW_LINE> <INDENT> for key in self.keyOrder: <NEW_LINE> <INDENT> yield dict.__getitem__(self, key) <NEW_LINE> <DEDENT> <DEDENT> def update(self, other_dict): <NEW_LINE> <INDENT> for k, v in other_dict.items(): <NEW_LINE> <INDENT> self.__setitem__(k, v) <NEW_LINE> <DEDENT> <DEDENT> def setdefault(self, key, default): <NEW_LINE> <INDENT> if key not in self.keyOrder: <NEW_LINE> <INDENT> self.keyOrder.append(key) <NEW_LINE> <DEDENT> return dict.setdefault(self, key, default) <NEW_LINE> <DEDENT> def value_for_index(self, index): <NEW_LINE> <INDENT> return self[self.keyOrder[index]] <NEW_LINE> <DEDENT> def insert(self, index, key, value): <NEW_LINE> <INDENT> if key in self.keyOrder: <NEW_LINE> <INDENT> n = self.keyOrder.index(key) <NEW_LINE> del self.keyOrder[n] <NEW_LINE> if n < index: <NEW_LINE> <INDENT> index -= 1 <NEW_LINE> <DEDENT> <DEDENT> self.keyOrder.insert(index, key) <NEW_LINE> dict.__setitem__(self, key, value) <NEW_LINE> <DEDENT> def copy(self): <NEW_LINE> <INDENT> obj = self.__class__(self) <NEW_LINE> obj.keyOrder = self.keyOrder <NEW_LINE> return obj <NEW_LINE> <DEDENT> def deepcopy(self): <NEW_LINE> <INDENT> return SortedDict([(k, deepcopy(v)) for k, v in self.items()]) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '{%s}' % ', '.join(['%r: %r' % (k, v) for k, v in self.items()]) | A dictionary that keeps its keys in the order in which they're inserted. | 62599056507cdc57c63a6306 |
class TestGetActionSelection(unittest.TestCase): <NEW_LINE> <INDENT> def testGetActionSolution(self): <NEW_LINE> <INDENT> actionlist = [1,2,3,4,5] <NEW_LINE> for action in actionlist: <NEW_LINE> <INDENT> if action == 1: <NEW_LINE> <INDENT> val = getActionSelection(action) <NEW_LINE> self.assertEqual(val,"Show All Books") <NEW_LINE> <DEDENT> if action == 2: <NEW_LINE> <INDENT> val = getActionSelection(action) <NEW_LINE> self.assertEqual(val,"Add a book") <NEW_LINE> <DEDENT> if action == 3: <NEW_LINE> <INDENT> val = getActionSelection(action) <NEW_LINE> self.assertEqual(val,"Edit a book") <NEW_LINE> <DEDENT> if action == 4: <NEW_LINE> <INDENT> val = getActionSelection(action) <NEW_LINE> self.assertEqual(val,"Remove a book") <NEW_LINE> <DEDENT> if action == 5: <NEW_LINE> <INDENT> val = getActionSelection(action) <NEW_LINE> self.assertEqual(val,"Exit Program") <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def testBadGetActionSolution(self): <NEW_LINE> <INDENT> actionlist = ["Add a book",7,8,100,"5","","@1"] <NEW_LINE> for action in actionlist: <NEW_LINE> <INDENT> val = getActionSelection(action) <NEW_LINE> self.assertFalse(val) | Test for getting action solution | 62599056fff4ab517ebced84 |
class Binomial: <NEW_LINE> <INDENT> def __init__(self, data=None, n=1, p=0.5): <NEW_LINE> <INDENT> if data is not None: <NEW_LINE> <INDENT> n = int(len(data) / 2) <NEW_LINE> q = 1 - p <NEW_LINE> for x in data: <NEW_LINE> <INDENT> p += np.power(p,x)*np.power(q,n-x) <NEW_LINE> <DEDENT> <DEDENT> self.n = n <NEW_LINE> self.p = p | Sets the instance attributes n and p | 62599056be8e80087fbc05e4 |
class PostSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> url = serializers.HyperlinkedIdentityField(view_name='blog:post-detail') <NEW_LINE> category = serializers.SlugRelatedField(read_only=True, slug_field='name') <NEW_LINE> tag = serializers.SlugRelatedField(many=True, read_only=True, slug_field='name') <NEW_LINE> owner = serializers.SlugRelatedField(read_only=True, slug_field='username') <NEW_LINE> created_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M%S") <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = Post <NEW_LINE> fields = ['url', 'id', 'title', 'category', 'tag', 'owner', 'created_time'] | 文章列表接口需要的serializer | 62599056b7558d58954649dc |
class Partial(Item): <NEW_LINE> <INDENT> duration = None <NEW_LINE> def partial_length(self): <NEW_LINE> <INDENT> if self.duration: <NEW_LINE> <INDENT> base, scaling = self.duration.base_scaling <NEW_LINE> return base * scaling | A \partial command. | 62599056a8ecb03325872779 |
class TestIndex(_BaseData.BaseIndex): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.calcType = None <NEW_LINE> self.num = None <NEW_LINE> self.min = 0 <NEW_LINE> self.max = 1 <NEW_LINE> self.step = 1 | Index class for TestData
:var calcType: calculation type, 'num' or 'rnd'
:var num: number of elements
:var min: minimal value
:var max: maximal value, 'rnd' only
:var step: step size for num only | 62599056462c4b4f79dbcf67 |
class VirtualPatientState(object): <NEW_LINE> <INDENT> def __init__( self, bg, sensor_bg, bg_prediction, pump_state, iob, iob_prediction, sensor_bg_prediction, isf, cir, ): <NEW_LINE> <INDENT> self.bg = bg <NEW_LINE> self.sensor_bg = sensor_bg <NEW_LINE> self.bg_prediction = bg_prediction <NEW_LINE> self.sensor_bg_prediction = sensor_bg_prediction <NEW_LINE> self.iob = iob <NEW_LINE> self.iob_prediction = iob_prediction <NEW_LINE> self.pump_state = pump_state <NEW_LINE> self.isf = isf <NEW_LINE> self.cir = cir | A class of instantaneous patient information. | 6259905694891a1f408ba1a7 |
class Sprite(sfml.Sprite, Thing): <NEW_LINE> <INDENT> depth = 0 <NEW_LINE> def __lt__(self, other): <NEW_LINE> <INDENT> return self.depth < other.depth <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> pass | Sfmllän Sprite paitsi että sen voi laitella syvyyden mukaan | 62599056ac7a0e7691f73a43 |
class ResearchModelOpsAPIView(WdCreateAPIView): <NEW_LINE> <INDENT> model = ResearchModel <NEW_LINE> POST_CHECK_REQUEST_PARAMETER = ('ops_type', 'model_id') <NEW_LINE> OPS_TYPE_RELEASE = 'release' <NEW_LINE> OPS_TYPE_INHERIT = 'inherit' <NEW_LINE> def post_check_parameter(self, kwargs): <NEW_LINE> <INDENT> err_code = super(ResearchModelOpsAPIView, self).post_check_parameter(kwargs) <NEW_LINE> if err_code != ErrorCode.SUCCESS: <NEW_LINE> <INDENT> return err_code <NEW_LINE> <DEDENT> if self.ops_type == self.OPS_TYPE_RELEASE: <NEW_LINE> <INDENT> if not ResearchSubstandard.objects.filter_active(model_id=self.model_id).exists(): <NEW_LINE> <INDENT> return ErrorCode.RESEARCH_MODEL_RELEASE_DATA_INVALID <NEW_LINE> <DEDENT> <DEDENT> elif self.ops_type == self.OPS_TYPE_INHERIT: <NEW_LINE> <INDENT> src_model = ResearchModel.objects.get(id=self.model_id) <NEW_LINE> if src_model.status != ResearchModel.STATUS_RELEASE: <NEW_LINE> <INDENT> return ErrorCode.RESEARCH_MODEL_INHERIT_DATA_INVALID <NEW_LINE> <DEDENT> <DEDENT> return ErrorCode.SUCCESS <NEW_LINE> <DEDENT> def release_model(self): <NEW_LINE> <INDENT> ResearchModel.objects.filter(id=self.model_id).update(status=ResearchModel.STATUS_RELEASE) <NEW_LINE> return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS) <NEW_LINE> <DEDENT> def inherit_model(self): <NEW_LINE> <INDENT> new_model_name = self.request.data.get('new_model_name', None) <NEW_LINE> new_model_en_name = self.request.data.get('new_model_en_name', None) <NEW_LINE> if new_model_name is None or new_model_en_name is None: <NEW_LINE> <INDENT> return general_json_response(status.HTTP_200_OK, ErrorCode.INVALID_INPUT) <NEW_LINE> <DEDENT> inherit_obj = ResearchModelUtils.deep_copy(int(self.model_id), new_model_name, new_model_en_name) <NEW_LINE> return general_json_response(status.HTTP_200_OK, ErrorCode.SUCCESS, {"id": inherit_obj.id}) <NEW_LINE> <DEDENT> def post(self, request, *args, **kwargs): <NEW_LINE> <INDENT> if self.ops_type == self.OPS_TYPE_RELEASE: <NEW_LINE> <INDENT> return self.release_model() <NEW_LINE> <DEDENT> elif self.ops_type == self.OPS_TYPE_INHERIT: <NEW_LINE> <INDENT> return self.inherit_model() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return general_json_response(status.HTTP_200_OK, ErrorCode.INVALID_INPUT) | 模型的发布与派生 | 62599056baa26c4b54d50807 |
class discrete_var_bounds_MILP(_ModelClassBase): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> _ModelClassBase.__init__(self) <NEW_LINE> self.linear = True <NEW_LINE> self.integer = True <NEW_LINE> self.disable_suffix_tests = True <NEW_LINE> self.results_file = join(thisDir,"discrete_var_bounds_MILP.results") <NEW_LINE> <DEDENT> def descrStr(self): <NEW_LINE> <INDENT> return "discrete_var_bounds_MILP" <NEW_LINE> <DEDENT> def generateModel(self): <NEW_LINE> <INDENT> self.model = None <NEW_LINE> self.model = ConcreteModel() <NEW_LINE> model = self.model <NEW_LINE> model.name = self.descrStr() <NEW_LINE> model.w2 = Var(within=Binary) <NEW_LINE> model.x2 = Var(within=Binary) <NEW_LINE> model.yb = Var(within=Binary, bounds=(1,1)) <NEW_LINE> model.zb = Var(within=Binary, bounds=(0,0)) <NEW_LINE> model.yi = Var(within=Integers, bounds=(-1,None)) <NEW_LINE> model.zi = Var(within=Integers, bounds=(None,1)) <NEW_LINE> model.obj = Objective(expr= model.w2 - model.x2 + model.yb - model.zb + model.yi - model.zi) <NEW_LINE> model.c3 = Constraint(expr=model.w2 >= 0) <NEW_LINE> model.c4 = Constraint(expr=model.x2 <= 1) <NEW_LINE> <DEDENT> def warmstartModel(self): <NEW_LINE> <INDENT> assert self.model is not None <NEW_LINE> model = self.model <NEW_LINE> model.w2 = None <NEW_LINE> model.x2 = 1 <NEW_LINE> model.yb = 0 <NEW_LINE> model.zb = 1 <NEW_LINE> model.yi = None <NEW_LINE> model.zi = 0 | A discrete model where discrete variables have custom bounds | 6259905601c39578d7f141e8 |
class TestDeterminant(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self) -> None: <NEW_LINE> <INDENT> self.func = Determinant() <NEW_LINE> self.simplifier = StepSimplifier() <NEW_LINE> <DEDENT> def create_call_expr(self, *args): <NEW_LINE> <INDENT> return Call(self.func, args) <NEW_LINE> <DEDENT> def test_call(self): <NEW_LINE> <INDENT> self.assertRaises(TypeError, lambda: self.simplifier(self.create_call_expr(1))) <NEW_LINE> array = np.array([[1, 2]]) <NEW_LINE> self.assertRaises(ValueError, lambda: self.simplifier(self.create_call_expr(array))) <NEW_LINE> array = np.array([[1]]) <NEW_LINE> expected = 1 <NEW_LINE> self.assertEqual(expected, self.simplifier(self.create_call_expr(array))) <NEW_LINE> array = np.array([[1, 2], [3, 4]]) <NEW_LINE> expected = Sum((Product((1, 4)), Product((-2, 3)))) <NEW_LINE> self.assertEqual(expected, self.simplifier(self.create_call_expr(array))) <NEW_LINE> array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) <NEW_LINE> expected = Sum((Product((1, self.create_call_expr(np.array([[5, 6], [8, 9]])))), Product((-2, self.create_call_expr(np.array([[4, 6], [7, 9]])))), Product((3, self.create_call_expr(np.array([[4, 5], [7, 8]])))))) <NEW_LINE> self.assertEqual(expected, self.simplifier(self.create_call_expr(array))) | Tests the functionalities and properties of a `matstep.matrices
.Determinant` instance. | 6259905621a7993f00c674cf |
class StorageAccountCreateParameters(Model): <NEW_LINE> <INDENT> _validation = { 'resource_id': {'required': True}, 'active_key_name': {'required': True}, 'auto_regenerate_key': {'required': True}, } <NEW_LINE> _attribute_map = { 'resource_id': {'key': 'resourceId', 'type': 'str'}, 'active_key_name': {'key': 'activeKeyName', 'type': 'str'}, 'auto_regenerate_key': {'key': 'autoRegenerateKey', 'type': 'bool'}, 'regeneration_period': {'key': 'regenerationPeriod', 'type': 'str'}, 'storage_account_attributes': {'key': 'attributes', 'type': 'StorageAccountAttributes'}, 'tags': {'key': 'tags', 'type': '{str}'}, } <NEW_LINE> def __init__(self, *, resource_id: str, active_key_name: str, auto_regenerate_key: bool, regeneration_period: str=None, storage_account_attributes=None, tags=None, **kwargs) -> None: <NEW_LINE> <INDENT> super(StorageAccountCreateParameters, self).__init__(**kwargs) <NEW_LINE> self.resource_id = resource_id <NEW_LINE> self.active_key_name = active_key_name <NEW_LINE> self.auto_regenerate_key = auto_regenerate_key <NEW_LINE> self.regeneration_period = regeneration_period <NEW_LINE> self.storage_account_attributes = storage_account_attributes <NEW_LINE> self.tags = tags | The storage account create parameters.
All required parameters must be populated in order to send to Azure.
:param resource_id: Required. Storage account resource id.
:type resource_id: str
:param active_key_name: Required. Current active storage account key name.
:type active_key_name: str
:param auto_regenerate_key: Required. whether keyvault should manage the
storage account for the user.
:type auto_regenerate_key: bool
:param regeneration_period: The key regeneration time duration specified
in ISO-8601 format.
:type regeneration_period: str
:param storage_account_attributes: The attributes of the storage account.
:type storage_account_attributes:
~azure.keyvault.models.StorageAccountAttributes
:param tags: Application specific metadata in the form of key-value pairs.
:type tags: dict[str, str] | 6259905676e4537e8c3f0aee |
@dataclass(order=True) <NEW_LINE> class Favourite: <NEW_LINE> <INDENT> lcn: int = field( init=True, repr=True, compare=True, ) <NEW_LINE> channelno: str = field( init=True, repr=True, compare=False, ) <NEW_LINE> channelname: str = field( init=True, repr=True, compare=False, ) <NEW_LINE> sid: str = field( init=True, repr=True, compare=False, ) <NEW_LINE> def __hash__(self): <NEW_LINE> <INDENT> return hash(self.lcn) <NEW_LINE> <DEDENT> def as_json(self) -> str: <NEW_LINE> <INDENT> return json.dumps(self, cls=_favouriteJSONEncoder) | SkyQ favourite Class. | 625990564e4d56256637396a |
class IrBlaster(object): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def periods_to_microseconds(frequency, pattern): <NEW_LINE> <INDENT> period = 1000000. / frequency <NEW_LINE> return [period * x for x in pattern] <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def microseconds_to_periods(frequency, pattern): <NEW_LINE> <INDENT> period = 1000000. / frequency <NEW_LINE> return [x / period for x in pattern] <NEW_LINE> <DEDENT> @property <NEW_LINE> def frequencies(self): <NEW_LINE> <INDENT> return self.get_frequencies() <NEW_LINE> <DEDENT> def get_frequencies(self): <NEW_LINE> <INDENT> return self._get_frequencies() <NEW_LINE> <DEDENT> def transmit(self, frequency, pattern, mode='period'): <NEW_LINE> <INDENT> return self._transmit(frequency, pattern, mode) <NEW_LINE> <DEDENT> def exists(self): <NEW_LINE> <INDENT> return self._exists() <NEW_LINE> <DEDENT> def _get_frequencies(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def _transmit(self, frequency, pattern, mode): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def _exists(self): <NEW_LINE> <INDENT> raise NotImplementedError() | Infrared blaster facade. | 6259905607f4c71912bb099d |
class ParameterParameter(ParameterExpressionItem): <NEW_LINE> <INDENT> datatype = "" <NEW_LINE> def __init__(self, _datatype="", _operator=None): <NEW_LINE> <INDENT> super(ParameterParameter, self).__init__(_operator) <NEW_LINE> self.datatype = _datatype <NEW_LINE> <DEDENT> def _generate_sql(self, _db_type): <NEW_LINE> <INDENT> return datatype_to_parameter(_db_type, self.datatype) | Holds a parameter to be used in prepared statements. | 6259905632920d7e50bc75a9 |
class GdwATMetatags(ATMetatags): <NEW_LINE> <INDENT> implements(IOpengraphMetatags) <NEW_LINE> @property <NEW_LINE> def admins(self): <NEW_LINE> <INDENT> pwManager = getUtility(IPasswordManager, 'facebookadmins') <NEW_LINE> admins = self.settings.admins or pwManager.username <NEW_LINE> return admins <NEW_LINE> <DEDENT> @property <NEW_LINE> def app_id(self): <NEW_LINE> <INDENT> pwManager = getUtility(IPasswordManager, 'facebookapp') <NEW_LINE> appid = self.settings.app_id or pwManager.username <NEW_LINE> return appid <NEW_LINE> <DEDENT> @property <NEW_LINE> def content_type(self): <NEW_LINE> <INDENT> return 'hotel' <NEW_LINE> <DEDENT> @property <NEW_LINE> def image_url(self): <NEW_LINE> <INDENT> return "%s/logo.png" % self.portal_state.portal_url() | Facebook informations for gdw | 625990562c8b7c6e89bd4d51 |
class _AbsConverge(_ConvergeFunction): <NEW_LINE> <INDENT> def is_converge(self, loss): <NEW_LINE> <INDENT> if loss <= self.eps: <NEW_LINE> <INDENT> converge_flag = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> converge_flag = False <NEW_LINE> <DEDENT> return converge_flag | Judge converge by absolute loss value. When loss value smaller than eps, converge flag
will be provided. | 625990564a966d76dd5f0454 |
class User(AbstractBaseUser, PermissionsMixin): <NEW_LINE> <INDENT> uuid = models.UUIDField( default=uuid.uuid4, editable=False, unique=True, verbose_name=_('uuid') ) <NEW_LINE> email = models.EmailField( _('email address'), unique=True, db_index=True ) <NEW_LINE> first_name = models.CharField( _('first name'), max_length=30, blank=True ) <NEW_LINE> last_name = models.CharField( _('last name'), max_length=30, blank=True ) <NEW_LINE> is_staff = models.BooleanField( _('staff status'), default=False, help_text=_('Designates whether the user can log into this admin site.'), ) <NEW_LINE> is_active = models.BooleanField( _('active'), default=True, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of deleting accounts.' ), ) <NEW_LINE> is_validated = models.BooleanField( _('validated'), default=False, help_text=_( 'Designates whether this user has passed account validation.' ), ) <NEW_LINE> date_joined = models.DateTimeField( _('date joined'), default=timezone.now ) <NEW_LINE> USERNAME_FIELD = "email" <NEW_LINE> REQUIRED_FIELDS = [] <NEW_LINE> objects = UserManager() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = _('user') <NEW_LINE> verbose_name_plural = _('users') <NEW_LINE> <DEDENT> def get_full_name(self): <NEW_LINE> <INDENT> return "{first} {last}".format( first=self.first_name, last=self.last_name ) <NEW_LINE> <DEDENT> def get_short_name(self): <NEW_LINE> <INDENT> return self.first_name <NEW_LINE> <DEDENT> def send_system_email(self, template, context): <NEW_LINE> <INDENT> t = Template(template_string=template.content) <NEW_LINE> ctx = Context(context) <NEW_LINE> content = t.render(ctx) | User model | 6259905673bcbd0ca4bcb7f5 |
class Following(ListView): <NEW_LINE> <INDENT> def get(self, request): <NEW_LINE> <INDENT> following = self.get_queryset() <NEW_LINE> if len(following) == 0: <NEW_LINE> <INDENT> return redirect(reverse('following-add')) <NEW_LINE> <DEDENT> context = {'followed_resource': following} <NEW_LINE> return render(request, 'followed-resources/followed_resource.html', context) <NEW_LINE> <DEDENT> def get_queryset(self): <NEW_LINE> <INDENT> return FollowedResource.objects.filter( user=self.request.user ).order_by('resource') | Display the list of resources that are being followed by the user. | 62599056e5267d203ee6ce52 |
class BookInstance(models.Model): <NEW_LINE> <INDENT> id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="Unique ID for this particular book across whole library") <NEW_LINE> book = models.ForeignKey('Book', on_delete=models.SET_NULL, null=True) <NEW_LINE> imprint = models.CharField(max_length=200) <NEW_LINE> due_back = models.DateField(null=True, blank=True) <NEW_LINE> borrower = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) <NEW_LINE> LOAN_STATUS = ( ('d', 'Maintenance'), ('o', 'On loan'), ('a', 'Available'), ('r', 'Reserved'), ) <NEW_LINE> status= models.CharField(max_length=1, choices=LOAN_STATUS, blank=True, default='d', help_text='Book availability') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> ordering = ["due_back"] <NEW_LINE> permissions = (("can_mark_returned", "Set book as returned"),) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '%s (%s)' % (self.id,self.book.title) | Model representing a specific copy of a book (i.e. that can be borrowed from the library). | 625990568e7ae83300eea5f1 |
class Solution(object): <NEW_LINE> <INDENT> def twoSum(self, nums: list, target: int)-> list: <NEW_LINE> <INDENT> m_dict = dict() <NEW_LINE> out_list = list() <NEW_LINE> for i in range(0, len(nums)): <NEW_LINE> <INDENT> if nums[i] in m_dict: <NEW_LINE> <INDENT> out_list.append(m_dict.get(nums[i])) <NEW_LINE> out_list.append(i) <NEW_LINE> break <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> m_dict[target - nums[i]] = i <NEW_LINE> <DEDENT> <DEDENT> return out_list | Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1]. | 6259905615baa723494634f6 |
class MyDocTemplate(BaseDocTemplate): <NEW_LINE> <INDENT> _invalidInitArgs = ('pageTemplates',) <NEW_LINE> def __init__(self, filename, **kw): <NEW_LINE> <INDENT> frame1 = Frame(2.5*cm, 2.5*cm, 15*cm, 25*cm, id='F1') <NEW_LINE> self.allowSplitting = 0 <NEW_LINE> BaseDocTemplate.__init__(self, filename, **kw) <NEW_LINE> template = PageTemplate('normal', [frame1], myMainPageFrame) <NEW_LINE> self.addPageTemplates(template) <NEW_LINE> <DEDENT> def afterFlowable(self, flowable): <NEW_LINE> <INDENT> if flowable.__class__.__name__ == 'Paragraph': <NEW_LINE> <INDENT> styleName = flowable.style.name <NEW_LINE> if styleName[:7] == 'Heading': <NEW_LINE> <INDENT> key = str(hash(flowable)) <NEW_LINE> self.canv.bookmarkPage(key) <NEW_LINE> level = int(styleName[7:]) <NEW_LINE> text = flowable.getPlainText() <NEW_LINE> pageNum = self.page <NEW_LINE> if level % 2 == 1: <NEW_LINE> <INDENT> self.notify('TOCEntry', (level, text, pageNum, key)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.notify('TOCEntry', (level, text, pageNum)) | The document template used for all PDF documents. | 62599056b7558d58954649dd |
class Deck: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.cards = [] <NEW_LINE> for rank in ["two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "jack", "queen", "king", "ace"]: <NEW_LINE> <INDENT> for suit in ["clubs", "diamonds", "hearts", "spades"]: <NEW_LINE> <INDENT> self.cards += [Card(rank,suit)] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> answer = "Deck of Cards\n" <NEW_LINE> answer += "-------------\n" <NEW_LINE> number = 1 <NEW_LINE> for card in self.cards: <NEW_LINE> <INDENT> answer += str(number) + " " + card.__str__() + "\n" <NEW_LINE> number += 1 <NEW_LINE> <DEDENT> return answer <NEW_LINE> <DEDENT> def shuffle(self): <NEW_LINE> <INDENT> while len(self.cards) > 0: <NEW_LINE> <INDENT> random_position = random.randit (0, len(self.cards) - 1) <NEW_LINE> removed_card = self.cards.pop(random_position) <NEW_LINE> result += [removed_card] <NEW_LINE> <DEDENT> self.cards = result | Deck class for representing and manipulating 52 instances of Card | 62599056097d151d1a2c25cf |
class HMLight(HMDevice, Light): <NEW_LINE> <INDENT> @property <NEW_LINE> def brightness(self): <NEW_LINE> <INDENT> if self._state == "LEVEL": <NEW_LINE> <INDENT> return int(self._hm_get_state() * 255) <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_on(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self._hm_get_state() > 0 <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def supported_features(self): <NEW_LINE> <INDENT> features = SUPPORT_BRIGHTNESS <NEW_LINE> if "COLOR" in self._hmdevice.WRITENODE: <NEW_LINE> <INDENT> features |= SUPPORT_COLOR <NEW_LINE> <DEDENT> if "PROGRAM" in self._hmdevice.WRITENODE: <NEW_LINE> <INDENT> features |= SUPPORT_EFFECT <NEW_LINE> <DEDENT> return features <NEW_LINE> <DEDENT> @property <NEW_LINE> def hs_color(self): <NEW_LINE> <INDENT> if not self.supported_features & SUPPORT_COLOR: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> hue, sat = self._hmdevice.get_hs_color(self._channel) <NEW_LINE> return hue * 360.0, sat * 100.0 <NEW_LINE> <DEDENT> @property <NEW_LINE> def effect_list(self): <NEW_LINE> <INDENT> if not self.supported_features & SUPPORT_EFFECT: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self._hmdevice.get_effect_list() <NEW_LINE> <DEDENT> @property <NEW_LINE> def effect(self): <NEW_LINE> <INDENT> if not self.supported_features & SUPPORT_EFFECT: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self._hmdevice.get_effect() <NEW_LINE> <DEDENT> def turn_on(self, **kwargs): <NEW_LINE> <INDENT> if ATTR_TRANSITION in kwargs: <NEW_LINE> <INDENT> self._hmdevice.setValue("RAMP_TIME", kwargs[ATTR_TRANSITION]) <NEW_LINE> <DEDENT> if ATTR_BRIGHTNESS in kwargs and self._state == "LEVEL": <NEW_LINE> <INDENT> percent_bright = float(kwargs[ATTR_BRIGHTNESS]) / 255 <NEW_LINE> self._hmdevice.set_level(percent_bright, self._channel) <NEW_LINE> <DEDENT> elif ATTR_HS_COLOR not in kwargs and ATTR_EFFECT not in kwargs: <NEW_LINE> <INDENT> self._hmdevice.on(self._channel) <NEW_LINE> <DEDENT> if ATTR_HS_COLOR in kwargs: <NEW_LINE> <INDENT> self._hmdevice.set_hs_color( hue=kwargs[ATTR_HS_COLOR][0] / 360.0, saturation=kwargs[ATTR_HS_COLOR][1] / 100.0, channel=self._channel, ) <NEW_LINE> <DEDENT> if ATTR_EFFECT in kwargs: <NEW_LINE> <INDENT> self._hmdevice.set_effect(kwargs[ATTR_EFFECT]) <NEW_LINE> <DEDENT> <DEDENT> def turn_off(self, **kwargs): <NEW_LINE> <INDENT> self._hmdevice.off(self._channel) <NEW_LINE> <DEDENT> def _init_data_struct(self): <NEW_LINE> <INDENT> self._state = "LEVEL" <NEW_LINE> self._data[self._state] = None <NEW_LINE> if self.supported_features & SUPPORT_COLOR: <NEW_LINE> <INDENT> self._data.update({"COLOR": None}) <NEW_LINE> <DEDENT> if self.supported_features & SUPPORT_EFFECT: <NEW_LINE> <INDENT> self._data.update({"PROGRAM": None}) | Representation of a Homematic light. | 62599056d99f1b3c44d06c04 |
class TechnicalParameterName(models.Model): <NEW_LINE> <INDENT> index_weight = 7 <NEW_LINE> category = models.ForeignKey(Category,verbose_name=_("material category")) <NEW_LINE> name = models.CharField(_("name"),max_length=const.DB_CHAR_NAME_40) <NEW_LINE> status = models.BooleanField(_("in use"),default=True) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return '%s' % self.name <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = _('technical parameter') <NEW_LINE> verbose_name_plural = _('technical parameter') | 技术参数-名称,将技术参数绑定于物料分类上,在此分类下的物料自动继承全部技术参数 | 625990568da39b475be04750 |
class ProfileFeedItem(models.Model): <NEW_LINE> <INDENT> user_profile = models.ForeignKey('UserProfile',on_delete=models.CASCADE) <NEW_LINE> status_text = models.CharField(max_length=255) <NEW_LINE> created_on = models.DateTimeField(auto_now_add=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.status_text | Profile status update | 62599056a219f33f346c7d69 |
class PredEvtWaitQueue: <NEW_LINE> <INDENT> def __init__(self, env, pred, get_evt): <NEW_LINE> <INDENT> self.evts = deque() <NEW_LINE> self.env = env <NEW_LINE> self.pred = pred <NEW_LINE> def loop(): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> if self.evts: <NEW_LINE> <INDENT> evt = self.evts.popleft() <NEW_LINE> evt.succeed() <NEW_LINE> <DEDENT> yield self.env.timeout(0) <NEW_LINE> yield get_evt() <NEW_LINE> print('evt succeed') <NEW_LINE> <DEDENT> <DEDENT> env.process(loop()) <NEW_LINE> <DEDENT> def queue(self): <NEW_LINE> <INDENT> evt = self.env.event() <NEW_LINE> if self.pred(): <NEW_LINE> <INDENT> evt.succeed() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.evts.append(evt) <NEW_LINE> <DEDENT> return evt | Takes a function returning a predicate and an function returning an event.
When someone queues, will return an event that either is succeeded
instantly if the predicat is true otherwise will succeed when an event is
triggered is true in FIFO order. | 6259905630dc7b76659a0d31 |
class User_Admin_EditForm(User_Form): <NEW_LINE> <INDENT> class Meta(User_Form.Meta): <NEW_LINE> <INDENT> exclude = ('password','last_login','is_staff','date_joined') | Form with sensitive fields. | 625990563539df3088ecd80b |
class SimpleConfig(DoconfConfig): <NEW_LINE> <INDENT> pass | name: simple_app
# The environment
{default}
[main_section]
HOST (str:"127.0.0.1"): who the server hosts the app to
PORT (int:8080): the default port, defined as an integer with default 8080
TIMEOUT (int): this is required because no default was defined
MILES_PER_HOUR (int:null): this is NOT required and is default None
DEBUG (bool:false): this is a boolean that is defaulting to False
# We can continue to define new sections.
[other_section]
NAME: this variable has no type defined so it is a "str" and required
AGE (int): this is an integer that is required. Due to this being required,
> it will fail if this section doesn't exist. This is also a long
> multiline description with continued lines specified with ">" prefix.
[third_section]
THIRD_SECT_VALUE (str:null): not required, default None | 62599056097d151d1a2c25d0 |
class ifeof(IfCommand): <NEW_LINE> <INDENT> def invoke(self, tex): <NEW_LINE> <INDENT> tex.readNumber() <NEW_LINE> tex.processIfContent(False) <NEW_LINE> return [] | Test for end of file | 62599056596a897236129062 |
class Place: <NEW_LINE> <INDENT> def __init__(self, name, exit=None): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.exit = exit <NEW_LINE> self.bees = [] <NEW_LINE> self.ant = None <NEW_LINE> self.entrance = None <NEW_LINE> if exit != None: <NEW_LINE> <INDENT> exit.entrance = self <NEW_LINE> <DEDENT> <DEDENT> def add_insect(self, insect): <NEW_LINE> <INDENT> if insect.is_ant: <NEW_LINE> <INDENT> if self.ant: <NEW_LINE> <INDENT> if self.ant.container and (insect.container or self.ant.ant): <NEW_LINE> <INDENT> assert self.ant is None, "More than one bodyguard" <NEW_LINE> <DEDENT> if not self.ant.container and not insect.container: <NEW_LINE> <INDENT> assert self.ant is None, 'Two ants in {0}'.format(self) <NEW_LINE> <DEDENT> if self.ant.can_contain(insect): <NEW_LINE> <INDENT> self.ant.contain_ant(insect) <NEW_LINE> insect.place = self <NEW_LINE> return <NEW_LINE> <DEDENT> if insect.can_contain(self.ant): <NEW_LINE> <INDENT> insect.contain_ant(self.ant) <NEW_LINE> self.ant = insect <NEW_LINE> insect.place = self <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.ant = insect <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.bees.append(insect) <NEW_LINE> <DEDENT> insect.place = self <NEW_LINE> <DEDENT> def remove_insect(self, insect): <NEW_LINE> <INDENT> if insect.is_ant: <NEW_LINE> <INDENT> assert self.ant == insect, '{0} is not in {1}'.format(insect, self) <NEW_LINE> if type(insect) == QueenAnt and insect.queen_impostor: <NEW_LINE> <INDENT> self.ant = None <NEW_LINE> insect.place = None <NEW_LINE> <DEDENT> if insect.container and insect.ant: <NEW_LINE> <INDENT> self.ant = insect.ant <NEW_LINE> insect.place = None <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.bees.remove(insect) <NEW_LINE> <DEDENT> insect.place = None <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.name | A Place holds insects and has an exit to another Place. | 625990563c8af77a43b689f2 |
class FileField(BaseField): <NEW_LINE> <INDENT> def __init__( self, name, value=None, ajax=False ): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.ajax = ajax <NEW_LINE> self.value = value <NEW_LINE> <DEDENT> def get_html( self, prefix="" ): <NEW_LINE> <INDENT> value_text = "" <NEW_LINE> if self.value: <NEW_LINE> <INDENT> value_text = ' value="%s"' % escape( str( self.value ), quote=True ) <NEW_LINE> <DEDENT> ajax_text = "" <NEW_LINE> if self.ajax: <NEW_LINE> <INDENT> ajax_text = ' galaxy-ajax-upload="true"' <NEW_LINE> <DEDENT> return unicodify( '<input type="file" name="%s%s"%s%s>' % ( prefix, self.name, ajax_text, value_text ) ) | A file upload input.
>>> print FileField( "foo" ).get_html()
<input type="file" name="foo">
>>> print FileField( "foo", ajax = True ).get_html()
<input type="file" name="foo" galaxy-ajax-upload="true"> | 6259905699cbb53fe6832443 |
class PUTOrderPatchRequestType(object): <NEW_LINE> <INDENT> swagger_types = { 'custom_fields': 'OrderObjectCustomFields', 'subscriptions': 'list[PUTOrderPatchRequestTypeSubscriptions]' } <NEW_LINE> attribute_map = { 'custom_fields': 'customFields', 'subscriptions': 'subscriptions' } <NEW_LINE> def __init__(self, custom_fields=None, subscriptions=None): <NEW_LINE> <INDENT> self._custom_fields = None <NEW_LINE> self._subscriptions = None <NEW_LINE> self.discriminator = None <NEW_LINE> if custom_fields is not None: <NEW_LINE> <INDENT> self.custom_fields = custom_fields <NEW_LINE> <DEDENT> if subscriptions is not None: <NEW_LINE> <INDENT> self.subscriptions = subscriptions <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def custom_fields(self): <NEW_LINE> <INDENT> return self._custom_fields <NEW_LINE> <DEDENT> @custom_fields.setter <NEW_LINE> def custom_fields(self, custom_fields): <NEW_LINE> <INDENT> self._custom_fields = custom_fields <NEW_LINE> <DEDENT> @property <NEW_LINE> def subscriptions(self): <NEW_LINE> <INDENT> return self._subscriptions <NEW_LINE> <DEDENT> @subscriptions.setter <NEW_LINE> def subscriptions(self, subscriptions): <NEW_LINE> <INDENT> self._subscriptions = subscriptions <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> 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, PUTOrderPatchRequestType): <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. | 625990564e696a045264e8d4 |
class AllSubDevicesGetPerformSelfTest(TestMixins.AllSubDevicesGetMixin, OptionalParameterTestFixture): <NEW_LINE> <INDENT> PID = 'PERFORM_SELFTEST' | Send a Get PERFORM_SELFTEST to ALL_SUB_DEVICES. | 625990567d847024c075d93f |
class ResourceSetupException(ResourceException): <NEW_LINE> <INDENT> pass | Resource setup failed | 625990564e4d56256637396c |
class NumpyToTensor(AbstractTransform): <NEW_LINE> <INDENT> def __call__(self, **data_dict): <NEW_LINE> <INDENT> import torch <NEW_LINE> data = data_dict.get("data") <NEW_LINE> seg = data_dict.get("seg") <NEW_LINE> assert isinstance(data, np.ndarray) <NEW_LINE> data_dict["data"] = torch.from_numpy(data) <NEW_LINE> if seg is not None: <NEW_LINE> <INDENT> data_dict["seg"] = torch.from_numpy(seg) <NEW_LINE> <DEDENT> return data_dict | Utility function for pytorch. Converts data (and seg) numpy ndarrays to pytorch tensors
| 62599056379a373c97d9a589 |
@register_message('shortvideo') <NEW_LINE> class ShortVideoMessage(BaseMessage): <NEW_LINE> <INDENT> type = 'shortvideo' <NEW_LINE> media_id = StringField('MediaId') <NEW_LINE> thumb_media_id = StringField('ThumbMediaId') | 短视频消息
详情请参阅
http://mp.weixin.qq.com/wiki/10/79502792eef98d6e0c6e1739da387346.html | 625990562ae34c7f260ac64c |
class XianHua(object): <NEW_LINE> <INDENT> def run(self, tel_num, session): <NEW_LINE> <INDENT> session.get() <NEW_LINE> return tel_num | 处理过程
生成结果文件 ==>> xianhua.xlsx | 625990568e7ae83300eea5f3 |
class RaspiledControlSite(Site, object): <NEW_LINE> <INDENT> ip_address = None <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> resource = kwargs.pop("resource", RaspiledControlResource()) <NEW_LINE> super(RaspiledControlSite, self).__init__(resource=resource, requestFactory=SmartRequest, *args, **kwargs) <NEW_LINE> <DEDENT> def buildProtocol(self, addr): <NEW_LINE> <INDENT> self.ip_address = addr <NEW_LINE> self.resource.ip_address = addr <NEW_LINE> return super(RaspiledControlSite, self).buildProtocol(addr) <NEW_LINE> <DEDENT> def setup_broadcasting(self, reactor): <NEW_LINE> <INDENT> self.resource.setup_broadcasting(reactor) <NEW_LINE> <DEDENT> def stopFactory(self): <NEW_LINE> <INDENT> self.resource.teardown() | Site thread which initialises the RaspiledControlResource properly | 62599056460517430c432b04 |
class Solution: <NEW_LINE> <INDENT> def maxPathSum(self, root): <NEW_LINE> <INDENT> if root is None: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> single, double = self.helper(root) <NEW_LINE> return max(single, double) <NEW_LINE> <DEDENT> def helper(self, root): <NEW_LINE> <INDENT> if root is None: <NEW_LINE> <INDENT> return None, None <NEW_LINE> <DEDENT> leftSingle, leftDouble = self.helper(root.left) <NEW_LINE> rightSingle, rightDouble = self.helper(root.right) <NEW_LINE> if leftSingle is None and rightSingle is None: <NEW_LINE> <INDENT> return root.val, root.val <NEW_LINE> <DEDENT> if leftSingle is None and rightSingle is not None: <NEW_LINE> <INDENT> return max(rightSingle, 0) + root.val, max(rightSingle + root.val, rightDouble, root.val) <NEW_LINE> <DEDENT> if rightSingle is None and leftSingle is not None: <NEW_LINE> <INDENT> return max(leftSingle, 0) + root.val, max(leftSingle + root.val, leftDouble, root.val) <NEW_LINE> <DEDENT> single = max(leftSingle, rightSingle, 0) + root.val <NEW_LINE> double = max(leftSingle + rightSingle + root.val, leftDouble, rightDouble, root.val) <NEW_LINE> return single, double | @param root: The root of binary tree.
@return: An integer | 62599056004d5f362081faa0 |
class BlockStream(object): <NEW_LINE> <INDENT> def __init__(self, new_blocks): <NEW_LINE> <INDENT> b = Bigchain() <NEW_LINE> self.new_blocks = new_blocks <NEW_LINE> self.unvoted_blocks = [] <NEW_LINE> if not b.federation_nodes: <NEW_LINE> <INDENT> self.unvoted_blocks = b.get_unvoted_blocks() <NEW_LINE> <DEDENT> <DEDENT> def get(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.unvoted_blocks.pop(0) <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> return self.new_blocks.get() | Combine the stream of new blocks coming from the changefeed with the list of unvoted blocks.
This is a utility class that abstracts the source of data for the `Voter`. | 62599056b830903b9686ef31 |
class FirmwareCompatibilityResponseTest(unittest.TestCase): <NEW_LINE> <INDENT> def test_firmware_compatibility_response(self): <NEW_LINE> <INDENT> firmware_compatibility_response_obj = FirmwareCompatibilityResponse() <NEW_LINE> self.assertNotEqual(firmware_compatibility_response_obj, None) | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 62599056d99f1b3c44d06c06 |
class ConstFAC_DCDC(ConstPSBSMP): <NEW_LINE> <INDENT> V_PS_SOFT_INTERLOCKS = 31 <NEW_LINE> V_PS_HARD_INTERLOCKS = 32 <NEW_LINE> V_I_LOAD_MEAN = 33 <NEW_LINE> V_I_LOAD1 = 34 <NEW_LINE> V_I_LOAD2 = 35 <NEW_LINE> V_V_CAPBANK = 36 <NEW_LINE> V_DUTY_CYCLE = 37 <NEW_LINE> V_V_INPUT_IIB = 38 <NEW_LINE> V_I_INPUT_IIB = 39 <NEW_LINE> V_I_OUTPUT_IIB = 40 <NEW_LINE> V_TEMP_IGBT_1_IIB = 41 <NEW_LINE> V_TEMP_IGBT_2_IIB = 42 <NEW_LINE> V_TEMP_INDUCTOR_IIB = 43 <NEW_LINE> V_TEMP_HEATSINK_IIB = 44 <NEW_LINE> V_V_DRIVER_IIB = 45 <NEW_LINE> V_I_DRIVER_1_IIB = 46 <NEW_LINE> V_I_DRIVER_2_IIB = 47 <NEW_LINE> V_I_LEAKAGE_IIB = 48 <NEW_LINE> V_TEMP_BOARD_IIB = 49 <NEW_LINE> V_RH_IIB = 50 <NEW_LINE> V_IIB_INTERLOCKS = 51 <NEW_LINE> V_IIB_ALARMS = 52 | Namespace for organizing power supply FAC_DCDC BSMP constants. | 6259905691af0d3eaad3b38f |
class MigrationsController(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.compute_api = compute.API() <NEW_LINE> <DEDENT> def index(self, req): <NEW_LINE> <INDENT> context = req.environ['patron.context'] <NEW_LINE> authorize(context, "index") <NEW_LINE> patron_context.require_admin_context(context) <NEW_LINE> migrations = self.compute_api.get_migrations(context, req.GET) <NEW_LINE> return {'migrations': output(migrations)} | Controller for accessing migrations in OpenStack API. | 625990568da39b475be04752 |
class BaseModel(models.Model): <NEW_LINE> <INDENT> creat_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间') <NEW_LINE> update_time = models.DateTimeField(auto_now=True, verbose_name='更新时间') <NEW_LINE> is_delete = models.BooleanField(default=False, verbose_name='删除标记') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> abstract = True | 抽象模型类基类 | 625990564e4d56256637396d |
class ofp_action_push(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.type = 0 <NEW_LINE> self.len = 0 <NEW_LINE> self.ethertype = 0 <NEW_LINE> self.pad= [0,0] <NEW_LINE> <DEDENT> def __assert(self): <NEW_LINE> <INDENT> if(not isinstance(self.pad, list)): <NEW_LINE> <INDENT> return (False, "self.pad is not list as expected.") <NEW_LINE> <DEDENT> if(len(self.pad) != 2): <NEW_LINE> <INDENT> return (False, "self.pad is not of size 2 as expected.") <NEW_LINE> <DEDENT> return (True, None) <NEW_LINE> <DEDENT> def pack(self, assertstruct=True): <NEW_LINE> <INDENT> if(assertstruct): <NEW_LINE> <INDENT> if(not self.__assert()[0]): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> packed = "" <NEW_LINE> packed += struct.pack("!HHH", self.type, self.len, self.ethertype) <NEW_LINE> packed += struct.pack("!BB", self.pad[0], self.pad[1]) <NEW_LINE> return packed <NEW_LINE> <DEDENT> def unpack(self, binaryString): <NEW_LINE> <INDENT> if (len(binaryString) < 8): <NEW_LINE> <INDENT> return binaryString <NEW_LINE> <DEDENT> fmt = '!HHH' <NEW_LINE> start = 0 <NEW_LINE> end = start + struct.calcsize(fmt) <NEW_LINE> (self.type, self.len, self.ethertype) = struct.unpack(fmt, binaryString[start:end]) <NEW_LINE> fmt = '!BB' <NEW_LINE> start = 6 <NEW_LINE> end = start + struct.calcsize(fmt) <NEW_LINE> (self.pad[0], self.pad[1]) = struct.unpack(fmt, binaryString[start:end]) <NEW_LINE> return binaryString[8:] <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> l = 8 <NEW_LINE> return l <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if type(self) != type(other): return False <NEW_LINE> if self.type != other.type: return False <NEW_LINE> if self.len != other.len: return False <NEW_LINE> if self.ethertype != other.ethertype: return False <NEW_LINE> if self.pad != other.pad: return False <NEW_LINE> return True <NEW_LINE> <DEDENT> def __ne__(self, other): return not self.__eq__(other) <NEW_LINE> def show(self, prefix=''): <NEW_LINE> <INDENT> outstr = '' <NEW_LINE> outstr += prefix + 'type: ' + str(self.type) + '\n' <NEW_LINE> outstr += prefix + 'len: ' + str(self.len) + '\n' <NEW_LINE> outstr += prefix + 'ethertype: ' + str(self.ethertype) + '\n' <NEW_LINE> return outstr | Automatically generated Python class for ofp_action_push
Date 2013-01-06
Created by of.pythonize.pythonizer
Core structure: Messages do not include ofp_header
Does not include var-length arrays | 6259905630dc7b76659a0d32 |
@register <NEW_LINE> class SourceBreakpoint(BaseSchema): <NEW_LINE> <INDENT> __props__ = { "line": { "type": "integer", "description": "The source line of the breakpoint or logpoint." }, "column": { "type": "integer", "description": "An optional source column of the breakpoint." }, "condition": { "type": "string", "description": "An optional expression for conditional breakpoints." }, "hitCondition": { "type": "string", "description": "An optional expression that controls how many hits of the breakpoint are ignored. The backend is expected to interpret the expression as needed." }, "logMessage": { "type": "string", "description": "If this attribute exists and is non-empty, the backend must not 'break' (stop) but log the message instead. Expressions within {} are interpolated." } } <NEW_LINE> __refs__ = set() <NEW_LINE> __slots__ = list(__props__.keys()) + ['kwargs'] <NEW_LINE> def __init__(self, line, column=None, condition=None, hitCondition=None, logMessage=None, **kwargs): <NEW_LINE> <INDENT> self.line = line <NEW_LINE> self.column = column <NEW_LINE> self.condition = condition <NEW_LINE> self.hitCondition = hitCondition <NEW_LINE> self.logMessage = logMessage <NEW_LINE> self.kwargs = kwargs <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> dct = { 'line': self.line, } <NEW_LINE> if self.column is not None: <NEW_LINE> <INDENT> dct['column'] = self.column <NEW_LINE> <DEDENT> if self.condition is not None: <NEW_LINE> <INDENT> dct['condition'] = self.condition <NEW_LINE> <DEDENT> if self.hitCondition is not None: <NEW_LINE> <INDENT> dct['hitCondition'] = self.hitCondition <NEW_LINE> <DEDENT> if self.logMessage is not None: <NEW_LINE> <INDENT> dct['logMessage'] = self.logMessage <NEW_LINE> <DEDENT> dct.update(self.kwargs) <NEW_LINE> return dct | Properties of a breakpoint or logpoint passed to the setBreakpoints request.
Note: automatically generated code. Do not edit manually. | 6259905663b5f9789fe866d9 |
class MoreKFragsThanArrangements(TypeError): <NEW_LINE> <INDENT> pass | Raised when a Policy has been used to generate Arrangements with Ursulas insufficient number
such that we don't have enough KFrags to give to each Ursula. | 6259905699cbb53fe6832446 |
class Input(Port): <NEW_LINE> <INDENT> def __init__(self, shape, name, dtype=None): <NEW_LINE> <INDENT> self.shape = shape <NEW_LINE> self._name = name <NEW_LINE> if dtype is None: <NEW_LINE> <INDENT> dtype = FLOATX <NEW_LINE> <DEDENT> self._dtype = dtype <NEW_LINE> self._variable = [TENSOR_TYPES[self.ndim](name=self._name, dtype=self._dtype)] <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self._variable = [TENSOR_TYPES[self.ndim](name=self._name, dtype=self._dtype)] <NEW_LINE> <DEDENT> @property <NEW_LINE> def __json__(self): <NEW_LINE> <INDENT> return dict( shape=self.shape, name=self.name, dtype=self.dtype, type=self.type) <NEW_LINE> <DEDENT> @property <NEW_LINE> def dtype(self): <NEW_LINE> <INDENT> return self._variable[0].dtype <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._variable[0].name <NEW_LINE> <DEDENT> @name.setter <NEW_LINE> def name(self, name): <NEW_LINE> <INDENT> self._variable[0].name = name | writeme.
shape = ...
None -> scalar
[1,] -> vector
[1, 2, ] -> matrix
[1, 2, 3, ] -> tensor3
[1, 2, 3, 4, ] -> tensor4 | 6259905621a7993f00c674d3 |
class ProcTestOutput(proctest.ProcTest): <NEW_LINE> <INDENT> def test_process_output_nonewline(self): <NEW_LINE> <INDENT> p = processhandler.ProcessHandler([self.python, "procnonewline.py"], cwd=here) <NEW_LINE> p.run() <NEW_LINE> p.processOutput(timeout=5) <NEW_LINE> p.wait() <NEW_LINE> detected, output = proctest.check_for_process("procnonewline.py") <NEW_LINE> self.determine_status(detected, output, p.proc.returncode, p.didTimeout, False, ()) <NEW_LINE> <DEDENT> def test_stream_process_output(self): <NEW_LINE> <INDENT> expected = '\n'.join([str(n) for n in range(0,10)]) <NEW_LINE> stream = io.BytesIO() <NEW_LINE> buf = io.BufferedRandom(stream) <NEW_LINE> p = processhandler.ProcessHandler([self.python, "proccountfive.py"], cwd=here, stream=buf) <NEW_LINE> p.run() <NEW_LINE> p.wait() <NEW_LINE> for i in range(5, 10): <NEW_LINE> <INDENT> stream.write(str(i)+'\n') <NEW_LINE> <DEDENT> buf.flush() <NEW_LINE> self.assertEquals(stream.getvalue().strip(), expected) <NEW_LINE> self.assertFalse(buf.closed) <NEW_LINE> buf.close() <NEW_LINE> detected, output = proctest.check_for_process("proccountfive.py") <NEW_LINE> self.determine_status(detected, output, p.proc.returncode, p.didTimeout, False, ()) | Class to test operations related to output handling | 62599056dd821e528d6da433 |
class RelatedReferral(models.Model): <NEW_LINE> <INDENT> from_referral = models.ForeignKey( Referral, on_delete=models.PROTECT, related_name="from_referral" ) <NEW_LINE> to_referral = models.ForeignKey( Referral, on_delete=models.PROTECT, related_name="to_referral" ) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return "{0} ({1} to {2})".format( self.pk, self.from_referral.pk, self.to_referral.pk ) | Intermediate class for relationships between Referral objects.
Trying to create this relationship without the intermediate class generated
some really odd recursion errors. | 625990567d847024c075d941 |
class YoConfigManager: <NEW_LINE> <INDENT> def __init__(self, filename, defaults=None): <NEW_LINE> <INDENT> defaults = defaults or {} <NEW_LINE> self.config_data = configparser.ConfigParser( inline_comment_prefixes=';') <NEW_LINE> self.config_data['yo_general'] = {'log_level': 'INFO', 'yo_db_url': ''} <NEW_LINE> self.config_data['vapid'] = {} <NEW_LINE> self.config_data['blockchain_follower'] = {} <NEW_LINE> self.config_data['notification_sender'] = {} <NEW_LINE> self.config_data['api_server'] = {} <NEW_LINE> self.vapid_priv_key = None <NEW_LINE> self.vapid = None <NEW_LINE> for k, v in defaults.items(): <NEW_LINE> <INDENT> self.config_data[k] = v <NEW_LINE> <DEDENT> if filename: <NEW_LINE> <INDENT> self.config_data.read(filename) <NEW_LINE> <DEDENT> for section in self.config_data.sections(): <NEW_LINE> <INDENT> for k in self.config_data[section]: <NEW_LINE> <INDENT> if section.startswith('yo_'): <NEW_LINE> <INDENT> env_name = k.upper() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> env_name = 'YO_%s_%s' % (section.upper(), k.upper()) <NEW_LINE> <DEDENT> if not os.getenv(env_name) is None: <NEW_LINE> <INDENT> self.config_data[section][k] = os.getenv(env_name) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> log_level = self.config_data['yo_general'].get('log_level', 'INFO') <NEW_LINE> logging.basicConfig(level=log_level) <NEW_LINE> self.generate_needed() <NEW_LINE> <DEDENT> def get_listen_host(self): <NEW_LINE> <INDENT> return self.config_data['http'].get('listen_host', '0.0.0.0') <NEW_LINE> <DEDENT> def get_listen_port(self): <NEW_LINE> <INDENT> return int(self.config_data['http'].get('listen_port', 8080)) <NEW_LINE> <DEDENT> def generate_needed(self): <NEW_LINE> <INDENT> self.vapid_priv_key = self.config_data['vapid'].get('priv_key', None) <NEW_LINE> if self.vapid_priv_key is None: <NEW_LINE> <INDENT> self.vapid = py_vapid.Vapid() <NEW_LINE> self.vapid.generate_keys() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if not self.vapid_priv_key: <NEW_LINE> <INDENT> self.vapid = py_vapid.Vapid() <NEW_LINE> self.vapid.generate_keys() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.vapid = py_vapid.Vapid.from_raw( private_raw=self.vapid_priv_key.encode()) | A class for handling configuration details all in one place
Also handles generation of missing keys where this is appropriate to do so | 625990564e4d56256637396e |
class HostPinger: <NEW_LINE> <INDENT> def __init__(self, PassedCommand): <NEW_LINE> <INDENT> self._command = PassedCommand <NEW_LINE> <DEDENT> def ping(self, PassedHostname): <NEW_LINE> <INDENT> myStatus, myOutput = commands.getstatusoutput(self._command + " " + PassedHostname) <NEW_LINE> return myStatus | Simple generic class whose funciton is to attempt to ping a given host. | 62599056097d151d1a2c25d2 |
class Bullet(Sprite): <NEW_LINE> <INDENT> def __init__(self, ai_game): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.screen = ai_game.screen <NEW_LINE> self.settings = ai_game.settings <NEW_LINE> self.color = self.settings.bullet_color <NEW_LINE> self.image = pygame.image.load('images/bullet.bmp') <NEW_LINE> self.rect = self.image.get_rect() <NEW_LINE> self.rect = pygame.Rect(0, 0, self.settings.bullet_width, self.settings.bullet_height) <NEW_LINE> self.rect.midtop = ai_game.ship.rect.midtop <NEW_LINE> self.x = float(self.rect.x) <NEW_LINE> self.y = float(self.rect.y) <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.y -= self.settings.bullet_speed <NEW_LINE> self.rect.y = self.y <NEW_LINE> <DEDENT> def draw_bullet(self): <NEW_LINE> <INDENT> self.screen.blit(self.image, self.rect) | A class to manage bullets fired from the ship | 6259905621bff66bcd7241cb |
class Regression(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def calculate(self, samples): <NEW_LINE> <INDENT> raise NotImplementedError | Base class for regression algorithms | 625990562ae34c7f260ac64d |
class KILOGRAM_FORCE( Unit ): <NEW_LINE> <INDENT> name= "kg_f" <NEW_LINE> standard= NEWTON <NEW_LINE> factor= 1/9.8065 | Kg (force) | 6259905671ff763f4b5e8d17 |
class MoneyField(serializers.Field): <NEW_LINE> <INDENT> def to_representation(self, obj): <NEW_LINE> <INDENT> return { 'amount': "%f" % (obj.amount), 'currency': "%s" % (obj.currency), } <NEW_LINE> <DEDENT> def to_internal_value(self, data): <NEW_LINE> <INDENT> return Money(data['amount'], data['currency']) | MoneyField is not officially supported by Django REST framework
so a new field serializer class should be implemented | 625990564a966d76dd5f0458 |
class AirbusScraper(Scraper): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def scrape_jobs(cls, response): <NEW_LINE> <INDENT> jobs = [] <NEW_LINE> soup = BeautifulSoup(response.text, 'html.parser') <NEW_LINE> for job_posting in cls._iter_job_postings(soup): <NEW_LINE> <INDENT> title, url = job_posting.text, job_posting['href'] <NEW_LINE> jobs.append( JobItem(Domain.AIRBUS, title, url) ) <NEW_LINE> <DEDENT> return jobs <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _iter_job_postings(soup): <NEW_LINE> <INDENT> _job_div = ('div', {'class': 'c-jobcarousel__slider--title'}) <NEW_LINE> _job_div_a = 'a' <NEW_LINE> for job_div in soup.find_all(*_job_div): <NEW_LINE> <INDENT> div_a = job_div.find(_job_div_a) <NEW_LINE> if div_a is not None: <NEW_LINE> <INDENT> yield div_a <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def scrape_job_details(cls, response): <NEW_LINE> <INDENT> _details_description_div = ('h2', {'text': 'Description of the job'}) <NEW_LINE> soup = BeautifulSoup(response.text, 'html.parser') <NEW_LINE> return JobDetails(category=cls._get_category(soup), department=cls._get_department(soup), summary=cls._get_summary(soup), duties=cls._get_duties(soup), skills=cls._get_skills(soup), location=cls._get_location(soup)) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _get_category(cls, soup): <NEW_LINE> <INDENT> return cls._get_target_by_parent_str(soup, 'span', 'span', 'Division') <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _get_department(cls, soup): <NEW_LINE> <INDENT> return cls._get_target_by_parent_str(soup, 'span', 'span', 'Functional Area') <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _get_summary(cls, soup): <NEW_LINE> <INDENT> return cls._get_target_by_parent_str(soup, 'div', 'h2', 'Description of the job') <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _get_duties(cls, soup): <NEW_LINE> <INDENT> return cls._get_target_by_parent_str(soup, 'div', 'h2', 'Tasks & accountabilities') <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _get_skills(cls, soup): <NEW_LINE> <INDENT> return cls._get_target_by_parent_str(soup, 'div', 'h2', 'Required skills') <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _get_location(cls, soup): <NEW_LINE> <INDENT> return cls._get_target_by_parent_str(soup, 'span', 'span', 'Location') <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _get_target_by_parent_str(soup, target_tag, parent_tag, parent_string): <NEW_LINE> <INDENT> parent_tag = soup.find(parent_tag, string=parent_string) <NEW_LINE> if parent_tag: <NEW_LINE> <INDENT> target_tag = parent_tag.findNext(target_tag) <NEW_LINE> return target_tag.text if target_tag else None | Scraper objects for Airbus html content. | 62599056be383301e0254d40 |
class Characteristic(object): <NEW_LINE> <INDENT> def __init__(self, handle, value): <NEW_LINE> <INDENT> self.handle = handle <NEW_LINE> self.value = value <NEW_LINE> self.props = value[0] <NEW_LINE> self.char_handle = struct.unpack('<H', value[1:3])[0] <NEW_LINE> self.raw_uuid = value[3:] <NEW_LINE> self.uuid = pp_hex(self.raw_uuid) <NEW_LINE> self.descriptors = {} <NEW_LINE> <DEDENT> def add_descriptor(self, handle, raw_uuid, uuid): <NEW_LINE> <INDENT> self.descriptors[handle] = Descriptor(handle, raw_uuid, uuid) <NEW_LINE> <DEDENT> def can_read(self): <NEW_LINE> <INDENT> return (self.props & PROP_READ != 0) <NEW_LINE> <DEDENT> def can_write(self): <NEW_LINE> <INDENT> return (self.props & PROP_WRITE != 0) <NEW_LINE> <DEDENT> def can_notify(self): <NEW_LINE> <INDENT> return (self.props & PROP_NOTIFY != 0) <NEW_LINE> <DEDENT> def pp_properties(self): <NEW_LINE> <INDENT> p = [] <NEW_LINE> if self.props & PROP_BROADCAST: <NEW_LINE> <INDENT> p.append('Broadcast') <NEW_LINE> <DEDENT> if self.props & PROP_READ: <NEW_LINE> <INDENT> p.append('Read') <NEW_LINE> <DEDENT> if self.props & PROP_WRITE_NO_RESP: <NEW_LINE> <INDENT> p.append('Write No Response') <NEW_LINE> <DEDENT> if self.props & PROP_WRITE: <NEW_LINE> <INDENT> p.append('Write') <NEW_LINE> <DEDENT> if self.props & PROP_NOTIFY: <NEW_LINE> <INDENT> p.append('Notify') <NEW_LINE> <DEDENT> return '|'.join(p) <NEW_LINE> <DEDENT> def get_descriptor_by_uuid(self, uuid): <NEW_LINE> <INDENT> for d in list(self.descriptors.values()): <NEW_LINE> <INDENT> if d.uuid == uuid: <NEW_LINE> <INDENT> return d <NEW_LINE> <DEDENT> <DEDENT> return None <NEW_LINE> <DEDENT> def pp(self, baseindent=1): <NEW_LINE> <INDENT> indent = '\t' * baseindent <NEW_LINE> print('{}Char uuid={}'.format(indent, self.uuid)) <NEW_LINE> print('{}\tProperties: {}'.format(indent, self.pp_properties())) <NEW_LINE> print('{}\tHandle: 0x{:04X}'.format(indent, self.handle)) <NEW_LINE> print('{}\tChar handle: 0x{:04X}'.format(indent, self.char_handle)) <NEW_LINE> print('{}\tNum descs: {}'.format(indent, len(self.descriptors))) <NEW_LINE> for d in self.descriptors.values(): <NEW_LINE> <INDENT> d.pp() <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> s = '[Characteristic] handle={:04X}, uuid={}, descriptors='.format(self.handle, self.uuid) <NEW_LINE> for d in self.descriptors.values(): <NEW_LINE> <INDENT> s += '\n\t{}'.format(d) <NEW_LINE> <DEDENT> return s | Represents a BLE characteristic within a service | 6259905629b78933be26ab78 |
class AppsHandler(BaseHandler): <NEW_LINE> <INDENT> def get(self): <NEW_LINE> <INDENT> self.template('apps/list.html', { 'repo': (config.githubAppListUser, config.githubAppListRepo), 'apps': AppStore().apps, }) | Displays apps available on github | 62599056be8e80087fbc05ea |
class DateEditor(wx.adv.DatePickerCtrl): <NEW_LINE> <INDENT> def __init__(self, olv,row,col, **kwargs): <NEW_LINE> <INDENT> wx.adv.DatePickerCtrl.__init__(self,olv, **kwargs) <NEW_LINE> self.SetValue(None) <NEW_LINE> olv.editor = {col:self} <NEW_LINE> self.Bind(wx.EVT_CHAR_HOOK, self._OnChar) <NEW_LINE> self.row = row <NEW_LINE> self.col = col <NEW_LINE> <DEDENT> def _OnChar(self, event): <NEW_LINE> <INDENT> OnChar(self,event) <NEW_LINE> <DEDENT> def SetValue(self, value): <NEW_LINE> <INDENT> if isinstance(value,(datetime.date,datetime.datetime)): <NEW_LINE> <INDENT> dt = wx.DateTime(value.day, value.month-1 , value.year) <NEW_LINE> <DEDENT> elif isinstance(value,wx.DateTime): <NEW_LINE> <INDENT> dt = wx.DateTime(value.GetDay(), value.GetMonth(), value.GetYear()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dt = wx.DateTime.Today() <NEW_LINE> <DEDENT> wx.adv.DatePickerCtrl.SetValue(self, dt) <NEW_LINE> <DEDENT> def GetValue(self): <NEW_LINE> <INDENT> dt = wx.adv.DatePickerCtrl.GetValue(self) <NEW_LINE> return dt | This control uses standard datetime.
wx.DatePickerCtrl works only with wx.DateTime, but they are strange beasts.
wx.DataTime use 0 indexed months, i.e. January==0 and December==11. | 625990568a43f66fc4bf36f5 |
class TaggedObjectListView(ListView): <NEW_LINE> <INDENT> def get(self, request, *args, **kwargs): <NEW_LINE> <INDENT> slug = kwargs.get('slug') <NEW_LINE> self.tag = get_object_or_404(Tag, slug=slug) <NEW_LINE> self.object_list = self.get_queryset() <NEW_LINE> context = self.get_context_data(object_list=self.object_list) <NEW_LINE> return self.render_to_response(context) <NEW_LINE> <DEDENT> def get_queryset(self): <NEW_LINE> <INDENT> original_queryset = super(ListView, self).get_queryset() <NEW_LINE> queryset = original_queryset.filter(pk__in=TaggedItem.objects.filter( tag=self.tag, content_type=ContentType.objects.get_for_model(original_queryset.model) ).values_list("object_id", flat=True)) <NEW_LINE> return queryset <NEW_LINE> <DEDENT> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super(ListView, self).get_context_data(**kwargs) <NEW_LINE> context['tag'] = self.tag <NEW_LINE> return context | Return all objects (from model or queryset) with specified tag | 62599056498bea3a75a5908e |
class Dataset(ArtifactType): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__(metadata_store_pb2.ArtifactType.DATASET) | Dataset is a system pre-defined artifact type. | 6259905663d6d428bbee3d3b |
class BLive_OT_videotexture_playlist_clear(bpy.types.Operator): <NEW_LINE> <INDENT> bl_idname = "blive.videotexture_playlist_clear" <NEW_LINE> bl_label = "BLive empty playlist entry" <NEW_LINE> @classmethod <NEW_LINE> def poll(self, context): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return bool(context.active_object.active_material.active_texture.image) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def execute(self, context): <NEW_LINE> <INDENT> player = context.active_object.active_material.active_texture.image.player <NEW_LINE> player.playlist.clear() <NEW_LINE> return{'CANCELLED'} | Videotexture clear playlist | 62599056b830903b9686ef32 |
class CloudtrailLogHasErrors(CloudtrailLogging): <NEW_LINE> <INDENT> active = True <NEW_LINE> severity = 2 <NEW_LINE> def __init__(self, app): <NEW_LINE> <INDENT> self.title = "CloudTrail: Logs delivered without errors" <NEW_LINE> self.description = ( "Checks that CloudTrail is able to write successfully to the S3 bucket." ) <NEW_LINE> self.why_is_it_important = ( "CloudTrail keeps logs of API calls made on your AWS account.<br />" "These logs allow closer monitoring of activity, " "to make sure that users and resources are not behaving incorrectly.<br />" "Because of this, it is important to make sure CloudTrail is not misconfigured." ) <NEW_LINE> self.how_do_i_fix_it = ( "Make sure that the S3 bucket that CloudTrail targets exists " "- if it gets removed, the logs can’t be delivered.<br />" "Make sure that CloudTrail has write permissions for the bucket it’s trying to deliver its logs to." ) <NEW_LINE> super(CloudtrailLogHasErrors, self).__init__(app) <NEW_LINE> <DEDENT> def evaluate(self, event, item, whitelist=[]): <NEW_LINE> <INDENT> compliance_type = "COMPLIANT" <NEW_LINE> self.annotation = "" <NEW_LINE> if item["metadata"][4] is not None: <NEW_LINE> <INDENT> compliance_type = "NON_COMPLIANT" <NEW_LINE> self.annotation = ( f'The cloudtrail {item["metadata"][1]} in region {item["metadata"][0]} has errors, ' f'the last one being: "{item["metadata"][4]}".' ) <NEW_LINE> <DEDENT> return self.build_evaluation( item["resourceId"], compliance_type, event, self.resource_type, self.annotation, ) | TODO | 62599056cc0a2c111447c554 |
class wrapcauchy_gen(rv_continuous): <NEW_LINE> <INDENT> def _argcheck(self, c): <NEW_LINE> <INDENT> return (c > 0) & (c < 1) <NEW_LINE> <DEDENT> def _pdf(self, x, c): <NEW_LINE> <INDENT> return (1.0-c*c)/(2*np.pi*(1+c*c-2*c*np.cos(x))) <NEW_LINE> <DEDENT> def _cdf(self, x, c): <NEW_LINE> <INDENT> output = np.zeros(x.shape, dtype=x.dtype) <NEW_LINE> val = (1.0+c)/(1.0-c) <NEW_LINE> c1 = x < np.pi <NEW_LINE> c2 = 1-c1 <NEW_LINE> xp = np.extract(c1, x) <NEW_LINE> xn = np.extract(c2, x) <NEW_LINE> if np.any(xn): <NEW_LINE> <INDENT> valn = np.extract(c2, np.ones_like(x)*val) <NEW_LINE> xn = 2*np.pi - xn <NEW_LINE> yn = np.tan(xn/2.0) <NEW_LINE> on = 1.0-1.0/np.pi*np.arctan(valn*yn) <NEW_LINE> np.place(output, c2, on) <NEW_LINE> <DEDENT> if np.any(xp): <NEW_LINE> <INDENT> valp = np.extract(c1, np.ones_like(x)*val) <NEW_LINE> yp = np.tan(xp/2.0) <NEW_LINE> op = 1.0/np.pi*np.arctan(valp*yp) <NEW_LINE> np.place(output, c1, op) <NEW_LINE> <DEDENT> return output <NEW_LINE> <DEDENT> def _ppf(self, q, c): <NEW_LINE> <INDENT> val = (1.0-c)/(1.0+c) <NEW_LINE> rcq = 2*np.arctan(val*np.tan(np.pi*q)) <NEW_LINE> rcmq = 2*np.pi-2*np.arctan(val*np.tan(np.pi*(1-q))) <NEW_LINE> return np.where(q < 1.0/2, rcq, rcmq) <NEW_LINE> <DEDENT> def _entropy(self, c): <NEW_LINE> <INDENT> return np.log(2*np.pi*(1-c*c)) | A wrapped Cauchy continuous random variable.
%(before_notes)s
Notes
-----
The probability density function for `wrapcauchy` is:
.. math::
f(x, c) = \frac{1-c^2}{2\pi (1+c^2 - 2c \cos(x))}
for :math:`0 \le x \le 2\pi`, :math:`0 < c < 1`.
`wrapcauchy` takes ``c`` as a shape parameter for :math:`c`.
%(after_notes)s
%(example)s | 6259905607d97122c4218213 |
class proxy_ip3366(object): <NEW_LINE> <INDENT> pass | http://www.ip3366.net/free/?page=2 | 62599056adb09d7d5dc0bad3 |
class World(Named, cache_size=20, cache_ttu=3600.0): <NEW_LINE> <INDENT> collection = 'world' <NEW_LINE> data: WorldData <NEW_LINE> id_field = 'world_id' <NEW_LINE> _model = WorldData <NEW_LINE> id: int <NEW_LINE> name: LocaleData <NEW_LINE> state: str <NEW_LINE> description: Optional[LocaleData] <NEW_LINE> async def events(self, **kwargs: Any) -> List[CensusData]: <NEW_LINE> <INDENT> collection: Final[str] = 'world_event' <NEW_LINE> query = Query(collection, service_id=self._client.service_id, **kwargs) <NEW_LINE> query.add_term(field=self.id_field, value=self.id) <NEW_LINE> query.limit(1000) <NEW_LINE> payload = await self._client.request(query) <NEW_LINE> data = extract_payload(payload, collection=collection) <NEW_LINE> return data <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> @deprecated('0.2', '0.3', replacement=':meth:`auraxium.Client.get`') <NEW_LINE> async def get_by_name(cls: Type[NamedT], name: str, *, locale: str = 'en', client: RequestClient) -> Optional[NamedT]: <NEW_LINE> <INDENT> data = await cls.find(20, client=client) <NEW_LINE> if data and not isinstance(data[0], cls): <NEW_LINE> <INDENT> raise RuntimeError( f'Expected {cls} instance, got {type(data[0])} instead, ' 'please report this bug to the project maintainers') <NEW_LINE> <DEDENT> name = name.lower() <NEW_LINE> for world in data: <NEW_LINE> <INDENT> if getattr(world.name, locale.lower(), '') == name: <NEW_LINE> <INDENT> return world <NEW_LINE> <DEDENT> <DEDENT> return None <NEW_LINE> <DEDENT> async def map(self, zone: Union[int, Zone], *args: Union[int, Zone]) -> List[CensusData]: <NEW_LINE> <INDENT> collection: Final[str] = 'map' <NEW_LINE> query = Query(collection, service_id=self._client.service_id) <NEW_LINE> query.add_term(field=self.id_field, value=self.id) <NEW_LINE> zone_ids: List[int] = [zone if isinstance(zone, int) else zone.id] <NEW_LINE> zone_ids.extend(z if isinstance(z, int) else z.id for z in args) <NEW_LINE> value = ','.join(str(z) for z in zone_ids) <NEW_LINE> query.add_term(field='zone_ids', value=value) <NEW_LINE> query.limit(3000) <NEW_LINE> payload = await self._client.request(query) <NEW_LINE> data = extract_payload(payload, collection=collection) <NEW_LINE> return data <NEW_LINE> <DEDENT> async def status(self) -> Tuple[str, datetime.datetime]: <NEW_LINE> <INDENT> query = Query('game_server_status', namespace='global', service_id=self._client.service_id, game_code='ps2', name=f'^{self.data.name.en}') <NEW_LINE> payload = await self._client.request(query) <NEW_LINE> data = extract_single(payload, 'game_server_status') <NEW_LINE> status = str(data['last_reported_state']) <NEW_LINE> last_updated = int(str(data['last_reported_time'])) <NEW_LINE> return status, datetime.datetime.utcfromtimestamp(last_updated) | A world (or server) in the game.
.. attribute:: id
:type: int
The unique ID of the world. In the API payload, this field
is called ``world_id``.
.. attribute:: name
:type: auraxium.types.LocaleData
Localised name of the world.
.. attribute:: state
:type: str
The current state (i.e. online status) of the world.
.. attribute:: description
:type: auraxium.types.LocaleData | None
A description of the world's server region. | 62599056baa26c4b54d5080d |
class MainMenu(Level): <NEW_LINE> <INDENT> def __init__(self, player): <NEW_LINE> <INDENT> Level.__init__(self, player) <NEW_LINE> self.background = pygame.image.load("resources/main_menu.png").convert() <NEW_LINE> self.background.set_colorkey(constants.WHITE) <NEW_LINE> self.level_limit = 100 <NEW_LINE> level = [ (structures.INVISIBLE_WALL, 0, 0) ] <NEW_LINE> floors = [] <NEW_LINE> first_floor = self.make_floor(structures.GRASS_MIDDLE, -5, self.FLOOR, 1000) <NEW_LINE> floors.append(first_floor) <NEW_LINE> for floor in floors: <NEW_LINE> <INDENT> for platform in floor: <NEW_LINE> <INDENT> level.append(platform) <NEW_LINE> <DEDENT> <DEDENT> for platform in level: <NEW_LINE> <INDENT> block = structures.Platform(platform[0]) <NEW_LINE> block.rect.x = platform[1] <NEW_LINE> block.rect.y = platform[2] - 15 <NEW_LINE> block.player = self.player <NEW_LINE> self.platform_list.add(block) | Definition for Main Menu | 625990562ae34c7f260ac64f |
class ImageData(PRAWBase): <NEW_LINE> <INDENT> pass | Class for image data that's part of a :class:`.CustomWidget`.
**Typical Attributes**
This table describes attributes that typically belong to objects of this
class. Since attributes are dynamically provided (see
:ref:`determine-available-attributes-of-an-object`), there is not a
guarantee that these attributes will always be present, nor is this list
comprehensive in any way.
======================= ===================================================
Attribute Description
======================= ===================================================
``height`` The image height.
``name`` The image name.
``url`` The URL of the image on Reddit's servers.
``width`` The image width.
======================= =================================================== | 6259905632920d7e50bc75af |
class MarketingWeibo(BaseHandler): <NEW_LINE> <INDENT> product_source = PRODUCT_SOURCE.get("weibo") <NEW_LINE> product_types = PRODUCT_TYPES_WEIBO_LIKE <NEW_LINE> template = "marketing/weibo.html" <NEW_LINE> @power_check("MARKETING_WEIBO") <NEW_LINE> def get(self, *args, **kwargs): <NEW_LINE> <INDENT> where = {"source": self.product_source, "types": self.product_types} <NEW_LINE> product = Product().get_one(where=where) <NEW_LINE> self.render( self.template, product=product, commentlike="1" if product.types == PRODUCT_TYPES_WEIBO_COMMENT_LIKE else "0" ) <NEW_LINE> <DEDENT> @power_check("MARKETING_WEIBO") <NEW_LINE> def post(self, *args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> product_id = self.get_args("product_id") <NEW_LINE> if is_empty(product_id): <NEW_LINE> <INDENT> self.send_fail_json("产品id不能为空") <NEW_LINE> return <NEW_LINE> <DEDENT> product = Product().get_one8id(product_id) <NEW_LINE> weibo_url = self.get_args("weibo_url") <NEW_LINE> res = re.match(r'^https://weibo\.com/\S*', weibo_url) <NEW_LINE> if res is None: <NEW_LINE> <INDENT> self.send_fail_json("微博地址不正确") <NEW_LINE> return <NEW_LINE> <DEDENT> product_numbers = self.get_args("amount") <NEW_LINE> res = re.match(r'^\d+$', str(product_numbers)) <NEW_LINE> if res is None: <NEW_LINE> <INDENT> self.send_fail_json("数量必须为整数") <NEW_LINE> return <NEW_LINE> <DEDENT> product_numbers = int(product_numbers) * settings.PRODUCT_BUY_PRECISION <NEW_LINE> data = dict( user_id=self.user["id"], product_id=product_id, product_name=product.name, product_types=self.product_types, product_price=product.price, product_numbers=product_numbers, weibo_url=weibo_url, ) <NEW_LINE> if product.types == PRODUCT_TYPES_WEIBO_COMMENT_LIKE: <NEW_LINE> <INDENT> comment_id = self.get_args("comment_id", "") <NEW_LINE> if not comment_id: <NEW_LINE> <INDENT> self.send_fail_json("评论id不能为空") <NEW_LINE> return <NEW_LINE> <DEDENT> data.update(comment_id=comment_id) <NEW_LINE> <DEDENT> comments = self.get_args("comments") <NEW_LINE> if not is_empty(comments): <NEW_LINE> <INDENT> data.update(comments=comments) <NEW_LINE> <DEDENT> user = SysUser().get_one8id(self.user["id"]) <NEW_LINE> if (user.balance - product_numbers * product.price) < 0: <NEW_LINE> <INDENT> self.send_fail_json("创建订单失败,账户余额不足") <NEW_LINE> return <NEW_LINE> <DEDENT> res = db_engine.transaction( dbengine_transaction, func=create_orders, user=user, order_data=data) <NEW_LINE> if not res: <NEW_LINE> <INDENT> self.send_fail_json("创建订单失败") <NEW_LINE> return <NEW_LINE> <DEDENT> write_log("'{}'添加了一个订单(product_id:{},产品名为:{},数量为:{},单价为:{})".format( user["id"], product_id, product.name, product_numbers, product.price), LOG_TYPE_OPERATE) <NEW_LINE> self.send_ok_json("创建订单成功,可去\"个人中心->我的订单\"中查看") <NEW_LINE> <DEDENT> except Exception as ex: <NEW_LINE> <INDENT> write_log("{}.{} raise exception, ex={}".format( self.__class__.__name__, sys._getframe().f_code.co_name, repr(ex) )) <NEW_LINE> self.send_fail_json("系统错误,稍会儿再试") | 微博营销类 | 62599056cb5e8a47e493cc3b |
class CrapStream(io.BytesIO): <NEW_LINE> <INDENT> def __init__(self, *args, modulus=2, **kwargs): <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> self._count = 0 <NEW_LINE> self._modulus = modulus <NEW_LINE> <DEDENT> def read(self, size=-1): <NEW_LINE> <INDENT> self._count += 1 <NEW_LINE> if self._count % self._modulus == 0: <NEW_LINE> <INDENT> raise botocore.exceptions.BotoCoreError() <NEW_LINE> <DEDENT> the_bytes = super().read(size) <NEW_LINE> return the_bytes | Raises an exception on every second read call. | 62599056b7558d58954649df |
class RamException(Exception): <NEW_LINE> <INDENT> pass | Base exception class. | 6259905616aa5153ce401a4d |
class IMotionDetector(metaclass=ABCMeta): <NEW_LINE> <INDENT> @abstractmethod <NEW_LINE> def warmup(self, frames: list) -> None: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> async def findMotionBoxes(self, frame : object) -> list: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> async def findMotionBoxesSequence(self, frames : list) -> list: <NEW_LINE> <INDENT> pass | Class holding and providing functionality for a motiondetector.
Starts from either cv2.createBackgroundSubtractorKNN() or
cv2.createBackgroundSubtractorMOG().
Additional custom processing such as dilation or erosion etc
can be added as a part of the detect() method.
__init__ should contain atleast a backgroundsubtractor as an attribute,
self.backSub = cv2.createBackgroundSubtractorKNN(...). | 625990568e7ae83300eea5f7 |
class BasicSerializer: <NEW_LINE> <INDENT> REST_API_DATE_FORMAT = '%Y-%m-%dT%H:%M:%S.%f+00:00' <NEW_LINE> fields = () <NEW_LINE> datetime_fields = () <NEW_LINE> nested_fields = {} <NEW_LINE> def dump(self, model_object) -> dict: <NEW_LINE> <INDENT> if model_object is None: <NEW_LINE> <INDENT> return self._dump_nones() <NEW_LINE> <DEDENT> result = dict((name, getattr(model_object, name)) for name in self.fields) <NEW_LINE> for name in self.datetime_fields: <NEW_LINE> <INDENT> date = getattr(model_object, name) <NEW_LINE> if date is None: <NEW_LINE> <INDENT> result[name] = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[name] = date.strftime(self.REST_API_DATE_FORMAT) <NEW_LINE> <DEDENT> <DEDENT> for name, serializer in self.nested_fields.items(): <NEW_LINE> <INDENT> result[name] = serializer.dump(getattr(model_object, name)) <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def dump_many(self, items) -> list: <NEW_LINE> <INDENT> return [self.dump(item) for item in items] <NEW_LINE> <DEDENT> def _dump_nones(self) -> dict: <NEW_LINE> <INDENT> result = dict((name, None) for name in self.fields) <NEW_LINE> for name in self.datetime_fields: <NEW_LINE> <INDENT> result[name] = None <NEW_LINE> <DEDENT> for name, serializer in self.nested_fields.items(): <NEW_LINE> <INDENT> result[name] = serializer.dump(None) <NEW_LINE> <DEDENT> return result | Basic serializer for better performance than marshmallow or restful serializers
The usage not so clean/user-friendly, but this performs serialization the fastest
Example:
>>> class TestSerializer(BasicSerializer):
... fields = ('id', 'comment')
... datetime_fields = ('timestamp', )
... nested_fields = {
... 'item': ItemSerializer(),
... } | 62599056dc8b845886d54b2f |
class FileSampleInfo(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Code = None <NEW_LINE> self.CreatedAt = None <NEW_LINE> self.EvilType = None <NEW_LINE> self.FileMd5 = None <NEW_LINE> self.FileName = None <NEW_LINE> self.FileType = None <NEW_LINE> self.Id = None <NEW_LINE> self.Label = None <NEW_LINE> self.Status = None <NEW_LINE> self.CompressFileUrl = None <NEW_LINE> self.FileUrl = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.Code = params.get("Code") <NEW_LINE> self.CreatedAt = params.get("CreatedAt") <NEW_LINE> self.EvilType = params.get("EvilType") <NEW_LINE> self.FileMd5 = params.get("FileMd5") <NEW_LINE> self.FileName = params.get("FileName") <NEW_LINE> self.FileType = params.get("FileType") <NEW_LINE> self.Id = params.get("Id") <NEW_LINE> self.Label = params.get("Label") <NEW_LINE> self.Status = params.get("Status") <NEW_LINE> self.CompressFileUrl = params.get("CompressFileUrl") <NEW_LINE> self.FileUrl = params.get("FileUrl") | 文件样本返回信息
| 62599056460517430c432b06 |
class UserMixin: <NEW_LINE> <INDENT> def save_model(self, request, obj, form, change): <NEW_LINE> <INDENT> _ = form <NEW_LINE> if not change: <NEW_LINE> <INDENT> obj.created_by = request.user <NEW_LINE> <DEDENT> obj.save() | Mixin saves the current admin user into the models. | 62599056d6c5a102081e3689 |
class AttributeTable(object): <NEW_LINE> <INDENT> def __init__(self, py_class, parents): <NEW_LINE> <INDENT> self.py_class = py_class <NEW_LINE> self.parents = parents <NEW_LINE> self.attributedict = {} <NEW_LINE> self.attributes = None <NEW_LINE> self.inherited = set() <NEW_LINE> <DEDENT> def to_struct(self): <NEW_LINE> <INDENT> return numba.struct([(attr, self.attributedict[attr]) for attr in self.attributes]) <NEW_LINE> <DEDENT> def create_attribute_ordering(self, orderer=ordering.unordered): <NEW_LINE> <INDENT> self.attributes = orderer(ordering.AttributeTable(self)) <NEW_LINE> <DEDENT> def need_tp_dealloc(self): <NEW_LINE> <INDENT> if self.parent_type is not None and self.parent_type.need_tp_dealloc: <NEW_LINE> <INDENT> result = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> field_types = self.attribute_struct.fielddict.itervalues() <NEW_LINE> result = any(map(is_obj, field_types)) <NEW_LINE> <DEDENT> self._need_tp_dealloc = result <NEW_LINE> return result <NEW_LINE> <DEDENT> def strtable(self): <NEW_LINE> <INDENT> if self.attributes is None: <NEW_LINE> <INDENT> return str(self.attributedict) <NEW_LINE> <DEDENT> return "{%s}" % ", ".join("%r: %r" % (name, self.attributedict[name]) for name in self.attributes) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "AttributeTable(%s)" % self.strtable() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def empty(cls, py_class): <NEW_LINE> <INDENT> table = AttributeTable(py_class, []) <NEW_LINE> table.create_attribute_ordering() <NEW_LINE> return table <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_list(cls, py_class, attributes): <NEW_LINE> <INDENT> table = AttributeTable(py_class, []) <NEW_LINE> table.attributedict.update(attributes) <NEW_LINE> table.attributes = [name for name, type in attributes] <NEW_LINE> return table | Type for extension type attributes. | 62599056462c4b4f79dbcf6f |
class Counterdict(dict): <NEW_LINE> <INDENT> def __missing__(self, key): <NEW_LINE> <INDENT> value = self[key] = 0 <NEW_LINE> return value | dict that always have an int 0 as value on new keys | 62599056435de62698e9d36d |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.