code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
class MagicClass: <NEW_LINE> <INDENT> def __init__(self, radius=0): <NEW_LINE> <INDENT> self.__radius = 0 <NEW_LINE> if type(radius) is not int and type(radius) is not float: <NEW_LINE> <INDENT> raise TypeError('radius must be a number') <NEW_LINE> <DEDENT> self.__radius = radius <NEW_LINE> <DEDENT> def area(self): <NEW_LINE> <INDENT> return (self.__radius ** 2 * math.pi) <NEW_LINE> <DEDENT> def circumference(self): <NEW_LINE> <INDENT> return (2 * math.pi * self.__radius) | Magic Class | 6259905116aa5153ce4019ba |
class FoodProduct(Product): <NEW_LINE> <INDENT> __tablename__ = 'food_product' <NEW_LINE> id = Column(Integer, ForeignKey('product.id'), primary_key=True) <NEW_LINE> allergens = relationship('Allergen', secondary=product_allergens) <NEW_LINE> customer_id = Column(Integer, ForeignKey('customer.id')) <NEW_LINE> customer = relationship('Customer', backref='food_products') <NEW_LINE> __mapper_args__ = { 'polymorphic_identity': 'food_product' } | Food product model class. | 6259905107f4c71912bb0902 |
class MftFlagsField(BaseField): <NEW_LINE> <INDENT> @property <NEW_LINE> def value(self): <NEW_LINE> <INDENT> flag_choices = { 0x01: 'In use', 0x02: 'Directory', } <NEW_LINE> if self.raw: <NEW_LINE> <INDENT> flags = self.unpack() <NEW_LINE> try: <NEW_LINE> <INDENT> return flag_choices[flags] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return flags | Stores the MFT Flags | 6259905129b78933be26ab29 |
class TestPinotDbEngineSpec(TestDbEngineSpec): <NEW_LINE> <INDENT> def test_pinot_time_expression_sec_one_1d_grain(self): <NEW_LINE> <INDENT> col = column("tstamp") <NEW_LINE> expr = PinotEngineSpec.get_timestamp_expr(col, "epoch_s", "P1D") <NEW_LINE> result = str(expr.compile()) <NEW_LINE> self.assertEqual( result, "DATETIMECONVERT(tstamp, '1:SECONDS:EPOCH', '1:SECONDS:EPOCH', '1:DAYS')", ) <NEW_LINE> <DEDENT> def test_pinot_time_expression_simple_date_format_1d_grain(self): <NEW_LINE> <INDENT> col = column("tstamp") <NEW_LINE> expr = PinotEngineSpec.get_timestamp_expr(col, "%Y-%m-%d %H:%M:%S", "P1D") <NEW_LINE> result = str(expr.compile()) <NEW_LINE> self.assertEqual( result, ( "DATETIMECONVERT(tstamp, " + "'1:SECONDS:SIMPLE_DATE_FORMAT:yyyy-MM-dd HH:mm:ss', " + "'1:SECONDS:SIMPLE_DATE_FORMAT:yyyy-MM-dd HH:mm:ss', '1:DAYS')" ), ) <NEW_LINE> <DEDENT> def test_pinot_time_expression_simple_date_format_1w_grain(self): <NEW_LINE> <INDENT> col = column("tstamp") <NEW_LINE> expr = PinotEngineSpec.get_timestamp_expr(col, "%Y-%m-%d %H:%M:%S", "P1W") <NEW_LINE> result = str(expr.compile()) <NEW_LINE> self.assertEqual( result, ( "ToDateTime(DATETRUNC('week', FromDateTime(tstamp, " + "'yyyy-MM-dd HH:mm:ss'), 'MILLISECONDS'), 'yyyy-MM-dd HH:mm:ss')" ), ) <NEW_LINE> <DEDENT> def test_pinot_time_expression_sec_one_1m_grain(self): <NEW_LINE> <INDENT> col = column("tstamp") <NEW_LINE> expr = PinotEngineSpec.get_timestamp_expr(col, "epoch_s", "P1M") <NEW_LINE> result = str(expr.compile()) <NEW_LINE> self.assertEqual( result, "DATETRUNC('month', tstamp, 'SECONDS')", ) <NEW_LINE> <DEDENT> def test_invalid_get_time_expression_arguments(self): <NEW_LINE> <INDENT> with self.assertRaises(NotImplementedError): <NEW_LINE> <INDENT> PinotEngineSpec.get_timestamp_expr(column("tstamp"), None, "P1M") <NEW_LINE> <DEDENT> with self.assertRaises(NotImplementedError): <NEW_LINE> <INDENT> PinotEngineSpec.get_timestamp_expr( column("tstamp"), "epoch_s", "invalid_grain" ) | Tests pertaining to our Pinot database support | 6259905123e79379d538d9c4 |
class SectorAIModel(DBModelBase): <NEW_LINE> <INDENT> areaConquest = DBModelProperty(factory=SectorAIACModel) | AI strategy settings for sector
| 625990524e696a045264e887 |
class SiteRules: <NEW_LINE> <INDENT> def __init__(self, file_rules): <NEW_LINE> <INDENT> cfg = configparser.ConfigParser() <NEW_LINE> cfg.read(file_rules) <NEW_LINE> try: <NEW_LINE> <INDENT> self.source = cfg.get('main', 'source') <NEW_LINE> self.lenta = str(cfg.get('main', 'news_lenta')).split(',') <NEW_LINE> self.base_url = cfg.get('main', 'base_url') <NEW_LINE> self.news_item = cfg.get('main', 'news_item') <NEW_LINE> self.content = cfg.get('main', 'content') <NEW_LINE> self.header = cfg.get('main', 'header') <NEW_LINE> self.rss = cfg.getboolean('main', 'rss') <NEW_LINE> <DEDENT> except configparser.NoOptionError as exc: <NEW_LINE> <INDENT> raise Exception("Incorrect rule file. Exception: {}".format(exc)) | Правила парсинга новостный сайтов | 625990520fa83653e46f63ae |
class Message(MessageBased): <NEW_LINE> <INDENT> pass | A Message is a node in a Room's Log. It corresponds to a chat message,
or a post, or any broadcasted event in a room that should appear in the log. | 625990523cc13d1c6d466c08 |
class ProductProperty(models.Model): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> verbose_name_plural = _('Product Properties') <NEW_LINE> <DEDENT> PT_SINGLE_VALUE = 0 <NEW_LINE> PROPERTY_TYPES = ( (PT_SINGLE_VALUE, 'Single Value'), ) <NEW_LINE> name = models.CharField(_('name'), max_length=40) <NEW_LINE> product = models.ForeignKey(Product, related_name=_('properties')) <NEW_LINE> property_type = models.IntegerField(_('property type'), default=PT_SINGLE_VALUE, choices=PROPERTY_TYPES) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return u'%s' % self.name | Represents a product object. | 62599052d486a94d0ba2d493 |
@dataclasses.dataclass(init=True, repr=True, eq=False, order=False, unsafe_hash=False, frozen=True) <NEW_LINE> class AaveSimpleEvent(AaveEvent): <NEW_LINE> <INDENT> asset: Asset <NEW_LINE> value: Balance <NEW_LINE> def serialize(self) -> Dict[str, Any]: <NEW_LINE> <INDENT> result = super().serialize() <NEW_LINE> result['asset'] = self.asset.identifier <NEW_LINE> return result <NEW_LINE> <DEDENT> def to_db_tuple(self, address: ChecksumEthAddress) -> AAVE_EVENT_DB_TUPLE: <NEW_LINE> <INDENT> base_tuple = super().to_db_tuple(address) <NEW_LINE> return base_tuple + ( self.asset.identifier, str(self.value.amount), str(self.value.usd_value), None, None, None, None, ) | A simple event of the Aave protocol. Deposit or withdrawal | 625990520a50d4780f706824 |
class IOauthTwitterSettings(Interface): <NEW_LINE> <INDENT> client_id = schema.ASCIILine( title = _(u'client_id' , default=u'Twitter client ID'), description = _(u'help_client_id' , default=u"Alternatively, you can of course use the ID of an existing app."), required = True, ) <NEW_LINE> client_secret = schema.ASCIILine( title = _(u'client_secret' , default=u'Twitter API Secret'), description = _(u'help_client_secret' , default=u"Alternatively, you can of course use the ID of an existing app."), required = True, ) <NEW_LINE> auth_url = schema.URI( title = _(u'auth_url' , default=u'Twitter authorize url'), description = _(u'help_auth_url' , default=u""), required = True, default = 'http://localhost:8080/', ) <NEW_LINE> token_url = schema.URI( title = _(u'token_url' , default=u'Twitter access token url'), description = _(u'help_token_url' , default=u""), required = True, default = 'http://localhost:8080/', ) <NEW_LINE> profile_url = schema.URI( title = _(u'profile_url' , default=u'Twitter profile url'), description = _(u'help_profile_url' , default=u""), required = True, default = 'http://localhost:8080/', ) | OAuth Twitter registry settings | 625990528da39b475be046b6 |
class ReversedEnumerable(Enumerable): <NEW_LINE> <INDENT> def __init__(self, enumerable): <NEW_LINE> <INDENT> super(ReversedEnumerable, self).__init__(enumerable) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> stack = LifoQueue() <NEW_LINE> for element in self._iterable: <NEW_LINE> <INDENT> stack.put(element) <NEW_LINE> <DEDENT> while not stack.empty(): <NEW_LINE> <INDENT> yield stack.get() | Class to hold state for reversing elements in a collection | 6259905230dc7b76659a0ce4 |
class ArchipackActiveManip: <NEW_LINE> <INDENT> def __init__(self, object_name): <NEW_LINE> <INDENT> self.object_name = object_name <NEW_LINE> self.stack = [] <NEW_LINE> self.manipulable = None <NEW_LINE> self.datablock = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def dirty(self): <NEW_LINE> <INDENT> return ( self.manipulable is None or bpy.data.objects.find(self.object_name) < 0 ) <NEW_LINE> <DEDENT> def exit(self): <NEW_LINE> <INDENT> for m in self.stack: <NEW_LINE> <INDENT> if m is not None: <NEW_LINE> <INDENT> m.exit() <NEW_LINE> <DEDENT> <DEDENT> if self.manipulable is not None: <NEW_LINE> <INDENT> o = bpy.data.objects.get(self.object_name) <NEW_LINE> d = self.datablock(o) <NEW_LINE> if d: <NEW_LINE> <INDENT> d.manipulate_mode = False <NEW_LINE> <DEDENT> <DEDENT> self.manipulable = None <NEW_LINE> self.datablock = None <NEW_LINE> self.object_name = "" <NEW_LINE> self.stack.clear() | Store manipulated object
- object_name: manipulated object name
- stack: array of Manipulators instances
- manipulable: Manipulable instance | 62599052004d5f362081fa51 |
class Deporte(models.Model): <NEW_LINE> <INDENT> nombre = models.CharField(max_length=200) <NEW_LINE> descripcion = models.CharField(max_length=1000, blank=True, verbose_name='Descripción') <NEW_LINE> imagen = models.CharField(max_length=1000, verbose_name='Imágen', help_text='URL de la imagen del deporte') <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.nombre | Describe un deporte. | 6259905291af0d3eaad3b2f4 |
class MemberView(LoginRequiredMixin, BaseView): <NEW_LINE> <INDENT> template_name = 'member.html' <NEW_LINE> def get(self, request, token): <NEW_LINE> <INDENT> room = self.get_object_or_404(PokerRoom, token=token) <NEW_LINE> member = PokerMember.objects.filter( room=room, user=self.user, is_active=True, ).first() <NEW_LINE> context = { 'member_name': member.name if member else '', 'room': room, 'token': token, } <NEW_LINE> return self.render_to_response(context) <NEW_LINE> <DEDENT> def post(self, request, token): <NEW_LINE> <INDENT> name = request.POST.get('name') <NEW_LINE> room = self.get_object_or_404(PokerRoom, token=token) <NEW_LINE> PokerMember.objects.update_or_create( room=room, user=self.user, defaults={ 'name': name, 'is_active': True, }, ) <NEW_LINE> return self.redirect('poker:room', args=(token,)) | View for editing member data. | 62599052379a373c97d9a4f1 |
class pyTigerGraphLoading(pyTigerGraphBase): <NEW_LINE> <INDENT> def runLoadingJobWithFile(self, filePath: str, fileTag: str, jobName: str, sep: str = None, eol: str = None, timeout: int = 16000, sizeLimit: int = 128000000) -> dict: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> data = open(filePath, 'rb').read() <NEW_LINE> params = { "tag": jobName, "filename": fileTag, } <NEW_LINE> if sep is not None: <NEW_LINE> <INDENT> params["sep"] = sep <NEW_LINE> <DEDENT> if eol is not None: <NEW_LINE> <INDENT> params["eol"] = eol <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self._post(self.restppUrl + "/ddl/" + self.graphname, params=params, data=data, headers={"RESPONSE-LIMIT": str(sizeLimit), "GSQL-TIMEOUT": str(timeout)}) <NEW_LINE> <DEDENT> def uploadFile(self, filePath, fileTag, jobName="", sep=None, eol=None, timeout=16000, sizeLimit=128000000) -> dict: <NEW_LINE> <INDENT> self.runLoadingJobWithFile(filePath, fileTag, jobName, sep, eol, timeout, sizeLimit) | Loading job-specific functions. | 62599052dd821e528d6da3ab |
class NoneClientError(Exception): <NEW_LINE> <INDENT> def __init__(self, username): <NEW_LINE> <INDENT> self.username = username <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return 'Клиент с именем {} не найден'.format(self.username) | Клиент не найден. | 6259905299cbb53fe68323b5 |
class DescribeDatabasesResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.TotalCount = None <NEW_LINE> self.Items = None <NEW_LINE> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.TotalCount = params.get("TotalCount") <NEW_LINE> self.Items = params.get("Items") <NEW_LINE> self.RequestId = params.get("RequestId") | DescribeDatabases response structure.
| 62599052009cb60464d02a0a |
class RBiovizbase(RPackage): <NEW_LINE> <INDENT> homepage = "http://bioconductor.org/packages/biovizBase/" <NEW_LINE> git = "https://git.bioconductor.org/packages/biovizBase.git" <NEW_LINE> version('1.24.0', commit='ae9cd2ff665b74a8f45ed9c1d17fc0a778b4af6c') <NEW_LINE> depends_on('[email protected]:3.4.9', when='@1.24.0') <NEW_LINE> depends_on('r-scales', type=('build', 'run')) <NEW_LINE> depends_on('r-hmisc', type=('build', 'run')) <NEW_LINE> depends_on('r-rcolorbrewer', type=('build', 'run')) <NEW_LINE> depends_on('r-dichromat', type=('build', 'run')) <NEW_LINE> depends_on('r-biocgenerics', type=('build', 'run')) <NEW_LINE> depends_on('r-s4vectors', type=('build', 'run')) <NEW_LINE> depends_on('r-iranges', type=('build', 'run')) <NEW_LINE> depends_on('r-genomeinfodb', type=('build', 'run')) <NEW_LINE> depends_on('r-genomicranges', type=('build', 'run')) <NEW_LINE> depends_on('r-summarizedexperiment', type=('build', 'run')) <NEW_LINE> depends_on('r-biostrings', type=('build', 'run')) <NEW_LINE> depends_on('r-rsamtools', type=('build', 'run')) <NEW_LINE> depends_on('r-genomicalignments', type=('build', 'run')) <NEW_LINE> depends_on('r-genomicfeatures', type=('build', 'run')) <NEW_LINE> depends_on('r-annotationdbi', type=('build', 'run')) <NEW_LINE> depends_on('r-variantannotation', type=('build', 'run')) <NEW_LINE> depends_on('r-ensembldb', type=('build', 'run')) <NEW_LINE> depends_on('r-annotationfilter', type=('build', 'run')) | The biovizBase package is designed to provide a set of
utilities, color schemes and conventions for genomic data.
It serves as the base for various high-level packages for
biological data visualization. This saves development effort
and encourages consistency. | 6259905210dbd63aa1c720b1 |
class PBNBoxCollection(BoxCollection): <NEW_LINE> <INDENT> @property <NEW_LINE> def _resource_type(self): <NEW_LINE> <INDENT> return PBNBox | Represent a collection of boxen.
:param connection: A RestClient instance
:param path: The canonical path to the Box collection resource | 6259905294891a1f408ba15d |
class Test_write__valid_x_cube_attributes(tests.IrisTest): <NEW_LINE> <INDENT> def test_valid_range_saved(self): <NEW_LINE> <INDENT> cube = tests.stock.lat_lon_cube() <NEW_LINE> cube.data = cube.data.astype('int32') <NEW_LINE> vrange = np.array([1, 2], dtype='int32') <NEW_LINE> cube.attributes['valid_range'] = vrange <NEW_LINE> with self.temp_filename('.nc') as nc_path: <NEW_LINE> <INDENT> with Saver(nc_path, 'NETCDF4') as saver: <NEW_LINE> <INDENT> saver.write(cube, unlimited_dimensions=[]) <NEW_LINE> <DEDENT> ds = nc.Dataset(nc_path) <NEW_LINE> self.assertArrayEqual(ds.valid_range, vrange) <NEW_LINE> ds.close() <NEW_LINE> <DEDENT> <DEDENT> def test_valid_min_saved(self): <NEW_LINE> <INDENT> cube = tests.stock.lat_lon_cube() <NEW_LINE> cube.data = cube.data.astype('int32') <NEW_LINE> cube.attributes['valid_min'] = 1 <NEW_LINE> with self.temp_filename('.nc') as nc_path: <NEW_LINE> <INDENT> with Saver(nc_path, 'NETCDF4') as saver: <NEW_LINE> <INDENT> saver.write(cube, unlimited_dimensions=[]) <NEW_LINE> <DEDENT> ds = nc.Dataset(nc_path) <NEW_LINE> self.assertArrayEqual(ds.valid_min, 1) <NEW_LINE> ds.close() <NEW_LINE> <DEDENT> <DEDENT> def test_valid_max_saved(self): <NEW_LINE> <INDENT> cube = tests.stock.lat_lon_cube() <NEW_LINE> cube.data = cube.data.astype('int32') <NEW_LINE> cube.attributes['valid_max'] = 2 <NEW_LINE> with self.temp_filename('.nc') as nc_path: <NEW_LINE> <INDENT> with Saver(nc_path, 'NETCDF4') as saver: <NEW_LINE> <INDENT> saver.write(cube, unlimited_dimensions=[]) <NEW_LINE> <DEDENT> ds = nc.Dataset(nc_path) <NEW_LINE> self.assertArrayEqual(ds.valid_max, 2) <NEW_LINE> ds.close() | Testing valid_range, valid_min and valid_max attributes. | 62599052b7558d5895464990 |
class EdfGenerator(gen.Generator): <NEW_LINE> <INDENT> def __init__(self, scheduler, templates, options, params): <NEW_LINE> <INDENT> super(EdfGenerator, self).__init__(scheduler, templates, self.__make_options() + options, params) <NEW_LINE> <DEDENT> def __make_options(self): <NEW_LINE> <INDENT> return [gen.Generator._dist_option('utils', 'uni-medium', gen.NAMED_UTILIZATIONS, 'Task utilization distributions.'), gen.Generator._dist_option('periods', 'harmonic', gen.NAMED_PERIODS, 'Task period distributions.')] <NEW_LINE> <DEDENT> def _create_exp(self, exp_params): <NEW_LINE> <INDENT> pdist = self._create_dist('period', exp_params['periods'], gen.NAMED_PERIODS) <NEW_LINE> udist = self._create_dist('utilization', exp_params['utils'], gen.NAMED_UTILIZATIONS) <NEW_LINE> ts = self._create_taskset(exp_params, pdist, udist) <NEW_LINE> self._customize(ts, exp_params) <NEW_LINE> self._write_schedule(dict(exp_params.items() + [('task_set', ts)])) <NEW_LINE> self._write_params(exp_params) <NEW_LINE> <DEDENT> def _customize(self, taskset, exp_params): <NEW_LINE> <INDENT> pass | Creates sporadic task sets with the most common Litmus options. | 6259905230c21e258be99cd6 |
class GuiBoundingRectGetter(qg.QGraphicsRectItem): <NEW_LINE> <INDENT> def __init__(self, scene, signal): <NEW_LINE> <INDENT> super(GuiBoundingRectGetter, self).__init__(0, 0, VID_DIM[1], VID_DIM[0], scene=scene) <NEW_LINE> self.setPen(qClear) <NEW_LINE> self.setBrush(qClear) <NEW_LINE> self.setZValue(2) <NEW_LINE> self.signal = signal <NEW_LINE> self.bounding_coords = [] <NEW_LINE> <DEDENT> def mousePressEvent(self, e): <NEW_LINE> <INDENT> if len(self.bounding_coords) < 2: <NEW_LINE> <INDENT> self.bounding_coords.append((e.pos().x(), e.pos().y())) <NEW_LINE> <DEDENT> if len(self.bounding_coords) == 2: <NEW_LINE> <INDENT> x1, y1 = self.bounding_coords[0] <NEW_LINE> x2, y2 = self.bounding_coords[1] <NEW_LINE> x1, x2 = min((x1, x2)), max((x1, x2)) <NEW_LINE> y1, y2 = min((y1, y2)), max((y1, y2)) <NEW_LINE> self.bounding_coords = [(int(x1), int(y1)), (int(x2), int(y2))] <NEW_LINE> self.signal.emit(self.bounding_coords) <NEW_LINE> self.bounding_coords = [] | Finds and returns user defined bounding coords | 62599052498bea3a75a58ff3 |
class Sheet(Component): <NEW_LINE> <INDENT> def __init__(self,id=Id()): <NEW_LINE> <INDENT> Component.__init__(self,id=id) | Defines a schematic sheet.
A sheet is a collection of components representing a schematic meant to be
encapsulated into one unit.
A sheet has two renderings, internal and external. The internal rendering
shows the components the sheet is made up of. The external rendering
presents the sheet as a box with named ports.
A sheet is a component as well, and therefore may have pins that can be connected. | 6259905223849d37ff852591 |
class OFFLOAD_STATUS4res(BaseObj): <NEW_LINE> <INDENT> _strfmt1 = "{1}" <NEW_LINE> def __init__(self, unpack): <NEW_LINE> <INDENT> self.set_attr("status", nfsstat4(unpack)) <NEW_LINE> if self.status == const.NFS4_OK: <NEW_LINE> <INDENT> self.set_attr("resok", OFFLOAD_STATUS4resok(unpack), switch=True) | union switch OFFLOAD_STATUS4res (nfsstat4 status) {
case const.NFS4_OK:
OFFLOAD_STATUS4resok resok;
default:
void;
}; | 625990523cc13d1c6d466c0b |
class KeyAttribute(parsing.Nonterm): <NEW_LINE> <INDENT> def reducePlain(self, element): <NEW_LINE> <INDENT> self.element = element.value <NEW_LINE> <DEDENT> def __repr__( self ): <NEW_LINE> <INDENT> return repr(self.element) | %nonterm | 62599052e64d504609df9e37 |
class V1PodTemplate(object): <NEW_LINE> <INDENT> operations = [ { 'class': 'ApiV1', 'type': 'create', 'method': 'create_podtemplate', 'namespaced': False }, { 'class': 'ApiV1', 'type': 'update', 'method': 'replace_namespaced_podtemplate', 'namespaced': True }, { 'class': 'ApiV1', 'type': 'delete', 'method': 'delete_namespaced_podtemplate', 'namespaced': True }, { 'class': 'ApiV1', 'type': 'read', 'method': 'get_namespaced_podtemplate', 'namespaced': True }, { 'class': 'ApiV1', 'type': 'create', 'method': 'create_namespaced_podtemplate', 'namespaced': True }, ] <NEW_LINE> swagger_types = { 'kind': 'str', 'api_version': 'str', 'metadata': 'V1ObjectMeta', 'template': 'V1PodTemplateSpec' } <NEW_LINE> attribute_map = { 'kind': 'kind', 'api_version': 'apiVersion', 'metadata': 'metadata', 'template': 'template' } <NEW_LINE> def __init__(self, kind=None, api_version=None, metadata=None, template=None): <NEW_LINE> <INDENT> self._kind = kind <NEW_LINE> self._api_version = api_version <NEW_LINE> self._metadata = metadata <NEW_LINE> self._template = template <NEW_LINE> <DEDENT> @property <NEW_LINE> def kind(self): <NEW_LINE> <INDENT> return self._kind <NEW_LINE> <DEDENT> @kind.setter <NEW_LINE> def kind(self, kind): <NEW_LINE> <INDENT> self._kind = kind <NEW_LINE> <DEDENT> @property <NEW_LINE> def api_version(self): <NEW_LINE> <INDENT> return self._api_version <NEW_LINE> <DEDENT> @api_version.setter <NEW_LINE> def api_version(self, api_version): <NEW_LINE> <INDENT> self._api_version = api_version <NEW_LINE> <DEDENT> @property <NEW_LINE> def metadata(self): <NEW_LINE> <INDENT> return self._metadata <NEW_LINE> <DEDENT> @metadata.setter <NEW_LINE> def metadata(self, metadata): <NEW_LINE> <INDENT> self._metadata = metadata <NEW_LINE> <DEDENT> @property <NEW_LINE> def template(self): <NEW_LINE> <INDENT> return self._template <NEW_LINE> <DEDENT> @template.setter <NEW_LINE> def template(self, template): <NEW_LINE> <INDENT> self._template = template <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in iteritems(V1PodTemplate.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> 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. | 62599052b830903b9686eee4 |
class NoLicenseAvailableForTask(BaseException): <NEW_LINE> <INDENT> pass | Raised to interrupt the dispatch iteration on an entry point node. | 62599052dc8b845886d54a91 |
class Lagrangian: <NEW_LINE> <INDENT> def __init__(self,json_dict): <NEW_LINE> <INDENT> self.Vi = InputFields() <NEW_LINE> self.Vi.get_info(json_dict['velocity']) <NEW_LINE> self.Vi.get_mfds() <NEW_LINE> self.Vi.get_grid() <NEW_LINE> self.Vi.get_interpolants() <NEW_LINE> self.boundaries = [] <NEW_LINE> <DEDENT> def F(self, r, t): <NEW_LINE> <INDENT> if self.boundaries: <NEW_LINE> <INDENT> r = self.boundaries.F(r) <NEW_LINE> <DEDENT> return self.Vi.F(r, t) | This class provides pure Lagrangian kernels.
The particle just follows the local velocity flow field.
Attributes:
-Vi (function): The interpolant function, to evaluate the
local flow velocity field V(r(t),t). | 62599052097d151d1a2c2544 |
class TextInput(Input): <NEW_LINE> <INDENT> input_type = 'text' | Render a single-line text input. | 62599052d99f1b3c44d06b6e |
class Changeish(object): <NEW_LINE> <INDENT> is_reportable = False <NEW_LINE> def __init__(self, project): <NEW_LINE> <INDENT> self.project = project <NEW_LINE> self.build_sets = [] <NEW_LINE> self.dequeued_needing_change = False <NEW_LINE> self.current_build_set = BuildSet(self) <NEW_LINE> self.build_sets.append(self.current_build_set) <NEW_LINE> self.change_ahead = None <NEW_LINE> self.change_behind = None <NEW_LINE> self.enqueue_time = None <NEW_LINE> self.dequeue_time = None <NEW_LINE> <DEDENT> def equals(self, other): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def isUpdateOf(self, other): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def filterJobs(self, jobs): <NEW_LINE> <INDENT> return filter(lambda job: job.changeMatches(self), jobs) <NEW_LINE> <DEDENT> def resetAllBuilds(self): <NEW_LINE> <INDENT> old = self.current_build_set <NEW_LINE> self.current_build_set.result = 'CANCELED' <NEW_LINE> self.current_build_set = BuildSet(self) <NEW_LINE> old.next_build_set = self.current_build_set <NEW_LINE> self.current_build_set.previous_build_set = old <NEW_LINE> self.build_sets.append(self.current_build_set) <NEW_LINE> <DEDENT> def addBuild(self, build): <NEW_LINE> <INDENT> self.current_build_set.addBuild(build) | Something like a change; either a change or a ref | 62599052f7d966606f74931f |
class pltfm_mgr_pwr_supply_present_get_result(object): <NEW_LINE> <INDENT> thrift_spec = ( (0, TType.BOOL, 'success', None, None, ), (1, TType.STRUCT, 'ouch', (InvalidPltfmMgrOperation, InvalidPltfmMgrOperation.thrift_spec), None, ), ) <NEW_LINE> def __init__(self, success=None, ouch=None,): <NEW_LINE> <INDENT> self.success = success <NEW_LINE> self.ouch = ouch <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: <NEW_LINE> <INDENT> iprot._fast_decode(self, iprot, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 0: <NEW_LINE> <INDENT> if ftype == TType.BOOL: <NEW_LINE> <INDENT> self.success = iprot.readBool() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.ouch = InvalidPltfmMgrOperation() <NEW_LINE> self.ouch.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot._fast_encode is not None and self.thrift_spec is not None: <NEW_LINE> <INDENT> oprot.trans.write(oprot._fast_encode(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('pltfm_mgr_pwr_supply_present_get_result') <NEW_LINE> if self.success is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('success', TType.BOOL, 0) <NEW_LINE> oprot.writeBool(self.success) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.ouch is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('ouch', TType.STRUCT, 1) <NEW_LINE> self.ouch.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in list(self.__dict__.items())] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) | Attributes:
- success
- ouch | 62599052d7e4931a7ef3d54d |
class SubPixels: <NEW_LINE> <INDENT> block_width: int <NEW_LINE> block_height: int <NEW_LINE> bit_size: int = 0b1111 <NEW_LINE> def __init_subclass__(cls): <NEW_LINE> <INDENT> cls.chars_by_name = chars_by_name = { key: value for key, value in cls.__dict__.items() if key.isupper() } <NEW_LINE> cls.chars_to_name = mirror_dict(chars_by_name) <NEW_LINE> cls.chars_in_order = { i: value for i, value in enumerate(chars_by_name.values()) } <NEW_LINE> cls.chars_to_order = mirror_dict(cls.chars_in_order) <NEW_LINE> cls.chars = set(chars_by_name.values()) <NEW_LINE> <DEDENT> def __contains__(self, char): <NEW_LINE> <INDENT> return char in self.chars <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _op(cls, pos, data, operation): <NEW_LINE> <INDENT> number = cls.chars_to_order[data] <NEW_LINE> index = 2 ** (pos[0] + cls.block_width * pos[1]) <NEW_LINE> return operation(number, index) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def set(cls, pos, data): <NEW_LINE> <INDENT> op = lambda n, index: n | index <NEW_LINE> return cls.chars_in_order[cls._op(pos, data, op)] <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def reset(cls, pos, data): <NEW_LINE> <INDENT> op = lambda n, index: n & (cls.bit_size - index) <NEW_LINE> return cls.chars_in_order[cls._op(pos, data, op)] <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_at(cls, pos, data): <NEW_LINE> <INDENT> op = lambda n, index: bool(n & index) <NEW_LINE> return cls._op(pos, data, op) | Used internally to emulate pixel setting/resetting/reading inside unicode block characters
Requires that the subclasses contain a listing and other mappings
of all block characters to be used in order, so that
bits in numbers from 0 to `bit_size` will match the "pixels" on the corresponding block character.
Although this class is purposed for internal use in the emulation of
a higher resolution canvas, its functions can be used by any application
that decides to manipulate block chars.
The class itself is stateless, and any subclass can be used as a single-instance.
The instance is needed so that one can use the operator
``in`` to check if a character is a block-character in that resolution.
(originally this code was in the BlockChars class - and was refactored
to include the other sub-block pixel resolutions. This class is used as base,
and depends mostly of declaring the pixel-representing characters in order
in the subclass.) | 6259905229b78933be26ab2c |
class TCPCommunicator(Communicator): <NEW_LINE> <INDENT> def __init__(self, host='', port=9637): <NEW_LINE> <INDENT> super(TCPCommunicator, self).__init__() <NEW_LINE> self.host = host <NEW_LINE> self.port = port <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> logger.info('TCPCommunicator started') <NEW_LINE> sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) <NEW_LINE> sock.bind((self.host, self.port)) <NEW_LINE> sock.listen(5) <NEW_LINE> sock.settimeout(0.5) <NEW_LINE> while not self._stop_flag.is_set(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> (client, addr) = sock.accept() <NEW_LINE> <DEDENT> except socket.timeout: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> logger.debug('Client connected') <NEW_LINE> client.settimeout(0.5) <NEW_LINE> while True and not self._stop_flag.is_set(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> d = client.recv(2048) <NEW_LINE> <DEDENT> except socket.timeout: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if not d: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> self._buffer.extend(bytearray(d)) <NEW_LINE> <DEDENT> self.parse() <NEW_LINE> client.close() <NEW_LINE> logger.debug('Client disconnected') <NEW_LINE> <DEDENT> sock.close() <NEW_LINE> logger.info('TCPCommunicator stopped') | Socket communicator class for EnOcean radio | 62599052d6c5a102081e35ec |
class Block(pygame.sprite.Sprite): <NEW_LINE> <INDENT> def __init__(self, color, x, y): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.image = pygame.Surface([block_width, block_height]) <NEW_LINE> self.image.fill(color) <NEW_LINE> self.rect = self.image.get_rect() <NEW_LINE> self.rect.x = x <NEW_LINE> self.rect.y = y | This class represents each block that will get knocked out by the ball
It derives from the "Sprite" class in Pygame | 6259905245492302aabfd9a8 |
class Audit(BaseAction): <NEW_LINE> <INDENT> @tornado.web.authenticated <NEW_LINE> def get(self): <NEW_LINE> <INDENT> if not self.accessAdmin(): <NEW_LINE> <INDENT> self.write("Permission Denied.") <NEW_LINE> return <NEW_LINE> <DEDENT> x = {'a':self.get_argument('a',''), 'p':self.get_argument('p',0), 'psz':self.get_argument('psz',50)} <NEW_LINE> if x['a']=='del': <NEW_LINE> <INDENT> model.del_audit_log() <NEW_LINE> <DEDENT> pg = int(x['p']) <NEW_LINE> pgcon = int(x['psz']) <NEW_LINE> pages = 1+ int(model.get_audit_log_counts()/pgcon) <NEW_LINE> items = model.get_audit_log(pg, pgcon) <NEW_LINE> self.render("publish_audit.html", items=items, pages=pages, ptitle="管理审计日志", strtime=utils.strtime) | 管理审计日志 | 6259905276d4e153a661dce2 |
class Endpoint(object): <NEW_LINE> <INDENT> __version = '0.0.1' <NEW_LINE> def __init__(self, endpoint_url, client_id = None, client_secret = None): <NEW_LINE> <INDENT> if client_id is None: <NEW_LINE> <INDENT> client_id = str(keyring.get_password('Addigy', 'ClientID')) <NEW_LINE> <DEDENT> if client_secret is None: <NEW_LINE> <INDENT> client_secret = str(keyring.get_password('Addigy', 'ClientSecret')) <NEW_LINE> <DEDENT> self.base_url = "https://prod.addigy.com/" <NEW_LINE> self.url = str(self.base_url + endpoint_url) <NEW_LINE> self.headers = { 'client-id': client_id, 'client-secret': client_secret, } <NEW_LINE> <DEDENT> def get(self, params = None, files = None): <NEW_LINE> <INDENT> response = requests.get(self.url, params = params, headers = self.headers) <NEW_LINE> return json.loads(response.text) <NEW_LINE> <DEDENT> def post(self, data = None, json_data = None): <NEW_LINE> <INDENT> response = requests.post(self.url, headers = self.headers, data = data, json = json_data) <NEW_LINE> return json.loads(response.text) <NEW_LINE> <DEDENT> def put(self): <NEW_LINE> <INDENT> response = requests.put(self.url, headers = self.headers, data = data) <NEW_LINE> return json.loads(response.text) <NEW_LINE> <DEDENT> def delete(self, json_data = None): <NEW_LINE> <INDENT> response = requests.delete(self.url, headers = self.headers, json = json_data) <NEW_LINE> return json.loads(response.text) | Use GET, POST, PUT, and DELETE methods with Addigy endpoints.
<Subclass>.__init__ pass endpoint_url to Endpoint.__init__, and subclass
methods pass params, json, etc. | 625990523617ad0b5ee07615 |
class FiniteJoinSemilattice(FinitePoset): <NEW_LINE> <INDENT> Element = JoinSemilatticeElement <NEW_LINE> def _repr_(self): <NEW_LINE> <INDENT> s = "Finite join-semilattice containing %s elements"%self._hasse_diagram.order() <NEW_LINE> if self._with_linear_extension: <NEW_LINE> <INDENT> s += " with distinguished linear extension" <NEW_LINE> <DEDENT> return s <NEW_LINE> <DEDENT> def join_matrix(self): <NEW_LINE> <INDENT> return self._hasse_diagram.join_matrix() <NEW_LINE> <DEDENT> def join(self, x, y=None): <NEW_LINE> <INDENT> if y is not None: <NEW_LINE> <INDENT> i, j = map(self._element_to_vertex, (x,y)) <NEW_LINE> return self._vertex_to_element(self._hasse_diagram._join[i,j]) <NEW_LINE> <DEDENT> j = 0 <NEW_LINE> for i in (self._element_to_vertex(_) for _ in x): <NEW_LINE> <INDENT> j = self._hasse_diagram._join[i, j] <NEW_LINE> <DEDENT> return self._vertex_to_element(j) | We assume that the argument passed to FiniteJoinSemilattice is the
poset of a join-semilattice (i.e. a poset with least upper bound
for each pair of elements).
TESTS::
sage: J = JoinSemilattice([[1,2],[3],[3]])
sage: TestSuite(J).run()
::
sage: P = Poset([[1,2],[3],[3]])
sage: J = JoinSemilattice(P)
sage: TestSuite(J).run() | 6259905207d97122c4218179 |
class aMSNSplashScreen(base.aMSNSplashScreen): <NEW_LINE> <INDENT> def __init__(self, amsn_core, parent): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def show(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def hide(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def set_text(self, text): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def set_image(self, image): <NEW_LINE> <INDENT> pass | This is the splashscreen for ncurses | 625990526e29344779b01b18 |
class ConfigParser: <NEW_LINE> <INDENT> config = {} <NEW_LINE> @staticmethod <NEW_LINE> def parse_config(filename): <NEW_LINE> <INDENT> filename = os.path.normpath(os.path.expanduser(filename)) <NEW_LINE> with open(filename) as config_file: <NEW_LINE> <INDENT> config_dict = yaml.load(config_file) <NEW_LINE> <DEDENT> ConfigParser.import_python_classes(config_dict) <NEW_LINE> ConfigParser.config = config_dict <NEW_LINE> return config_dict <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def import_python_classes(obj): <NEW_LINE> <INDENT> if isinstance(obj, dict): <NEW_LINE> <INDENT> if key_contains("module", obj) and key_contains("class", obj): <NEW_LINE> <INDENT> module_key = get_full_key("module", obj) <NEW_LINE> class_key = get_full_key("class", obj) <NEW_LINE> obj[module_key] = importlib.import_module(obj[module_key]) <NEW_LINE> obj[class_key] = getattr(obj[module_key], obj[class_key]) <NEW_LINE> obj.pop(module_key) <NEW_LINE> <DEDENT> if 'import' in obj and 'class' in obj: <NEW_LINE> <INDENT> spec = importlib.util.spec_from_file_location(obj['class'], obj['import']) <NEW_LINE> obj['import'] = importlib.util.module_from_spec(spec) <NEW_LINE> spec.loader.exec_module(obj['import']) <NEW_LINE> obj['class'] = getattr(obj['import'], obj['class']) <NEW_LINE> if 'function' in obj: <NEW_LINE> <INDENT> obj['function'] = getattr(obj['class'], obj['function']) <NEW_LINE> <DEDENT> <DEDENT> for key, value in obj.items(): <NEW_LINE> <INDENT> if key != 'module' and key != 'class': <NEW_LINE> <INDENT> ConfigParser.import_python_classes(value) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if isinstance(obj, list): <NEW_LINE> <INDENT> for item in obj: <NEW_LINE> <INDENT> ConfigParser.import_python_classes(item) | Wrapper class for the config.
Before first use call parse_config_file
or you will get an empty config object | 625990523cc13d1c6d466c0d |
class ConsumerListCommand(PulpCliCommand): <NEW_LINE> <INDENT> _ALL_FIELDS = ['id', 'display_name', 'description', 'bindings', 'notes'] <NEW_LINE> def __init__(self, context, name=None, description=None): <NEW_LINE> <INDENT> name = name or 'list' <NEW_LINE> description = description or _('lists a summary of consumers registered to the Pulp server') <NEW_LINE> super(ConsumerListCommand, self).__init__(name, description, self.run) <NEW_LINE> self.add_option(OPTION_FIELDS) <NEW_LINE> self.add_flag(FLAG_BINDINGS) <NEW_LINE> self.add_flag(FLAG_DETAILS) <NEW_LINE> self.context = context <NEW_LINE> self.api = context.server.consumer <NEW_LINE> <DEDENT> def run(self, **kwargs): <NEW_LINE> <INDENT> details = kwargs.get(FLAG_DETAILS.keyword, False) <NEW_LINE> consumer_list = self.get_consumer_list(kwargs) <NEW_LINE> filters = order = self._ALL_FIELDS <NEW_LINE> if details: <NEW_LINE> <INDENT> order = self._ALL_FIELDS[:2] <NEW_LINE> filters = None <NEW_LINE> <DEDENT> elif kwargs[OPTION_FIELDS.keyword]: <NEW_LINE> <INDENT> filters = kwargs[OPTION_FIELDS.keyword].split(',') <NEW_LINE> if 'bindings' not in filters: <NEW_LINE> <INDENT> filters.append('bindings') <NEW_LINE> <DEDENT> if 'id' not in filters: <NEW_LINE> <INDENT> filters.insert(0, 'id') <NEW_LINE> <DEDENT> <DEDENT> self.context.prompt.render_title(self.get_title()) <NEW_LINE> for consumer in consumer_list: <NEW_LINE> <INDENT> self.format_bindings(consumer) <NEW_LINE> self.context.prompt.render_document(consumer, filters=filters, order=order) <NEW_LINE> <DEDENT> <DEDENT> def get_consumer_list(self, kwargs): <NEW_LINE> <INDENT> details = kwargs.get(FLAG_DETAILS.keyword, False) <NEW_LINE> bindings = kwargs.get(FLAG_BINDINGS.keyword, False) <NEW_LINE> response = self.api.consumers(details=details, bindings=bindings) <NEW_LINE> return response.response_body <NEW_LINE> <DEDENT> def get_title(self): <NEW_LINE> <INDENT> return _('Consumers') <NEW_LINE> <DEDENT> def format_bindings(self, consumer): <NEW_LINE> <INDENT> bindings = consumer.get('bindings') <NEW_LINE> if not bindings: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> confirmed = set() <NEW_LINE> unconfirmed = set() <NEW_LINE> for binding in bindings: <NEW_LINE> <INDENT> repo_id = binding['repo_id'] <NEW_LINE> if binding['deleted'] or len(binding['consumer_actions']): <NEW_LINE> <INDENT> unconfirmed.add(repo_id) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> confirmed.add(repo_id) <NEW_LINE> <DEDENT> <DEDENT> consumer['bindings'] = {'confirmed': list(confirmed), 'unconfirmed': list(unconfirmed)} | List the consumers that are currently registered with the Pulp server. | 62599052d486a94d0ba2d498 |
class Attribute(object): <NEW_LINE> <INDENT> __slots__ = ( "name", "default", "validator", "repr", "cmp", "hash", "init", "metadata", "type", "converter", ) <NEW_LINE> def __init__( self, name, default, validator, repr, cmp, hash, init, convert=None, metadata=None, type=None, converter=None, ): <NEW_LINE> <INDENT> bound_setattr = _obj_setattr.__get__(self, Attribute) <NEW_LINE> if convert is not None: <NEW_LINE> <INDENT> if converter is not None: <NEW_LINE> <INDENT> raise RuntimeError( "Can't pass both `convert` and `converter`. " "Please use `converter` only." ) <NEW_LINE> <DEDENT> warnings.warn( "The `convert` argument is deprecated in favor of `converter`." " It will be removed after 2019/01.", DeprecationWarning, stacklevel=2, ) <NEW_LINE> converter = convert <NEW_LINE> <DEDENT> bound_setattr("name", name) <NEW_LINE> bound_setattr("default", default) <NEW_LINE> bound_setattr("validator", validator) <NEW_LINE> bound_setattr("repr", repr) <NEW_LINE> bound_setattr("cmp", cmp) <NEW_LINE> bound_setattr("hash", hash) <NEW_LINE> bound_setattr("init", init) <NEW_LINE> bound_setattr("converter", converter) <NEW_LINE> bound_setattr( "metadata", ( metadata_proxy(metadata) if metadata else _empty_metadata_singleton ), ) <NEW_LINE> bound_setattr("type", type) <NEW_LINE> <DEDENT> def __setattr__(self, name, value): <NEW_LINE> <INDENT> raise FrozenInstanceError() <NEW_LINE> <DEDENT> @property <NEW_LINE> def convert(self): <NEW_LINE> <INDENT> warnings.warn( "The `convert` attribute is deprecated in favor of `converter`. " "It will be removed after 2019/01.", DeprecationWarning, stacklevel=2, ) <NEW_LINE> return self.converter <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_counting_attr(cls, name, ca, type=None): <NEW_LINE> <INDENT> if type is None: <NEW_LINE> <INDENT> type = ca.type <NEW_LINE> <DEDENT> elif ca.type is not None: <NEW_LINE> <INDENT> raise ValueError( "Type annotation and type argument cannot both be present" ) <NEW_LINE> <DEDENT> inst_dict = { k: getattr(ca, k) for k in Attribute.__slots__ if k not in ( "name", "validator", "default", "type", "convert", ) } <NEW_LINE> return cls( name=name, validator=ca._validator, default=ca._default, type=type, **inst_dict ) <NEW_LINE> <DEDENT> def __getstate__(self): <NEW_LINE> <INDENT> return tuple( getattr(self, name) if name != "metadata" else dict(self.metadata) for name in self.__slots__ ) <NEW_LINE> <DEDENT> def __setstate__(self, state): <NEW_LINE> <INDENT> bound_setattr = _obj_setattr.__get__(self, Attribute) <NEW_LINE> for name, value in zip(self.__slots__, state): <NEW_LINE> <INDENT> if name != "metadata": <NEW_LINE> <INDENT> bound_setattr(name, value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> bound_setattr( name, metadata_proxy(value) if value else _empty_metadata_singleton, ) | *Read-only* representation of an attribute.
:attribute name: The name of the attribute.
Plus *all* arguments of :func:`attr.ib`.
For the version history of the fields, see :func:`attr.ib`. | 62599052e5267d203ee6cdbe |
class MathEffect(Effect): <NEW_LINE> <INDENT> def __init__(self, noise=0.15, fill=(0,0,0,0)): <NEW_LINE> <INDENT> self.fill = rgba(fill) <NEW_LINE> self.above = noise > 0 <NEW_LINE> self.noise = abs(noise) <NEW_LINE> <DEDENT> def eqn(self, x, n, size): <NEW_LINE> <INDENT> dh = self.noise <NEW_LINE> if not self.above: n = 1 - n <NEW_LINE> return size[1] * ((1 + dh) * n - uniform(0, dh)), self.above <NEW_LINE> <DEDENT> def apply(self, img, n=0): <NEW_LINE> <INDENT> if n >= 1: return img <NEW_LINE> srf, size = self.srfSize(img, True) <NEW_LINE> h = size[1] <NEW_LINE> pxa = PixelArray(srf) <NEW_LINE> x = 0 <NEW_LINE> for pxCol in pxa: <NEW_LINE> <INDENT> y = self.eqn(x, n, size) <NEW_LINE> if type(y) is tuple: y, above = y <NEW_LINE> else: above = True <NEW_LINE> if type(y) is float: y = int(y) <NEW_LINE> if above: <NEW_LINE> <INDENT> if y < h - 1: <NEW_LINE> <INDENT> if y < 0: y = 0 <NEW_LINE> pxCol[y:] = self.fill <NEW_LINE> <DEDENT> <DEDENT> elif y > 0: <NEW_LINE> <INDENT> if y > h: y = h <NEW_LINE> pxCol[:y] = self.fill <NEW_LINE> <DEDENT> x += 1 <NEW_LINE> <DEDENT> return srf | Effect based on y < f(x) or y > f(x) | 625990524e696a045264e88a |
class PhoneVerificationForm(Form): <NEW_LINE> <INDENT> verification_code = TextField('Verification code', [Required(),]) | A basic verification form to take in the user's verification code
attempt. | 62599052a8ecb033258726e7 |
class CLHEP2042( Clhep.Clhep ): <NEW_LINE> <INDENT> def __init__( self ): <NEW_LINE> <INDENT> super( CLHEP2042, self ).__init__( "clhep-2.0.4.2", "clhep-2.0.4.2.tgz" ) <NEW_LINE> return | Clhep 2.0.4.2, install package. | 62599052cad5886f8bdc5ae9 |
class Solution(object): <NEW_LINE> <INDENT> def firstBadVersion(self, n): <NEW_LINE> <INDENT> class Wrap: <NEW_LINE> <INDENT> def __getitem__(self, i): <NEW_LINE> <INDENT> return isBadVersion(i) <NEW_LINE> <DEDENT> <DEDENT> return bisect.bisect(Wrap(), False, 0, n) | 用python 的库bisect来实现,指定0-n这样的list区间,然后对每个数进行isBadVersion(i)判断
这里用到了__getitem__(self, i)的魔法方法,使得区间的每个数可以用索引访问,当为false时返回结果
Runtime: 12 ms, faster than 93.14% of Python online submissions for First Bad Version.
Memory Usage: 11.8 MB, less than 44.40% of Python online submissions for First Bad Version. | 62599052379a373c97d9a4f6 |
class HRInsuranceModel(S3Model): <NEW_LINE> <INDENT> names = ("hrm_insurance", ) <NEW_LINE> def model(self): <NEW_LINE> <INDENT> T = current.T <NEW_LINE> insurance_types = {"SOCIAL": T("Social Insurance"), "HEALTH": T("Health Insurance"), } <NEW_LINE> insurance_type_represent = S3Represent(options = insurance_types) <NEW_LINE> tablename = "hrm_insurance" <NEW_LINE> self.define_table(tablename, self.hrm_human_resource_id(), Field("type", label = T("Type"), represent = insurance_type_represent, requires = IS_IN_SET(insurance_types), ), Field("insurance_number", length = 128, label = T("Insurance Number"), requires = IS_LENGTH(128), ), Field("insurer", length = 255, label = T("Insurer"), requires = IS_LENGTH(255), ), Field("provider", length = 255, label = T("Provider"), requires = IS_LENGTH(255), ), Field("phone", label = T("Emergency Number"), requires = IS_EMPTY_OR( IS_PHONE_NUMBER_MULTI(), ), ), s3_comments(), *s3_meta_fields()) <NEW_LINE> self.configure(tablename, deduplicate = S3Duplicate(primary = ("human_resource_id", "type", ), ), ) <NEW_LINE> return {} | Data Model to track insurance information of staff members | 6259905276d4e153a661dce3 |
class TextureCubeMap(Texture): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> Texture.__init__(self, gl.GL_TEXTURE_CUBE_MAP, *args, **kwargs) | Representation of a cube map, to store texture data for the
6 sided of a cube. Used for instance to create environment mappings.
Inherits :class:`texture.Texture`.
This class is not yet implemented. | 625990528e71fb1e983bcf9b |
class PokemonWikiDownloader(object): <NEW_LINE> <INDENT> def __init__(self, wiki_downloader: WikiDownloader): <NEW_LINE> <INDENT> self.wiki_downloader = wiki_downloader <NEW_LINE> <DEDENT> def download_pokemon(self, pokemon: str): <NEW_LINE> <INDENT> self.wiki_downloader.download(pokemon + '_(Pokémon)') | Downloads Pokemon Wikimedia file. | 6259905230dc7b76659a0ce7 |
class GeoprocessingApiUserRateThrottle(UserRateThrottle): <NEW_LINE> <INDENT> def allow_request(self, request, view): <NEW_LINE> <INDENT> if request.user and request.user.username == settings.CLIENT_APP_USERNAME: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return UserRateThrottle.allow_request(self, request, view) | Only throttle "real" users of the API, not the client app | 625990524e4d5625663738d9 |
class PersonalInfo(Model): <NEW_LINE> <INDENT> __table__ = 'resume_personalinfo' <NEW_LINE> @staticmethod <NEW_LINE> def get_my_profile(): <NEW_LINE> <INDENT> personal_info = PersonalInfo.find(1) <NEW_LINE> if personal_info: <NEW_LINE> <INDENT> return personal_info | PersonalInfo Model. | 625990523c8af77a43b689a8 |
class MathJax: <NEW_LINE> <INDENT> def __call__(self, x, combine_all=False): <NEW_LINE> <INDENT> return self.eval(x, combine_all=combine_all) <NEW_LINE> <DEDENT> def eval(self, x, globals=None, locals=None, mode='display', combine_all=False): <NEW_LINE> <INDENT> x = latex(x, combine_all=combine_all) <NEW_LINE> prefix = r"\text{\texttt{" <NEW_LINE> parts = x.split(prefix) <NEW_LINE> for i, part in enumerate(parts): <NEW_LINE> <INDENT> if i == 0: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> n = 1 <NEW_LINE> for closing, c in enumerate(part): <NEW_LINE> <INDENT> if c == "{" and part[closing - 1] != "\\": <NEW_LINE> <INDENT> n += 1 <NEW_LINE> <DEDENT> if c == "}" and part[closing - 1] != "\\": <NEW_LINE> <INDENT> n -= 1 <NEW_LINE> <DEDENT> if n == -1: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> y = part[:closing-1] <NEW_LINE> for delimiter in """|"'`#%&,.:;?!@_~^+-/\=<>()[]{}0123456789E""": <NEW_LINE> <INDENT> if delimiter not in y: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> if delimiter == "E": <NEW_LINE> <INDENT> delimiter = "|" <NEW_LINE> y = "(complicated string)" <NEW_LINE> <DEDENT> wrapper = r"\verb" + delimiter + "%s" + delimiter <NEW_LINE> spacer = r"\phantom{\verb!%s!}" <NEW_LINE> y = y.replace("{ }", " ").replace("{-}", "-") <NEW_LINE> for c in r"#$%&\^_{}~": <NEW_LINE> <INDENT> char_wrapper = r"{\char`\%s}" % c <NEW_LINE> y = y.replace(char_wrapper, c) <NEW_LINE> <DEDENT> subparts = [] <NEW_LINE> nspaces = 0 <NEW_LINE> for subpart in y.split(" "): <NEW_LINE> <INDENT> if subpart == "": <NEW_LINE> <INDENT> nspaces += 1 <NEW_LINE> continue <NEW_LINE> <DEDENT> if nspaces > 0: <NEW_LINE> <INDENT> subparts.append(spacer % ("x" * nspaces)) <NEW_LINE> <DEDENT> nspaces = 1 <NEW_LINE> subparts.append(wrapper % subpart) <NEW_LINE> <DEDENT> if not y: <NEW_LINE> <INDENT> subparts.append(spacer % "x") <NEW_LINE> <DEDENT> subparts.append(part[closing + 1:]) <NEW_LINE> parts[i] = "".join(subparts) <NEW_LINE> <DEDENT> x = "".join(parts) <NEW_LINE> from sage.misc.latex_macros import sage_configurable_latex_macros <NEW_LINE> if mode == 'display': <NEW_LINE> <INDENT> modecode = '; mode=display' <NEW_LINE> <DEDENT> elif mode == 'inline': <NEW_LINE> <INDENT> modecode = '' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("mode must be either 'display' or 'inline'") <NEW_LINE> <DEDENT> return MathJaxExpr('<html><script type="math/tex{}">'.format(modecode) + ''.join(sage_configurable_latex_macros) + _Latex_prefs._option['macros'] + '{}</script></html>'.format(x)) | Render LaTeX input using MathJax. This returns a :class:`MathJaxExpr`.
EXAMPLES::
sage: from sage.misc.latex import MathJax
sage: MathJax()(3)
<html><script type="math/tex; mode=display">\newcommand{\Bold}[1]{\mathbf{#1}}3</script></html>
sage: MathJax()(ZZ)
<html><script type="math/tex; mode=display">\newcommand{\Bold}[1]{\mathbf{#1}}\Bold{Z}</script></html> | 62599052379a373c97d9a4f7 |
class LinksysWRT54GL(cgm_devices.DeviceBase): <NEW_LINE> <INDENT> identifier = 'wrt54gl' <NEW_LINE> name = "WRT54GL" <NEW_LINE> manufacturer = "Linksys" <NEW_LINE> url = 'http://www.linksysbycisco.com/' <NEW_LINE> architecture = 'brcm47xx' <NEW_LINE> radios = [ cgm_devices.IntegratedRadio('wifi0', _("Integrated wireless radio"), [cgm_protocols.IEEE80211BG], [ cgm_devices.AntennaConnector('a1', "Antenna0"), cgm_devices.AntennaConnector('a2', "Antenna1"), ]) ] <NEW_LINE> switches = [ cgm_devices.Switch( 'sw0', "Switch0", ports=6, cpu_port=5, vlans=16, configurable=False, presets=[ cgm_devices.SwitchPreset('default', _("Default VLAN configuration"), vlans=[ cgm_devices.SwitchVLANPreset( 'wan0', "Wan0", vlan=2, ports=[5, 0], ), cgm_devices.SwitchVLANPreset( 'lan0', "Lan0", vlan=1, ports=[5, 1, 2, 3, 4], ), ]) ] ) ] <NEW_LINE> ports = [] <NEW_LINE> antennas = [ cgm_devices.InternalAntenna( identifier='a1', polarization='horizontal', angle_horizontal=360, angle_vertical=75, gain=2, ) ] <NEW_LINE> port_map = { 'openwrt': { 'wifi0': 'wlan0', 'sw0': cgm_devices.SwitchPortMap('switch0', vlans='eth0.{vlan}'), } } | Linksys WRT54GL device descriptor. | 62599052e76e3b2f99fd9ed0 |
class HourGlass(nn.Module): <NEW_LINE> <INDENT> def __init__(self,n=4,f=128): <NEW_LINE> <INDENT> super(HourGlass,self).__init__() <NEW_LINE> self._n = n <NEW_LINE> self._f = f <NEW_LINE> self._init_layers(self._n,self._f) <NEW_LINE> <DEDENT> def _init_layers(self,n,f): <NEW_LINE> <INDENT> setattr(self,'res'+str(n)+'_1',Residual(f,f)) <NEW_LINE> setattr(self,'pool'+str(n)+'_1',nn.MaxPool2d(2,2)) <NEW_LINE> setattr(self,'res'+str(n)+'_2',Residual(f,f)) <NEW_LINE> if n > 1: <NEW_LINE> <INDENT> self._init_layers(n-1,f) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.res_center = Residual(f,f) <NEW_LINE> <DEDENT> setattr(self,'res'+str(n)+'_3',Residual(f,f)) <NEW_LINE> setattr(self,'unsample'+str(n),Upsample(scale_factor=2)) <NEW_LINE> <DEDENT> def _forward(self,x,n,f): <NEW_LINE> <INDENT> up1 = x <NEW_LINE> up1 = eval('self.res'+str(n)+'_1')(up1) <NEW_LINE> low1 = eval('self.pool'+str(n)+'_1')(x) <NEW_LINE> low1 = eval('self.res'+str(n)+'_2')(low1) <NEW_LINE> if n > 1: <NEW_LINE> <INDENT> low2 = self._forward(low1,n-1,f) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> low2 = self.res_center(low1) <NEW_LINE> <DEDENT> low3 = low2 <NEW_LINE> low3 = eval('self.'+'res'+str(n)+'_3')(low3) <NEW_LINE> up2 = eval('self.'+'unsample'+str(n)).forward(low3) <NEW_LINE> return up1+up2 <NEW_LINE> <DEDENT> def forward(self,x): <NEW_LINE> <INDENT> return self._forward(x,self._n,self._f) | 不改变特征图的高宽 | 6259905263d6d428bbee3ca3 |
class DemoView(BrowserView): <NEW_LINE> <INDENT> def __init__(self, context, request): <NEW_LINE> <INDENT> self.context = context <NEW_LINE> self.request = request <NEW_LINE> <DEDENT> def __call__(self): <NEW_LINE> <INDENT> return super(DemoView, self).__call__() | This does nothing so far
| 625990528da39b475be046bd |
class AtomicWriter(object): <NEW_LINE> <INDENT> def __init__(self, path, mode): <NEW_LINE> <INDENT> self.path = path <NEW_LINE> self.mode = mode <NEW_LINE> <DEDENT> def commit(self, writer): <NEW_LINE> <INDENT> writer.flush() <NEW_LINE> os.rename(writer.name, self.path) <NEW_LINE> <DEDENT> def rollback(self, writer): <NEW_LINE> <INDENT> os.unlink(writer.name) <NEW_LINE> <DEDENT> def get_stream(self): <NEW_LINE> <INDENT> return NamedTemporaryFile(delete=False, mode=self.mode) <NEW_LINE> <DEDENT> @contextmanager <NEW_LINE> def transaction(self): <NEW_LINE> <INDENT> with self.get_stream() as writer: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> yield writer <NEW_LINE> self.commit(writer) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> self.rollback(writer) <NEW_LINE> raise | Helper class for performing atomic writes.
:param path: Path to the file.
:param mode: Mode to open the file with. | 625990522ae34c7f260ac5b9 |
class Deque(object): <NEW_LINE> <INDENT> def __init__(self, limit = 10): <NEW_LINE> <INDENT> self.queue = [] <NEW_LINE> self.limit = limit <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return ' '.join([str(i) for i in self.queue]) <NEW_LINE> <DEDENT> def isEmpty(self): <NEW_LINE> <INDENT> return len(self.queue) <= 0 <NEW_LINE> <DEDENT> def isFull(self): <NEW_LINE> <INDENT> return len(self.queue) >= self.limit <NEW_LINE> <DEDENT> def insertRear(self, data): <NEW_LINE> <INDENT> if self.isFull(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.queue.insert(0, data) <NEW_LINE> <DEDENT> <DEDENT> def insertFront(self, data): <NEW_LINE> <INDENT> if self.isFull(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.queue.append(data) <NEW_LINE> <DEDENT> <DEDENT> def deleteRear(self): <NEW_LINE> <INDENT> if self.isEmpty(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.queue.pop(0) <NEW_LINE> <DEDENT> <DEDENT> def deleteFront(self): <NEW_LINE> <INDENT> if self.isFull(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.queue.pop() | isEmpty : checks whether the deque is empty
isFull : checks whether the deque is full
insertRear : inserts an element at the rear end of the deque
insertFront : inserts an element at the front end of the deque
deleteRear : deletes an element from the rear end of the deque
deleteFront : deletes an element from the front end of the deque | 625990526e29344779b01b1c |
class ServerHeartbeatSucceededEvent(_ServerHeartbeatEvent): <NEW_LINE> <INDENT> __slots__ = ('__duration', '__reply', '__awaited') <NEW_LINE> def __init__(self, duration, reply, connection_id, awaited=False): <NEW_LINE> <INDENT> super(ServerHeartbeatSucceededEvent, self).__init__(connection_id) <NEW_LINE> self.__duration = duration <NEW_LINE> self.__reply = reply <NEW_LINE> self.__awaited = awaited <NEW_LINE> <DEDENT> @property <NEW_LINE> def duration(self): <NEW_LINE> <INDENT> return self.__duration <NEW_LINE> <DEDENT> @property <NEW_LINE> def reply(self): <NEW_LINE> <INDENT> return self.__reply <NEW_LINE> <DEDENT> @property <NEW_LINE> def awaited(self): <NEW_LINE> <INDENT> return self.__awaited <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<%s %s duration: %s, awaited: %s, reply: %s>" % ( self.__class__.__name__, self.connection_id, self.duration, self.awaited, self.reply) | Fired when the server heartbeat succeeds.
.. versionadded:: 3.3 | 6259905271ff763f4b5e8c81 |
class UsernameConfiguration(AWSProperty): <NEW_LINE> <INDENT> props: PropsDictType = { "CaseSensitive": (boolean, False), } | `UsernameConfiguration <http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-usernameconfiguration.html>`__ | 6259905223e79379d538d9ce |
class Seccion: <NEW_LINE> <INDENT> def __init__(self, nombre, tipo, propiedades, material, qy=None): <NEW_LINE> <INDENT> self.qy = qy <NEW_LINE> self.propiedadesGeometricas = propiedades <NEW_LINE> self.material = material <NEW_LINE> self.nombre = nombre <NEW_LINE> if tipo == TipoSeccion.RECTANGULAR: <NEW_LINE> <INDENT> self.area = propiedades[0] * propiedades[1] <NEW_LINE> self.inercia = (propiedades[0] * propiedades[1] ** 3) / 12 <NEW_LINE> self.As = 5 / 6 * self.area <NEW_LINE> <DEDENT> if tipo == TipoSeccion.CIRCULAR: <NEW_LINE> <INDENT> self.area = propiedades[0] ** 2 * np.pi / 4 <NEW_LINE> self.inercia = np.pi / 4 * (propiedades[0] / 2) ** 4 <NEW_LINE> self.As = 9 / 10 * self.area <NEW_LINE> <DEDENT> if tipo == TipoSeccion.GENERAL: <NEW_LINE> <INDENT> if len(propiedades) >= 3: <NEW_LINE> <INDENT> self.area = propiedades[0] <NEW_LINE> self.inercia = propiedades[1] <NEW_LINE> self.As = propiedades[2] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.area = propiedades[0] <NEW_LINE> self.inercia = propiedades[1] <NEW_LINE> self.As = 10 * 10 ** 10 | Clase que representa la sección de los elementos a utilizar, asi como los materiales que la componen
Args:
nombre (str): Nombre definido para la sección a crear
tipo (Tipo): Geometría de la sección transversal (Rectangular, Circular o General)
propiedades (list): Dimensiones en metros relacionadas al tipo de geometría (Rectangular: base y altura, Circular: diámetro, General: área, inercia y área de cortante)
material (Material): Tipo de material a utilizar
qy (list, optional): Esto era algo de no lineal material pero no recuerdo. Defaults to None. | 62599052435de62698e9d2d6 |
class AdminUserAPI(Resource): <NEW_LINE> <INDENT> method_decorators = [admin_required] <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.put_parser = parser(False) <NEW_LINE> super(AdminUserAPI, self).__init__() <NEW_LINE> <DEDENT> @marshal_with(admin_user_fields) <NEW_LINE> def get(self, key_id): <NEW_LINE> <INDENT> user = ndb.Key(UserModel, key_id).get() <NEW_LINE> if not user: <NEW_LINE> <INDENT> abort(404) <NEW_LINE> <DEDENT> return user <NEW_LINE> <DEDENT> @marshal_with(admin_user_fields) <NEW_LINE> def put(self, key_id): <NEW_LINE> <INDENT> user = ndb.Key(UserModel, key_id).get() <NEW_LINE> if not user: <NEW_LINE> <INDENT> abort(404) <NEW_LINE> <DEDENT> args = self.put_parser.parse_args() <NEW_LINE> args = {k:v for (k, v) in args.items() if v is not None} <NEW_LINE> user.populate(**args) <NEW_LINE> user.put() <NEW_LINE> return user <NEW_LINE> <DEDENT> def delete(self, key_id): <NEW_LINE> <INDENT> key = ndb.Key(UserModel, key_id) <NEW_LINE> if not key.get(): <NEW_LINE> <INDENT> abort(404) <NEW_LINE> <DEDENT> key.delete() <NEW_LINE> return make_response("", 204) | GET, PUT, DELETE on _other_ users | 62599052379a373c97d9a4f9 |
class IloVirtualMediaAgentDeploy(base.DeployInterface): <NEW_LINE> <INDENT> def get_properties(self): <NEW_LINE> <INDENT> return COMMON_PROPERTIES <NEW_LINE> <DEDENT> def validate(self, task): <NEW_LINE> <INDENT> driver_utils.validate_boot_mode_capability(task.node) <NEW_LINE> driver_utils.validate_secure_boot_capability(task.node) <NEW_LINE> _parse_driver_info(task.node) <NEW_LINE> <DEDENT> @task_manager.require_exclusive_lock <NEW_LINE> def deploy(self, task): <NEW_LINE> <INDENT> _prepare_agent_vmedia_boot(task) <NEW_LINE> return states.DEPLOYWAIT <NEW_LINE> <DEDENT> @task_manager.require_exclusive_lock <NEW_LINE> def tear_down(self, task): <NEW_LINE> <INDENT> manager_utils.node_power_action(task, states.POWER_OFF) <NEW_LINE> try: <NEW_LINE> <INDENT> _update_secure_boot_mode(task, False) <NEW_LINE> <DEDENT> except exception.IloOperationNotSupported: <NEW_LINE> <INDENT> LOG.warn(_LW('Secure boot mode is not supported for node %s'), task.node.uuid) <NEW_LINE> <DEDENT> return states.DELETED <NEW_LINE> <DEDENT> def prepare(self, task): <NEW_LINE> <INDENT> node = task.node <NEW_LINE> node.instance_info = agent.build_instance_info_for_deploy(task) <NEW_LINE> node.save() <NEW_LINE> _prepare_node_for_deploy(task) <NEW_LINE> <DEDENT> def clean_up(self, task): <NEW_LINE> <INDENT> ilo_common.cleanup_vmedia_boot(task) <NEW_LINE> <DEDENT> def take_over(self, task): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_clean_steps(self, task): <NEW_LINE> <INDENT> steps = deploy_utils.agent_get_clean_steps(task) <NEW_LINE> if CONF.ilo.clean_priority_erase_devices: <NEW_LINE> <INDENT> for step in steps: <NEW_LINE> <INDENT> if (step.get('step') == 'erase_devices' and step.get('interface') == 'deploy'): <NEW_LINE> <INDENT> step['priority'] = CONF.ilo.clean_priority_erase_devices <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return steps <NEW_LINE> <DEDENT> def execute_clean_step(self, task, step): <NEW_LINE> <INDENT> return deploy_utils.agent_execute_clean_step(task, step) <NEW_LINE> <DEDENT> def prepare_cleaning(self, task): <NEW_LINE> <INDENT> provider = dhcp_factory.DHCPFactory().provider <NEW_LINE> if getattr(provider, 'delete_cleaning_ports', None): <NEW_LINE> <INDENT> provider.delete_cleaning_ports(task) <NEW_LINE> <DEDENT> if getattr(provider, 'create_cleaning_ports', None): <NEW_LINE> <INDENT> provider.create_cleaning_ports(task) <NEW_LINE> <DEDENT> _prepare_agent_vmedia_boot(task) <NEW_LINE> return states.CLEANING <NEW_LINE> <DEDENT> def tear_down_cleaning(self, task): <NEW_LINE> <INDENT> manager_utils.node_power_action(task, states.POWER_OFF) <NEW_LINE> provider = dhcp_factory.DHCPFactory().provider <NEW_LINE> if getattr(provider, 'delete_cleaning_ports', None): <NEW_LINE> <INDENT> provider.delete_cleaning_ports(task) | Interface for deploy-related actions. | 625990520c0af96317c577cb |
class CreateCommitError(Exception): <NEW_LINE> <INDENT> pass | The creation of a commit has failed or was aborted. | 62599052a8ecb033258726eb |
class T7(SortTest): <NEW_LINE> <INDENT> def sink(self, Q: list, k: int, n: int): <NEW_LINE> <INDENT> while 2 * k <= n: <NEW_LINE> <INDENT> j = 2 * k <NEW_LINE> if j < n and Q[j] < Q[j + 1]: <NEW_LINE> <INDENT> j += 1 <NEW_LINE> <DEDENT> if Q[j] < Q[k]: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> Q[j], Q[k] = Q[k], Q[j] <NEW_LINE> k = j <NEW_LINE> <DEDENT> <DEDENT> def sort(self, Q: list): <NEW_LINE> <INDENT> Q.insert(0, 0) <NEW_LINE> N = len(Q) - 1 <NEW_LINE> for k in range(N // 2, 0, -1): <NEW_LINE> <INDENT> self.sink(Q, k, N) <NEW_LINE> <DEDENT> for k in range(N, 0, -1): <NEW_LINE> <INDENT> Q[k], Q[1] = Q[1], Q[k] <NEW_LINE> self.sink(Q, 1, k - 1) <NEW_LINE> <DEDENT> Q.pop(0) | 堆排序 | 625990523539df3088ecd77a |
class BootKExec(Boot): <NEW_LINE> <INDENT> def __init__(self, parent, parameters): <NEW_LINE> <INDENT> super(BootKExec, self).__init__(parent) <NEW_LINE> self.action = BootKexecAction() <NEW_LINE> self.action.section = self.action_type <NEW_LINE> self.action.job = self.job <NEW_LINE> parent.add_action(self.action, parameters) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def accepts(cls, device, parameters): <NEW_LINE> <INDENT> if 'method' in parameters: <NEW_LINE> <INDENT> if parameters['method'] == 'kexec': <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False | Expects a shell session, checks for kexec executable and
prepares the arguments to run kexec, | 625990528da39b475be046bf |
class TestMediaFileListResponse(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testMediaFileListResponse(self): <NEW_LINE> <INDENT> model = kinow_client.models.media_file_list_response.MediaFileListResponse() | MediaFileListResponse unit test stubs | 62599052b7558d5895464994 |
class EggDrop: <NEW_LINE> <INDENT> def __init__( self, n: int, e: int): <NEW_LINE> <INDENT> if n < 0: <NEW_LINE> <INDENT> raise ValueError("Number of floors should be positive.") <NEW_LINE> <DEDENT> if e < 0: <NEW_LINE> <INDENT> raise ValueError("Number of eggs should be positive.") <NEW_LINE> <DEDENT> self.n = n <NEW_LINE> self.e = e <NEW_LINE> self.current_solutions = {0: 0} <NEW_LINE> return None <NEW_LINE> <DEDENT> def _two_eggs(self, n): <NEW_LINE> <INDENT> return ceil(0.5 * (-1 + sqrt(1 + 8 * n))) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> if self.n == 0: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> elif self.n == 1: <NEW_LINE> <INDENT> self.current_solutions[1] = 1 <NEW_LINE> <DEDENT> elif self.e == 1: <NEW_LINE> <INDENT> self.current_solutions.update({x: x for x in range(self.n + 1)}) <NEW_LINE> <DEDENT> elif self.e == 2: <NEW_LINE> <INDENT> self.result = self._two_eggs(self.n) <NEW_LINE> self.current_solutions.update( {x: self._two_eggs(x) for x in range(1, self.n + 1)}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.prev_solutions = {0: 0, 1: 1} <NEW_LINE> for x in range(2, self.n + 1): <NEW_LINE> <INDENT> self.prev_solutions[x] = self._two_eggs(x) <NEW_LINE> <DEDENT> for current_e in range(self.e - 2): <NEW_LINE> <INDENT> self.current_solutions = {0: 0, 1: 1} <NEW_LINE> for current_n in range(2, self.n + 1): <NEW_LINE> <INDENT> current_min = current_n <NEW_LINE> for k in range(2, current_n): <NEW_LINE> <INDENT> current_min = min( current_min, 1 + max( self.prev_solutions[k - 1], self.current_solutions[current_n - k] ) ) <NEW_LINE> <DEDENT> self.current_solutions[current_n] = current_min <NEW_LINE> <DEDENT> self.prev_solutions = deepcopy(self.current_solutions) <NEW_LINE> <DEDENT> <DEDENT> self.solution = self.current_solutions[self.n] <NEW_LINE> return self.solution | Run dynamic programming routine to solve egg drop problem. | 62599052cad5886f8bdc5aeb |
class FavouriteManager(object): <NEW_LINE> <INDENT> def __init__(self, session): <NEW_LINE> <INDENT> self._session = session <NEW_LINE> <DEDENT> @property <NEW_LINE> def _favourite_ids(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return map(int, self._session.get('favourite', '').split(',')) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> <DEDENT> @_favourite_ids.setter <NEW_LINE> def _favourite_ids(self, ids): <NEW_LINE> <INDENT> self._session['favourite'] = ','.join(set(ids)) <NEW_LINE> <DEDENT> def add(self, estate): <NEW_LINE> <INDENT> ids = self._favourite_ids <NEW_LINE> ids.append(estate.id) <NEW_LINE> self._favourite_ids = ids | Favourite manager | 62599052baa26c4b54d50783 |
class RectDelta(XY): <NEW_LINE> <INDENT> pass | X/Y rectangle delta data item | 62599052d53ae8145f919937 |
class QIMatch(DataProcessor): <NEW_LINE> <INDENT> def get_train_examples(self, data_dir,fname=None): <NEW_LINE> <INDENT> if fname!=None: <NEW_LINE> <INDENT> return self._create_examples( self._read_tsv(os.path.join(data_dir, fname)), "train") <NEW_LINE> <DEDENT> return self._create_examples( self._read_tsv(os.path.join(data_dir, "train.txt.match")), "train") <NEW_LINE> <DEDENT> def get_dev_examples(self, data_dir,fname=None): <NEW_LINE> <INDENT> if fname!=None: <NEW_LINE> <INDENT> return self._create_examples( self._read_tsv(os.path.join(data_dir, fname)), "dev") <NEW_LINE> <DEDENT> return self._create_examples( self._read_tsv(os.path.join(data_dir, "dev.txt.match")), "dev") <NEW_LINE> <DEDENT> def get_test_examples(self, data_dir,fname=None): <NEW_LINE> <INDENT> if fname!=None: <NEW_LINE> <INDENT> return self._create_examples( self._read_tsv(os.path.join(data_dir, fname)), "test") <NEW_LINE> <DEDENT> return self._create_examples( self._read_tsv(os.path.join(data_dir, "test.txt.match")), "test") <NEW_LINE> <DEDENT> def get_labels(self): <NEW_LINE> <INDENT> return ["0","1"] <NEW_LINE> <DEDENT> def _create_examples(self, lines, set_type): <NEW_LINE> <INDENT> examples = [] <NEW_LINE> for (i, line) in enumerate(lines): <NEW_LINE> <INDENT> guid = "%s-%s" % (set_type, i) <NEW_LINE> text_a = tokenization.convert_to_unicode(line[1]) <NEW_LINE> text_b = tokenization.convert_to_unicode(line[2]) <NEW_LINE> label = tokenization.convert_to_unicode(line[3]) <NEW_LINE> examples.append( InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) <NEW_LINE> <DEDENT> return examples | Processor for the CoLA data set (GLUE version). | 6259905271ff763f4b5e8c83 |
class Course(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=50, unique=True, verbose_name='课程名称') <NEW_LINE> price = models.PositiveSmallIntegerField(verbose_name='价格') <NEW_LINE> period = models.PositiveSmallIntegerField(verbose_name='课程周期(月)', default=5) <NEW_LINE> outline = models.TextField(verbose_name='大纲') <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name_plural = verbose_name = '课程' | 课程表 | 62599052a219f33f346c7cda |
class LockedSet: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.inner = set() <NEW_LINE> self.lock = threading.Lock() <NEW_LINE> <DEDENT> def add(self, element): <NEW_LINE> <INDENT> with self.lock: <NEW_LINE> <INDENT> prelength = len(self.inner) <NEW_LINE> self.inner.add(element) <NEW_LINE> return prelength != len(self.inner) <NEW_LINE> <DEDENT> <DEDENT> def move(self, item, to): <NEW_LINE> <INDENT> if id(self) < id(to): <NEW_LINE> <INDENT> first = self <NEW_LINE> second = to <NEW_LINE> <DEDENT> elif id(self) > id(to): <NEW_LINE> <INDENT> first = to <NEW_LINE> second = self <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> with first.lock: <NEW_LINE> <INDENT> with second.lock: <NEW_LINE> <INDENT> self.inner.remove(item) <NEW_LINE> to.inner.add(item) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def length(self): <NEW_LINE> <INDENT> with self.lock: <NEW_LINE> <INDENT> return len(self.inner) | Wrapper around a set() with a lock and atomic move. | 625990528e7ae83300eea56c |
class qZ(object): <NEW_LINE> <INDENT> def __init__(self, fa_dim): <NEW_LINE> <INDENT> self.fa_dim = fa_dim <NEW_LINE> self.aug_dim = fa_dim + 1 <NEW_LINE> self.prior = None <NEW_LINE> self.set_default_priors() <NEW_LINE> self.mu = None <NEW_LINE> self.cov = None <NEW_LINE> self.prec = None <NEW_LINE> self.expt2 = None <NEW_LINE> <DEDENT> def init_expt(self, data_len): <NEW_LINE> <INDENT> self.mu = tile(self.prior.mu, (1, data_len)) <NEW_LINE> self.cov = ncopy(self.prior.cov[:, :, 0]) <NEW_LINE> self.prec = ncopy(self.prior.prec[:, :, 0]) <NEW_LINE> self.expt2 = self.calc_expt2() <NEW_LINE> <DEDENT> def set_default_priors(self): <NEW_LINE> <INDENT> m, c, p = DefaultFaParams().Z(self.fa_dim) <NEW_LINE> m = m[:, newaxis] <NEW_LINE> c = c[:, :, newaxis] <NEW_LINE> p = p[:, :, newaxis] <NEW_LINE> self.set_prior(mu=m, cov=c, prec=p) <NEW_LINE> <DEDENT> def set_prior(self, **argvs): <NEW_LINE> <INDENT> self.prior = MultivariateNormal(self.aug_dim, 1) <NEW_LINE> self.prior.set_params(**argvs) <NEW_LINE> <DEDENT> def update(self, theta, Y): <NEW_LINE> <INDENT> rll = einsum('ddk,ljdk->lj', theta.r.post.expt, theta.lamb.post.expt2) <NEW_LINE> self.prec = rll + self.prior.prec[:, :, 0] <NEW_LINE> self.cov = inv(self.prec) <NEW_LINE> lr = einsum('ldk,ddk->ld', theta.lamb.post.mu, theta.r.post.expt) <NEW_LINE> lry = einsum('ld,dt->lt', lr, Y) <NEW_LINE> lry_muz = lry + self.prior.expt_prec_mu[:, 0, newaxis] <NEW_LINE> self.mu = einsum('lj,jt->lt', self.cov, lry_muz) <NEW_LINE> self.expt2 = self.calc_expt2() <NEW_LINE> <DEDENT> def samples(self, data_len, by_posterior=True): <NEW_LINE> <INDENT> if by_posterior: <NEW_LINE> <INDENT> sample_z = ones((self.aug_dim, data_len)) * nan <NEW_LINE> mu_len = 0 if self.mu is None else self.mu.shape[-1] <NEW_LINE> t_max = data_len if data_len < mu_len else mu_len <NEW_LINE> for t in range(t_max): <NEW_LINE> <INDENT> sample_z[:, t] = mvnrnd(self.mu[:, t], self.cov) <NEW_LINE> <DEDENT> t_rest = data_len - t_max <NEW_LINE> if t_rest > 0: <NEW_LINE> <INDENT> sample_z[:, t_max:] = self.prior.samples(t_rest)[:, :, 0].T <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> sample_z = self.prior.samples(data_len)[:, :, 0].T <NEW_LINE> <DEDENT> return sample_z <NEW_LINE> <DEDENT> def expectations(self, by_posterior=True): <NEW_LINE> <INDENT> dst = tile(self.mu, (self.n_states, 1, 1)).transpose(1, 0, 2) <NEW_LINE> return dst <NEW_LINE> <DEDENT> def calc_expt2(self): <NEW_LINE> <INDENT> mm = einsum('lt,jt->ljt', self.mu, self.mu) + self.cov[:, :, newaxis] <NEW_LINE> return mm | z = qZ(data_len, fa_dim) | 6259905224f1403a9268633a |
class OCIObjectStoragePrefixSensor(BaseOCIObjectStorageSensor): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> <DEDENT> def poke(self, context): <NEW_LINE> <INDENT> self.log.info('Poking for prefix %s in bucket %s', self.prefix, self.bucket_name) <NEW_LINE> try: <NEW_LINE> <INDENT> hook = self.get_oci_hook() <NEW_LINE> namespace_name = hook.get_namespace(compartment_id=self.compartment_id) <NEW_LINE> object_store_client = hook.get_client(hook.oci_client) <NEW_LINE> base_arguments = dict( namespace_name=namespace_name, bucket_name=self.bucket_name, prefix=self.prefix, fields="size", ) <NEW_LINE> objectsummary = object_store_client.list_objects(**base_arguments) <NEW_LINE> file_names = [] <NEW_LINE> total_files = 0 <NEW_LINE> total_size = 0 <NEW_LINE> while True: <NEW_LINE> <INDENT> object_list = objectsummary.data <NEW_LINE> for object in object_list.objects: <NEW_LINE> <INDENT> file_names.append(object.name) <NEW_LINE> total_files += 1 <NEW_LINE> total_size += object.size <NEW_LINE> <DEDENT> if object_list.next_start_with is None: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> base_arguments["next_start_with"] = object_list.next_start_with <NEW_LINE> object_store_client.list_object(**base_arguments) <NEW_LINE> <DEDENT> if len(file_names) > 0: <NEW_LINE> <INDENT> context['task_instance'].xcom_push('oci_prefix_file_names', file_names) <NEW_LINE> context['task_instance'].xcom_push('oci_prefix_total_files', total_files) <NEW_LINE> context['task_instance'].xcom_push('oci_prefix_total_size', total_size) <NEW_LINE> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> except AirflowException as e: <NEW_LINE> <INDENT> self.log.error(e.response["Error"]["Message"]) | Prefix sensor for OCI Object Storage | 6259905223849d37ff852599 |
class SwitchView(base_widget): <NEW_LINE> <INDENT> def __init__(self, contr: base_controller, parent: base_widget, idstr: str, attrdct: dict, jsel) -> None: <NEW_LINE> <INDENT> super().__init__(contr, parent, idstr, attrdct, jsel) <NEW_LINE> self.view_lst: T.List[BasicView] = [] <NEW_LINE> self.view_dct: T.Dict[str, BasicView] = {} <NEW_LINE> <DEDENT> def addView(self, child_el: BasicView, viewname: str): <NEW_LINE> <INDENT> self.view_lst.append(child_el) <NEW_LINE> self.view_dct[viewname] = child_el <NEW_LINE> child_el.addObserver(self, base.MSGD_BUTTON_CLICK) <NEW_LINE> <DEDENT> def getView(self, numorname) -> T.Optional[BasicView]: <NEW_LINE> <INDENT> on_view = None <NEW_LINE> if isinstance(numorname, int): <NEW_LINE> <INDENT> if 0 <= numorname < len(self.view_lst): <NEW_LINE> <INDENT> on_view = self.view_lst[numorname] <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> on_view = self.view_dct.get(numorname, None) <NEW_LINE> <DEDENT> if on_view is None: <NEW_LINE> <INDENT> log("getView error: no element '{}' found (len={}, names={})".format(numorname, len(self.view_lst), " ,".join(self.view_dct.keys()))) <NEW_LINE> <DEDENT> return on_view <NEW_LINE> <DEDENT> def switchTo(self, numorname) -> None: <NEW_LINE> <INDENT> on_view = self.getView(numorname) <NEW_LINE> if on_view is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for el in self.view_lst: <NEW_LINE> <INDENT> el.set_visible(el == on_view) <NEW_LINE> <DEDENT> <DEDENT> def rcvMsg(self, whofrom: base.base_obj, msgdesc: base.MSGdesc_Type, msgdat: T.Optional[base.MSGdata_Type]) -> None: <NEW_LINE> <INDENT> print("switchview: got message {}, {}".format(msgdesc, msgdat)) <NEW_LINE> if msgdat is not None: <NEW_LINE> <INDENT> cmd = msgdat.get('cmd', None) <NEW_LINE> tgt_view_name = msgdat.get('target', None) <NEW_LINE> if cmd == 'viewswitch' and tgt_view_name is not None: <NEW_LINE> <INDENT> self.switchTo(tgt_view_name) | An html div element that has a list of other div elements.
Only one of these is visible at any one time, one is able to switch
between them.
Note:
this works by setting and removing the hidden HTML5 attribute
of the elements.
This will only work with list elements that support this attribute, such
as div elements.
E.g. adding img elements directly to the switchview will NOT work.
Instead, use a BasicView, as a parent and then add that BasicView to the switchview. | 6259905230c21e258be99cde |
class InvalidJWEKeyType(JWException): <NEW_LINE> <INDENT> def __init__(self, expected, obtained): <NEW_LINE> <INDENT> msg = 'Expected key type %s, got %s' % (expected, obtained) <NEW_LINE> super(InvalidJWEKeyType, self).__init__(msg) | Invalid JWE Key Type.
This exception is raised when the provided JWK Key does not match
the type required by the sepcified algorithm. | 62599052596a89723612901a |
class BatchNormalizationLayer(StemCell): <NEW_LINE> <INDENT> def __init__(self, batch_mean=None, batch_std=None, is_test=0, **kwargs): <NEW_LINE> <INDENT> super(BatchNormalizationLayer, self).__init__(**kwargs) <NEW_LINE> self.batch_mean = batch_mean <NEW_LINE> self.batch_std = batch_std <NEW_LINE> self.set_mode(self.is_test) <NEW_LINE> <DEDENT> def set_mode(self, is_test=0): <NEW_LINE> <INDENT> self.is_test = is_test <NEW_LINE> if self.is_test: <NEW_LINE> <INDENT> self.fprop = self.which_fn('test_prop') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.fprop = self.which_fn('train_prop') <NEW_LINE> <DEDENT> <DEDENT> def train_prop(self, z): <NEW_LINE> <INDENT> z = unpack(z) <NEW_LINE> z.name = self.name <NEW_LINE> return z * self.train_scale <NEW_LINE> <DEDENT> def test_prop(self, z): <NEW_LINE> <INDENT> z = unpack(z) <NEW_LINE> z.name = self.name <NEW_LINE> return z * self.test_scale <NEW_LINE> <DEDENT> def __getstate__(self): <NEW_LINE> <INDENT> dic = self.__dict__.copy() <NEW_LINE> dic.pop('fprop') <NEW_LINE> return dic <NEW_LINE> <DEDENT> def __setstate__(self, state): <NEW_LINE> <INDENT> self.__dict__.update(state) <NEW_LINE> self.set_mode(self.is_test) | Batch normalization layer
Parameters
----------
.. todo:: | 62599052e64d504609df9e3b |
class ExampleBlock(Block): <NEW_LINE> <INDENT> def __init__(self, parent, idevice): <NEW_LINE> <INDENT> Block.__init__(self, parent, idevice) <NEW_LINE> self.contentElement = TextAreaElement(idevice.content) <NEW_LINE> self.contentElement.height = 250 <NEW_LINE> <DEDENT> def process(self, request): <NEW_LINE> <INDENT> Block.process(self, request) <NEW_LINE> content = self.contentElement.process(request) <NEW_LINE> if content: <NEW_LINE> <INDENT> self.idevice.content = content <NEW_LINE> <DEDENT> <DEDENT> def renderEdit(self, style): <NEW_LINE> <INDENT> html = u"<div>\n" <NEW_LINE> html += self.contentElement.renderEdit() <NEW_LINE> html += self.renderEditButtons() <NEW_LINE> html += u"</div>\n" <NEW_LINE> return html <NEW_LINE> <DEDENT> def renderPreview(self, style): <NEW_LINE> <INDENT> html = u"<div class=\"iDevice " <NEW_LINE> html += u"emphasis"+unicode(self.idevice.emphasis)+"\" " <NEW_LINE> html += u"ondblclick=\"submitLink('edit',"+self.id+", 0);\">\n" <NEW_LINE> html += self.contentElement.renderView() <NEW_LINE> html += self.renderViewButtons() <NEW_LINE> html += "</div>\n" <NEW_LINE> return html <NEW_LINE> <DEDENT> def renderView(self, style): <NEW_LINE> <INDENT> html = u"<div class=\"iDevice " <NEW_LINE> html += u"emphasis"+unicode(self.idevice.emphasis)+"\">\n" <NEW_LINE> html += self.contentElement.renderView() <NEW_LINE> html += u"</div>\n" <NEW_LINE> return html | ExampleBlock can render and process ExampleIdevices as XHTML
GenericBlock will replace it..... one day | 62599052097d151d1a2c254c |
class Footer(QWidget): <NEW_LINE> <INDENT> def __init__(self, manager, parent=None): <NEW_LINE> <INDENT> super(Footer, self).__init__(parent=parent) <NEW_LINE> self.__manager = manager <NEW_LINE> self.version = self.__manager.version <NEW_LINE> self.initUI() <NEW_LINE> <DEDENT> def initUI(self): <NEW_LINE> <INDENT> self.mainLayout = QHBoxLayout() <NEW_LINE> self.logWidget = QLabel("") <NEW_LINE> self.mainLayout.addWidget(self.logWidget) <NEW_LINE> self.mainLayout.addStretch() <NEW_LINE> self.currentVersion = QLabel("V %s" % self.version) <NEW_LINE> self.mainLayout.addWidget(self.currentVersion) <NEW_LINE> self.setLayout(self.mainLayout) <NEW_LINE> <DEDENT> def updateLog(self, text=""): <NEW_LINE> <INDENT> self.logWidget.setText(text) <NEW_LINE> <DEDENT> def refresh(self): <NEW_LINE> <INDENT> self.update() | Footer Class.
Args:
manager (class: "Manager"): The hestia manager.
parent (class: "QtWidgets.QWidget", optional): The parent widget. Defaults to None. | 62599052a8ecb033258726ed |
class EncoderBlock(HybridBlock): <NEW_LINE> <INDENT> def __init__(self, opts, num_unit, num_filters, trans_block=True): <NEW_LINE> <INDENT> super(EncoderBlock, self).__init__() <NEW_LINE> self.eblock = HybridSequential() <NEW_LINE> if trans_block: <NEW_LINE> <INDENT> self.eblock.add(TransitionBlock(opts, num_filters=num_filters)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.eblock.add(MaxPool3D(pool_size=(opts.zKernelSize, 3, 3), strides=(opts.zStride, 2, 2), padding=(opts.zPad, 1, 1))) <NEW_LINE> <DEDENT> self.eblock.add(DenseBlock(opts, num_unit)) <NEW_LINE> <DEDENT> def hybrid_forward(self, F, x, *args, **kwargs): <NEW_LINE> <INDENT> return self.eblock(x) | Return a block in Encoder | 6259905263b5f9789fe86648 |
class TableWidgetWrapper(WidgetWrapper): <NEW_LINE> <INDENT> def createWidget(self, schema_param=None): <NEW_LINE> <INDENT> self._schema_param = schema_param <NEW_LINE> self._database = None <NEW_LINE> self._schema = None <NEW_LINE> self._combo = QComboBox() <NEW_LINE> self._combo.setEditable(True) <NEW_LINE> self.refreshItems() <NEW_LINE> self._combo.currentIndexChanged.connect(lambda: self.widgetValueHasChanged.emit(self)) <NEW_LINE> self._combo.lineEdit().editingFinished.connect(lambda: self.widgetValueHasChanged.emit(self)) <NEW_LINE> return self._combo <NEW_LINE> <DEDENT> def postInitialize(self, wrappers): <NEW_LINE> <INDENT> for wrapper in wrappers: <NEW_LINE> <INDENT> if wrapper.parameterDefinition().name() == self._schema_param: <NEW_LINE> <INDENT> self.schema_wrapper = wrapper <NEW_LINE> self.setSchema(wrapper.database(), wrapper.value()) <NEW_LINE> wrapper.widgetValueHasChanged.connect(self.schemaChanged) <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def schemaChanged(self, wrapper): <NEW_LINE> <INDENT> database = wrapper.database() <NEW_LINE> schema = wrapper.value() <NEW_LINE> if database == self._database and schema == self._schema: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.setSchema(database, schema) <NEW_LINE> <DEDENT> def setSchema(self, database, schema): <NEW_LINE> <INDENT> self._database = database <NEW_LINE> self._schema = schema <NEW_LINE> self.refreshItems() <NEW_LINE> self.widgetValueHasChanged.emit(self) <NEW_LINE> <DEDENT> def refreshItems(self): <NEW_LINE> <INDENT> value = self.comboValue(combobox=self._combo) <NEW_LINE> self._combo.clear() <NEW_LINE> if (self._database is not None and isinstance(self._schema, str)): <NEW_LINE> <INDENT> for table in self._database.list_geotables(self._schema): <NEW_LINE> <INDENT> self._combo.addItem(table[0], table[0]) <NEW_LINE> <DEDENT> <DEDENT> if self.dialogType == DIALOG_MODELER: <NEW_LINE> <INDENT> strings = self.dialog.getAvailableValuesOfType( [QgsProcessingParameterString, QgsProcessingParameterNumber, QgsProcessingParameterFile, QgsProcessingParameterField, QgsProcessingParameterExpression], QgsProcessingOutputString) <NEW_LINE> for text, data in [(self.dialog.resolveValueDescription(s), s) for s in strings]: <NEW_LINE> <INDENT> self._combo.addItem(text, data) <NEW_LINE> <DEDENT> <DEDENT> self.setComboValue(value, self._combo) <NEW_LINE> <DEDENT> def setValue(self, value): <NEW_LINE> <INDENT> self.setComboValue(value, self._combo) <NEW_LINE> self.widgetValueHasChanged.emit(self) <NEW_LINE> <DEDENT> def value(self): <NEW_LINE> <INDENT> return self.comboValue(combobox=self._combo) | WidgetWrapper for ParameterString that create and manage a combobox widget
with existing tables from a parent schema parameter. | 6259905291af0d3eaad3b2ff |
class Guide(guide.ComponentGuide): <NEW_LINE> <INDENT> compType = TYPE <NEW_LINE> compName = NAME <NEW_LINE> description = DESCRIPTION <NEW_LINE> author = AUTHOR <NEW_LINE> url = URL <NEW_LINE> email = EMAIL <NEW_LINE> version = VERSION <NEW_LINE> def postInit(self): <NEW_LINE> <INDENT> self.save_transform = ["root", "eff"] <NEW_LINE> self.save_blade = ["blade"] <NEW_LINE> <DEDENT> def addObjects(self): <NEW_LINE> <INDENT> self.root = self.addRoot() <NEW_LINE> vTemp = transform.getOffsetPosition(self.root, [0, 4, 0]) <NEW_LINE> self.eff = self.addLoc("eff", self.root, vTemp) <NEW_LINE> self.blade = self.addBlade("blade", self.root, self.eff) <NEW_LINE> centers = [self.root, self.eff] <NEW_LINE> self.dispcrv = self.addDispCurve("crv", centers) <NEW_LINE> <DEDENT> def addParameters(self): <NEW_LINE> <INDENT> self.pPosition = self.addParam("position", "double", 0, 0, 1) <NEW_LINE> self.pMaxStretch = self.addParam("maxstretch", "double", 1.5, 1) <NEW_LINE> self.pMaxSquash = self.addParam("maxsquash", "double", .5, 0, 1) <NEW_LINE> self.pSoftness = self.addParam("softness", "double", 0, 0, 1) <NEW_LINE> self.pLockOri = self.addParam("lock_ori", "double", 1, 0, 1) <NEW_LINE> self.pDivision = self.addParam("division", "long", 5, 3) <NEW_LINE> self.pAutoBend = self.addParam("autoBend", "bool", False) <NEW_LINE> self.pCentralTangent = self.addParam("centralTangent", "bool", False) <NEW_LINE> self.pSt_profile = self.addFCurveParam( "st_profile", [[0, 0], [.5, -1], [1, 0]]) <NEW_LINE> self.pSq_profile = self.addFCurveParam( "sq_profile", [[0, 0], [.5, 1], [1, 0]]) <NEW_LINE> self.pUseIndex = self.addParam("useIndex", "bool", False) <NEW_LINE> self.pParentJointIndex = self.addParam( "parentJointIndex", "long", -1, None, None) | Component Guide Class | 62599052d99f1b3c44d06b76 |
class DropWorseModels(tf.keras.callbacks.Callback): <NEW_LINE> <INDENT> def __init__(self, model_dir, monitor, log_dir, keep_best=2): <NEW_LINE> <INDENT> super(DropWorseModels, self).__init__() <NEW_LINE> self._model_dir = model_dir <NEW_LINE> self._filename = "model-{:04d}" + SAVE_FORMAT_WITH_SEP <NEW_LINE> self._log_dir = log_dir <NEW_LINE> self._keep_best = keep_best <NEW_LINE> self.monitor = monitor <NEW_LINE> <DEDENT> def on_epoch_end(self, epoch, logs=None): <NEW_LINE> <INDENT> super(DropWorseModels, self).on_epoch_end(epoch, logs) <NEW_LINE> if epoch < self._keep_best: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> model_files = frozenset( filter( lambda filename: path.splitext(filename)[1] == SAVE_FORMAT_WITH_SEP, listdir(self._model_dir), ) ) <NEW_LINE> if len(model_files) < self._keep_best: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> tf_events_logs = tuple( islice( log_parser( infile=None, top=min(self._keep_best, epoch), directory=self._log_dir, tag=self.monitor, stdout=False, )[1], self._keep_best, ) ) <NEW_LINE> keep_models = frozenset( map(self._filename.format, map(itemgetter(0), tf_events_logs)) ) <NEW_LINE> if len(keep_models) < self._keep_best: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> files_to_remove = model_files - keep_models <NEW_LINE> with open("/tmp/log.txt", "a") as f: <NEW_LINE> <INDENT> f.write( "\n\n_save_model::epoch: \t{}".format(epoch).ljust(30) ) <NEW_LINE> f.write( "\n_save_model::logs: \t{}".format(logs).ljust(30) ) <NEW_LINE> f.write( "\n_save_model::tf_events_logs: \t{}".format( tf_events_logs ).ljust(30) ) <NEW_LINE> f.write( "\n_save_model::keep_models: \t{}".format( keep_models ).ljust(30) ) <NEW_LINE> f.write( "\n_save_model::model_files: \t{}".format( model_files ).ljust(30) ) <NEW_LINE> f.write( "\n_save_model::model_files - keep_models:\t{}".format( files_to_remove ).ljust(30) ) <NEW_LINE> f.write( "\n_save_model::keep_models - model_files:\t{}\n".format( keep_models - model_files ).ljust(30) ) <NEW_LINE> <DEDENT> it_consumes( islice( map( lambda filename: remove(path.join(self._model_dir, filename)), files_to_remove, ), len(keep_models) - self._keep_best, ) ) | Designed around making `save_best_only` work for arbitrary metrics and thresholds between metrics | 625990528da39b475be046c1 |
class IKContentFile(ContentFile): <NEW_LINE> <INDENT> def __init__(self, filename, content, format=None): <NEW_LINE> <INDENT> self.file = ContentFile(content) <NEW_LINE> self.file.name = filename <NEW_LINE> mimetype = getattr(self.file, 'content_type', None) <NEW_LINE> if format and not mimetype: <NEW_LINE> <INDENT> mimetype = format_to_mimetype(format) <NEW_LINE> <DEDENT> if not mimetype: <NEW_LINE> <INDENT> ext = os.path.splitext(filename or '')[1] <NEW_LINE> mimetype = extension_to_mimetype(ext) <NEW_LINE> <DEDENT> self.file.content_type = mimetype <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return smart_str(self.file.name or '') | Wraps a ContentFile in a file-like object with a filename and a
content_type. A PIL image format can be optionally be provided as a content
type hint. | 62599052d7e4931a7ef3d554 |
class member: <NEW_LINE> <INDENT> def __init__(self, func, decorators): <NEW_LINE> <INDENT> self.__name__ = func.__name__ <NEW_LINE> for deco in reversed(decorators): <NEW_LINE> <INDENT> func = deco(func) <NEW_LINE> <DEDENT> self.target = func <NEW_LINE> self.decorators = decorators <NEW_LINE> <DEDENT> def __get__(self, obj, owner): <NEW_LINE> <INDENT> if obj is None: <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> if not isinstance(owner, inheritly.meta): <NEW_LINE> <INDENT> raise TypeError("can't access {!r} from non-inheritly {!r}" .format(self, owner)) <NEW_LINE> <DEDENT> return self.target.__get__(obj, owner) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<inheritly.member {!r}>".format(self.__name__) | The result type of the ``@inheritly`` decorator | 6259905221a7993f00c67444 |
class CircleViz(MapViz): <NEW_LINE> <INDENT> def __init__(self, data, label_property=None, color_property=None, color_stops=None, color_default='grey', color_function_type='interpolate', *args, **kwargs): <NEW_LINE> <INDENT> super(CircleViz, self).__init__(data, *args, **kwargs) <NEW_LINE> self.template = 'circle' <NEW_LINE> self.label_property = label_property <NEW_LINE> self.color_property = color_property <NEW_LINE> self.color_stops = color_stops <NEW_LINE> self.color_function_type = color_function_type <NEW_LINE> self.color_default = color_default <NEW_LINE> <DEDENT> def add_unique_template_variables(self, options): <NEW_LINE> <INDENT> options.update(dict( geojson_data=json.dumps(self.data, ensure_ascii=False), colorProperty=self.color_property, colorType=self.color_function_type, colorStops=self.color_stops, defaultColor=self.color_default )) | Create a circle map | 62599052cad5886f8bdc5aec |
class kpoints_class(object): <NEW_LINE> <INDENT> def __init__(self, nk = 1): <NEW_LINE> <INDENT> self.nk = nk <NEW_LINE> self.weight = [2.0 / nk] * nk | store information related to kpoints | 62599052287bf620b62730c6 |
class NameToLabelTests(TestCase): <NEW_LINE> <INDENT> def test_nameToLabel(self): <NEW_LINE> <INDENT> nameData = [ ("f", "F"), ("fo", "Fo"), ("foo", "Foo"), ("fooBar", "Foo Bar"), ("fooBarBaz", "Foo Bar Baz"), ] <NEW_LINE> for inp, out in nameData: <NEW_LINE> <INDENT> got = util.nameToLabel(inp) <NEW_LINE> self.assertEqual(got, out, f"nameToLabel({inp!r}) == {got!r} != {out!r}") | Tests for L{nameToLabel}. | 62599052004d5f362081fa57 |
class IntegerLyraType(LyraType): <NEW_LINE> <INDENT> def __repr__(self): <NEW_LINE> <INDENT> return "int" | Integer type representation. | 6259905271ff763f4b5e8c85 |
class SpatialDropout1D(Dropout): <NEW_LINE> <INDENT> @interfaces.legacy_spatialdropout1d_support <NEW_LINE> def __init__(self, rate, **kwargs): <NEW_LINE> <INDENT> super(SpatialDropout1D, self).__init__(rate, **kwargs) <NEW_LINE> self.input_spec = InputSpec(ndim=3) <NEW_LINE> <DEDENT> def _get_noise_shape(self, inputs): <NEW_LINE> <INDENT> input_shape = K.shape(inputs) <NEW_LINE> noise_shape = (input_shape[0], 1, input_shape[2]) <NEW_LINE> return noise_shape | Spatial 1D version of Dropout.
This version performs the same function as Dropout, however it drops
entire 1D feature maps instead of individual elements. If adjacent frames
within feature maps are strongly correlated (as is normally the case in
early convolution layers) then regular dropout will not regularize the
activations and will otherwise just result in an effective learning rate
decrease. In this case, SpatialDropout1D will help promote independence
between feature maps and should be used instead.
# Arguments
rate: float between 0 and 1. Fraction of the input units to drop.
# Input shape
3D tensor with shape:
`(samples, timesteps, channels)`
# Output shape
Same as input
# References
- [Efficient Object Localization Using Convolutional Networks](https://arxiv.org/abs/1411.4280) | 6259905207d97122c4218181 |
class HwSupply(HwModule.HwModule): <NEW_LINE> <INDENT> INTR_SWITCHON = 'hw_supply.switchOn' <NEW_LINE> def __init__(self,engine,motehandler): <NEW_LINE> <INDENT> self.engine = engine <NEW_LINE> self.motehandler = motehandler <NEW_LINE> self.moteOn = False <NEW_LINE> HwModule.HwModule.__init__(self,'HwSupply') <NEW_LINE> <DEDENT> def switchOn(self): <NEW_LINE> <INDENT> if self.log.isEnabledFor(logging.DEBUG): <NEW_LINE> <INDENT> self.log.debug('switchOn') <NEW_LINE> <DEDENT> if self.moteOn: <NEW_LINE> <INDENT> raise RuntimeError('mote already on') <NEW_LINE> <DEDENT> self.moteOn = True <NEW_LINE> self.motehandler.hwCrystal.start() <NEW_LINE> self.motehandler.mote.supply_on() <NEW_LINE> <DEDENT> def switchOff(self): <NEW_LINE> <INDENT> if self.log.isEnabledFor(logging.DEBUG): <NEW_LINE> <INDENT> self.log.debug('switchOff') <NEW_LINE> <DEDENT> if not self.moteOn: <NEW_LINE> <INDENT> raise RuntimeError('mote already off') <NEW_LINE> <DEDENT> self.moteOn = False <NEW_LINE> <DEDENT> def isOn(self): <NEW_LINE> <INDENT> return self.moteOn | rief Emulates the mote's power supply | 6259905207f4c71912bb0910 |
class DefensiveReflexAgent(ReflexCaptureAgent): <NEW_LINE> <INDENT> def choosePowers(self, gameState, powerLimit): <NEW_LINE> <INDENT> validPowers = LEGAL_POWERS[:] <NEW_LINE> powers = util.Counter() <NEW_LINE> opponentPowers = self.getOpponentTeamPowers(gameState) <NEW_LINE> if 'speed' in opponentPowers: <NEW_LINE> <INDENT> powers['reflex'] = 2 <NEW_LINE> validPowers.remove('reflex') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> powers['laser'] = 2 <NEW_LINE> validPowers.remove('laser') <NEW_LINE> <DEDENT> for i in range(powerLimit - 2): <NEW_LINE> <INDENT> choice = random.choice(validPowers) <NEW_LINE> powers[choice] += 1 <NEW_LINE> if powers[choice] == 2: <NEW_LINE> <INDENT> validPowers.remove(choice) <NEW_LINE> <DEDENT> <DEDENT> return powers <NEW_LINE> <DEDENT> def getFeatures(self, gameState, action): <NEW_LINE> <INDENT> features = util.Counter() <NEW_LINE> successor = self.getSuccessor(gameState, action) <NEW_LINE> myState = successor.getAgentState(self.index) <NEW_LINE> myPos = myState.getPosition() <NEW_LINE> features['onDefense'] = 1 <NEW_LINE> if myState.isPacman: features['onDefense'] = 0 <NEW_LINE> enemies = [successor.getAgentState(i) for i in self.getOpponents(successor)] <NEW_LINE> invaders = [a for a in enemies if a.isPacman and a.getPosition() != None] <NEW_LINE> features['numInvaders'] = len(invaders) <NEW_LINE> if len(invaders) > 0: <NEW_LINE> <INDENT> dists = [self.getMazeDistance(myPos, a.getPosition(), successor) for a in invaders] <NEW_LINE> features['invaderDistance'] = min(dists) <NEW_LINE> <DEDENT> if action == Directions.STOP: features['stop'] = 1 <NEW_LINE> elif action == Directions.LASER: features['laser'] = 1 <NEW_LINE> rev = Directions.REVERSE[gameState.getAgentState(self.index).configuration.direction] <NEW_LINE> if action == rev: features['reverse'] = 1 <NEW_LINE> return features <NEW_LINE> <DEDENT> def getWeights(self, gameState, action): <NEW_LINE> <INDENT> return {'numInvaders': -1000, 'onDefense': 100, 'invaderDistance': -10, 'stop': -100, 'reverse': -2, 'laser': -5} | A reflex agent that keeps its side Pacman-free. Again,
this is to give you an idea of what a defensive agent
could be like. It is not the best or only way to make
such an agent. | 6259905216aa5153ce4019c2 |
class Atome(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.nom="" <NEW_LINE> self.symbole="" <NEW_LINE> self.valence=0 <NEW_LINE> self.indice=0 <NEW_LINE> self.etage_ox=[] <NEW_LINE> self.latex=" latex " <NEW_LINE> self.formule=" formule " | Un atome est défini par un nom, un symbole et une valence | 6259905255399d3f056279f6 |
class SelectableConfig(AppConfig): <NEW_LINE> <INDENT> name = 'selectable' <NEW_LINE> def ready(self): <NEW_LINE> <INDENT> from . import registry <NEW_LINE> registry.autodiscover() | App configuration for django-selectable. | 62599052ac7a0e7691f739b8 |
class DictType(Type): <NEW_LINE> <INDENT> def __init__(self, of_key, of_value): <NEW_LINE> <INDENT> super(DictType, self).__init__( qualifiers=of_key.qualifiers.union(of_value.qualifiers), of_key=of_key, of_value=of_value ) <NEW_LINE> <DEDENT> def iscombined(self): <NEW_LINE> <INDENT> return any(of.iscombined() for of in (self.of_key, self.of_value)) <NEW_LINE> <DEDENT> def generate(self, ctx): <NEW_LINE> <INDENT> return 'pythonic::types::dict<{0},{1}>'.format( ctx(self.of_key).generate(ctx), ctx(self.of_value).generate(ctx)) | Type holding a dict of stuff of the same key and value type
>>> DictType(NamedType('int'), NamedType('float'))
pythonic::types::dict<int,float> | 62599052e5267d203ee6cdc6 |
class PasswordExpiredException(SuiteException): <NEW_LINE> <INDENT> pass | Exception raised when password of logged user is expired. | 6259905273bcbd0ca4bcb767 |
class GroupSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> def to_representation(self, instance): <NEW_LINE> <INDENT> ret = super(GroupSerializer, self).to_representation(instance) <NEW_LINE> ret['userCnt'] = instance.user_set.all().count() <NEW_LINE> return ret <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> model = Group <NEW_LINE> fields = ("id", "name") | group序列化类 | 62599052009cb60464d02a16 |
class RepoGroupAPI(PulpAPI): <NEW_LINE> <INDENT> PATH = 'v2/repo_groups/' <NEW_LINE> def repo_groups(self): <NEW_LINE> <INDENT> return self.server.GET(self.PATH) <NEW_LINE> <DEDENT> def create(self, id, display_name, description, notes): <NEW_LINE> <INDENT> data = {'id': id, 'display_name': display_name, 'description': description, 'notes': notes,} <NEW_LINE> return self.server.POST(self.PATH, data) <NEW_LINE> <DEDENT> def create_and_configure(self, group_id, display_name, description, notes, distributors=None): <NEW_LINE> <INDENT> data = { 'id': group_id, 'display_name': display_name, 'description': description, 'notes': notes, 'distributors': distributors, } <NEW_LINE> return self.server.POST(self.PATH, data) <NEW_LINE> <DEDENT> def repo_group(self, id): <NEW_LINE> <INDENT> path = self.PATH + ('%s/' % id) <NEW_LINE> return self.server.GET(path) <NEW_LINE> <DEDENT> def delete(self, id): <NEW_LINE> <INDENT> path = self.PATH + '%s/' % id <NEW_LINE> return self.server.DELETE(path) <NEW_LINE> <DEDENT> def update(self, id, delta): <NEW_LINE> <INDENT> path = self.PATH + '%s/' % id <NEW_LINE> return self.server.PUT(path, delta) | Connection class to access consumer specific calls | 6259905245492302aabfd9b1 |
class BlogSpider(Spider): <NEW_LINE> <INDENT> start_urls = ['http://www.ruanyifeng.com/blog/archives.html'] <NEW_LINE> request_config = { 'RETRIES': 3, 'DELAY': 0, 'TIMEOUT': 20 } <NEW_LINE> concurrency = 10 <NEW_LINE> async def parse(self, res): <NEW_LINE> <INDENT> items = await MyItem.get_items(html=res.html) <NEW_LINE> for item in items: <NEW_LINE> <INDENT> yield Request( item.href, callback=self.parse_item ) <NEW_LINE> <DEDENT> <DEDENT> async def parse_item(self, res): <NEW_LINE> <INDENT> print("lalala") | 针对博客源 http://www.ruanyifeng.com/blog/archives.html 的爬虫
这里为了模拟ua,引入了一个ruia的第三方扩展
- ruia-ua: https://github.com/howie6879/ruia-ua
- pipenv install ruia-ua
- 此扩展会自动为每一次请求随机添加 User-Agent | 6259905263b5f9789fe8664a |
class Kwarwp(): <NEW_LINE> <INDENT> GLIFOS = { "&": "https://i.imgur.com/dZQ8liT.jpg", "^": "https://imgur.com/8jMuupz.png", ".": "https://i.imgur.com/npb9Oej.png", "_": "https://i.imgur.com/sGoKfvs.jpg", "#": "https://imgur.com/ldI7IbK.png", "@": "https://imgur.com/tLLVjfN.png", "~": "https://i.imgur.com/UAETaiP.gif", "*": "https://i.imgur.com/PfodQmT.gif", "%": "https://i.imgur.com/uwYPNlz.png" } <NEW_LINE> def __init__(self, vitollino=None, mapa=MAPA_CERCA, medidas={}): <NEW_LINE> <INDENT> self.v = vitollino() <NEW_LINE> mapa = mapa.split() <NEW_LINE> self.lado, self.col = 100, len(mapa[0]) <NEW_LINE> self.cena = self.cria(mapa=mapa) if vitollino else None <NEW_LINE> <DEDENT> def cria(self, mapa=" "): <NEW_LINE> <INDENT> lado = self.lado <NEW_LINE> cena = self.v.c(self.GLIFOS["_"]) <NEW_LINE> ceu = self.v.a(self.GLIFOS["~"], w=lado*self.col, h=lado, x=0, y=0, cena=cena) <NEW_LINE> sol = self.v.a(self.GLIFOS["*"], w=60, h=60, x=0, y=40, cena=cena) <NEW_LINE> [self.cria_elemento( x=i*lado, y=j*lado+lado, cena=cena) for j, linha in enumerate(mapa) for i, imagem in enumerate(linha)] <NEW_LINE> cena.vai() <NEW_LINE> return cena <NEW_LINE> <DEDENT> def cria_elemento(self, x, y, cena): <NEW_LINE> <INDENT> lado = self.lado <NEW_LINE> return self.v.a(self.GLIFOS[imagem], w=lado, h=lado, x=i*lado, y=j*lado+lado, cena=cena) | Arena onde os desafios ocorrem.
:param vitollino: Empacota o engenho de jogo Vitollino.
:param mapa: Um texto representando o mapa do desafio. | 6259905210dbd63aa1c720bc |
class XNDefenseBundle: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.ru = 0 <NEW_LINE> self.ll = 0 <NEW_LINE> self.tl = 0 <NEW_LINE> self.gauss = 0 <NEW_LINE> self.ion = 0 <NEW_LINE> self.plasma = 0 <NEW_LINE> self.small_dome = 0 <NEW_LINE> self.big_dome = 0 <NEW_LINE> self.defender_rocket = 0 <NEW_LINE> self.attack_rocket = 0 <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> ret = '' <NEW_LINE> if self.ru > 0: <NEW_LINE> <INDENT> ret += 'RU: {0} '.format(self.ru) <NEW_LINE> <DEDENT> if self.ll > 0: <NEW_LINE> <INDENT> ret += 'LL: {0} '.format(self.ll) <NEW_LINE> <DEDENT> if self.tl > 0: <NEW_LINE> <INDENT> ret += 'TL: {0} '.format(self.tl) <NEW_LINE> <DEDENT> if self.gauss > 0: <NEW_LINE> <INDENT> ret += 'GAUSS: {0} '.format(self.gauss) <NEW_LINE> <DEDENT> if self.ion > 0: <NEW_LINE> <INDENT> ret += 'ION: {0} '.format(self.ion) <NEW_LINE> <DEDENT> if self.plasma > 0: <NEW_LINE> <INDENT> ret += 'PLASMA: {0} '.format(self.plasma) <NEW_LINE> <DEDENT> if self.small_dome > 0: <NEW_LINE> <INDENT> ret += 'MSK: {0} '.format(self.small_dome) <NEW_LINE> <DEDENT> if self.big_dome > 0: <NEW_LINE> <INDENT> ret += 'BSK: {0} '.format(self.big_dome) <NEW_LINE> <DEDENT> if self.defender_rocket > 0: <NEW_LINE> <INDENT> ret += 'Defender Rocket: {0} '.format(self.defender_rocket) <NEW_LINE> <DEDENT> if self.attack_rocket > 0: <NEW_LINE> <INDENT> ret += 'MPR: {0} '.format(self.attack_rocket) <NEW_LINE> <DEDENT> return ret.strip() | holds all info about planet's defenses count | 62599052507cdc57c63a627d |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.