code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class EntityId(object): <NEW_LINE> <INDENT> swagger_types = { 'id': 'str', 'entity_type': 'str' } <NEW_LINE> attribute_map = { 'id': 'id', 'entity_type': 'entityType' } <NEW_LINE> def __init__(self, id=None, entity_type=None): <NEW_LINE> <INDENT> self._id = None <NEW_LINE> self._entity_type = None <NEW_LINE> self.discriminator = None <NEW_LINE> self.id = id <NEW_LINE> self.entity_type = entity_type <NEW_LINE> <DEDENT> @property <NEW_LINE> def id(self): <NEW_LINE> <INDENT> return self._id <NEW_LINE> <DEDENT> @id.setter <NEW_LINE> def id(self, id): <NEW_LINE> <INDENT> if id is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `id`, must not be `None`") <NEW_LINE> <DEDENT> self._id = id <NEW_LINE> <DEDENT> @property <NEW_LINE> def entity_type(self): <NEW_LINE> <INDENT> return self._entity_type <NEW_LINE> <DEDENT> @entity_type.setter <NEW_LINE> def entity_type(self, entity_type): <NEW_LINE> <INDENT> if entity_type is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `entity_type`, must not be `None`") <NEW_LINE> <DEDENT> allowed_values = ["ALARM", "API_USAGE_STATE", "ASSET", "CUSTOMER", "DASHBOARD", "DEVICE", "DEVICE_PROFILE", "EDGE", "ENTITY_VIEW", "OTA_PACKAGE", "RPC", "RULE_CHAIN", "RULE_NODE", "TB_RESOURCE", "TENANT", "TENANT_PROFILE", "USER", "WIDGETS_BUNDLE", "WIDGET_TYPE"] <NEW_LINE> if entity_type not in allowed_values: <NEW_LINE> <INDENT> raise ValueError( "Invalid value for `entity_type` ({0}), must be one of {1}" .format(entity_type, allowed_values) ) <NEW_LINE> <DEDENT> self._entity_type = entity_type <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> if issubclass(EntityId, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, EntityId): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | NOTE: This class is auto generated by the swagger code generator program.
from tb_rest_client.api_client import ApiClient
Do not edit the class manually.
| 62598fa897e22403b383ae53 |
class User(AbstractBaseUser, PermissionsMixin): <NEW_LINE> <INDENT> email = models.EmailField(max_length=255, unique=True) <NEW_LINE> name = models.CharField(max_length=255) <NEW_LINE> is_active = models.BooleanField(default=True) <NEW_LINE> is_staff = models.BooleanField(default=False) <NEW_LINE> objects = UserManager() <NEW_LINE> USERNAME_FIELD = 'email' | custom user model that supports using email insteadof username | 62598fa88c0ade5d55dc3634 |
class XslTransformation(Document): <NEW_LINE> <INDENT> name = fields.StringField( blank=False, unique=True, validation=not_empty_or_whitespaces ) <NEW_LINE> filename = fields.StringField(blank=False, validation=not_empty_or_whitespaces) <NEW_LINE> content = fields.StringField(blank=False) <NEW_LINE> meta = {"allow_inheritance": True} <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_all(): <NEW_LINE> <INDENT> return XslTransformation.objects.all() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_by_id_list(list_id): <NEW_LINE> <INDENT> return XslTransformation.objects(pk__in=list_id) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_by_name(xslt_name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return XslTransformation.objects.get(name=xslt_name) <NEW_LINE> <DEDENT> except mongoengine_errors.DoesNotExist as e: <NEW_LINE> <INDENT> raise exceptions.DoesNotExist(str(e)) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> raise exceptions.ModelError(str(e)) <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def get_by_id(xslt_id): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return XslTransformation.objects.get(pk=str(xslt_id)) <NEW_LINE> <DEDENT> except mongoengine_errors.DoesNotExist as e: <NEW_LINE> <INDENT> raise exceptions.DoesNotExist(str(e)) <NEW_LINE> <DEDENT> except Exception as ex: <NEW_LINE> <INDENT> raise exceptions.ModelError(str(ex)) <NEW_LINE> <DEDENT> <DEDENT> def save_object(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.save() <NEW_LINE> <DEDENT> except mongoengine_errors.NotUniqueError as e: <NEW_LINE> <INDENT> raise exceptions.NotUniqueError(str(e)) <NEW_LINE> <DEDENT> except Exception as ex: <NEW_LINE> <INDENT> raise exceptions.ModelError(str(ex)) <NEW_LINE> <DEDENT> <DEDENT> def clean(self): <NEW_LINE> <INDENT> self.name = self.name.strip() <NEW_LINE> self.filename = self.filename.strip() | XslTransformation object | 62598fa856b00c62f0fb27fa |
class adjustVerticalMetrics(hDialog): <NEW_LINE> <INDENT> ascender_min = 1 <NEW_LINE> capheight_min = 1 <NEW_LINE> xheight_min = 1 <NEW_LINE> descender_min = 1 <NEW_LINE> column_1 = 80 <NEW_LINE> column_2 = 200 <NEW_LINE> column_3 = 45 <NEW_LINE> moveX = 0 <NEW_LINE> moveY = 0 <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.title = "vmetrics" <NEW_LINE> self.height = (self.spinner_height*5) + (self.padding_y*6) + 1 <NEW_LINE> self.w = HUDFloatingWindow((self.width, self.height), self.title) <NEW_LINE> x = 0 <NEW_LINE> y = self.padding_y <NEW_LINE> self.w.emsquare = Spinner( (x, y), default='1000', scale=1, integer=True, label='ems') <NEW_LINE> y += self.spinner_height + self.padding_y <NEW_LINE> self.w.xheight = Spinner( (x, y), default='500', scale=1, integer=True, label='xht') <NEW_LINE> y += self.spinner_height + self.padding_y <NEW_LINE> self.w.capheight = Spinner( (x, y), default='700', scale=1, integer=True, label='cap') <NEW_LINE> y += self.spinner_height + self.padding_y <NEW_LINE> self.w.ascender = Spinner( (x, y), default='800', scale=1, integer=True, label='asc') <NEW_LINE> y += self.spinner_height + self.padding_y <NEW_LINE> self.w.descender = Spinner( (x, y), default='200', scale=1, integer=True, label='dsc') <NEW_LINE> y += self.spinner_height + self.padding_y <NEW_LINE> self.w.open() | A dialog to adjust the vertical metrics of the font.
.. image:: imgs/font/adjust-vmetrics.png | 62598fa832920d7e50bc5f9b |
class ToggleDisplayMode(gui_base.GuiCommandNeedsSelection): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(ToggleDisplayMode, self).__init__(name=_tr("Toggle display mode")) <NEW_LINE> <DEDENT> def GetResources(self): <NEW_LINE> <INDENT> _menu = "Toggle normal/wireframe display" <NEW_LINE> _tip = ("Switches the display mode of selected objects " "from flatlines to wireframe and back.\n" "This is helpful to quickly visualize objects " "that are hidden by other objects.\n" "This is intended to be used with closed shapes " "and solids, and doesn't affect open wires.") <NEW_LINE> d = {'Pixmap': 'Draft_SwitchMode', 'Accel': "Shift+Space", 'MenuText': QT_TRANSLATE_NOOP("Draft_ToggleDisplayMode", _menu), 'ToolTip': QT_TRANSLATE_NOOP("Draft_ToggleDisplayMode", _tip)} <NEW_LINE> return d <NEW_LINE> <DEDENT> def Activated(self): <NEW_LINE> <INDENT> super(ToggleDisplayMode, self).Activated() <NEW_LINE> for obj in Gui.Selection.getSelection(): <NEW_LINE> <INDENT> if obj.ViewObject.DisplayMode == "Flat Lines": <NEW_LINE> <INDENT> if "Wireframe" in obj.ViewObject.listDisplayModes(): <NEW_LINE> <INDENT> obj.ViewObject.DisplayMode = "Wireframe" <NEW_LINE> <DEDENT> <DEDENT> elif obj.ViewObject.DisplayMode == "Wireframe": <NEW_LINE> <INDENT> if "Flat Lines" in obj.ViewObject.listDisplayModes(): <NEW_LINE> <INDENT> obj.ViewObject.DisplayMode = "Flat Lines" | GuiCommand for the Draft_ToggleDisplayMode tool.
Switches the display mode of selected objects from flatlines
to wireframe and back.
It inherits `GuiCommandNeedsSelection` to only be available
when there is a document and a selection.
See this class for more information. | 62598fa9cc0a2c111447af57 |
class Dict(dict): <NEW_LINE> <INDENT> def __init__(self, names=(), values=(), **kw): <NEW_LINE> <INDENT> super(Dict, self).__init__(**kw) <NEW_LINE> for k, v in zip(names, values): <NEW_LINE> <INDENT> self[k] = v <NEW_LINE> <DEDENT> <DEDENT> def __getattr__(self, key): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self[key] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise AttributeError(r"'Dict' object has no attribute %s" % key) <NEW_LINE> <DEDENT> <DEDENT> def __setattr__(self, key, value): <NEW_LINE> <INDENT> self[key] = value | Simple dict but support access as x.y style | 62598fa967a9b606de545f12 |
class ProjectDetail(generics.RetrieveUpdateDestroyAPIView): <NEW_LINE> <INDENT> queryset = models.Project.objects.all() <NEW_LINE> serializer_class = serializers.ProjectDetailSerializer <NEW_LINE> permission_classes = (rest_permissions.IsAuthenticated, permissions.IsRepOrSecyAndClubMemberReadOnlyProject) | View to allow retrieval, updation and deletion of a project based on appropriate permissions | 62598fa9167d2b6e312b6eb7 |
class PDAQRun(object): <NEW_LINE> <INDENT> TSTRSRC = None <NEW_LINE> MAX_TIMEOUTS = 6 <NEW_LINE> def __init__(self, run_cfg_name, duration, num_runs=1, flasher_data=None, has_doms=False): <NEW_LINE> <INDENT> self.__run_cfg_name = run_cfg_name <NEW_LINE> self.__duration = duration <NEW_LINE> self.__num_runs = num_runs <NEW_LINE> self.__has_doms = has_doms <NEW_LINE> if flasher_data is None: <NEW_LINE> <INDENT> self.__flasher_data = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.__flasher_data = [] <NEW_LINE> for pair in flasher_data: <NEW_LINE> <INDENT> if pair[0] is None: <NEW_LINE> <INDENT> path = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tstdir = self.test_resource_path <NEW_LINE> path = FlasherScript.find_data_file(pair[0], basedir=tstdir) <NEW_LINE> <DEDENT> self.__flasher_data.append((path, pair[1])) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @property <NEW_LINE> def cluster_config(self): <NEW_LINE> <INDENT> return self.__run_cfg_name <NEW_LINE> <DEDENT> @property <NEW_LINE> def has_doms(self): <NEW_LINE> <INDENT> return self.__has_doms <NEW_LINE> <DEDENT> @classproperty <NEW_LINE> def test_resource_path(cls): <NEW_LINE> <INDENT> if cls.TSTRSRC is None: <NEW_LINE> <INDENT> cls.TSTRSRC = os.path.join(PDAQ_HOME, "src", "test", "resources") <NEW_LINE> <DEDENT> return cls.TSTRSRC <NEW_LINE> <DEDENT> def run(self, runmgr, quick, cluster_desc=None, ignore_db=False, verbose=False): <NEW_LINE> <INDENT> flasher_delay = 120 <NEW_LINE> if not quick: <NEW_LINE> <INDENT> duration = self.__duration <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self.__duration > 3600: <NEW_LINE> <INDENT> duration = self.__duration / 120 <NEW_LINE> <DEDENT> elif self.__duration > 1200: <NEW_LINE> <INDENT> duration = self.__duration / 10 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> duration = self.__duration <NEW_LINE> <DEDENT> flasher_delay = 30 <NEW_LINE> <DEDENT> timeouts = 0 <NEW_LINE> try: <NEW_LINE> <INDENT> runmgr.run(self.__run_cfg_name, self.__run_cfg_name, duration, num_runs=self.__num_runs, flasher_data=self.__flasher_data, flasher_delay=flasher_delay, cluster_desc=cluster_desc, ignore_db=ignore_db, verbose=verbose) <NEW_LINE> timeouts = 0 <NEW_LINE> <DEDENT> except SystemExit: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> except LiveTimeoutException: <NEW_LINE> <INDENT> traceback.print_exc() <NEW_LINE> timeouts += 1 <NEW_LINE> if timeouts > self.MAX_TIMEOUTS: <NEW_LINE> <INDENT> raise SystemExit("I3Live seems to have gone away") <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> traceback.print_exc() | Description of a pDAQ run | 62598fa91b99ca400228f4d3 |
class Spectrum(object): <NEW_LINE> <INDENT> def __init__(self, wave, flux, wave_unit=u.AA, unit=(u.erg / u.s / u.cm**2 / u.AA)): <NEW_LINE> <INDENT> self.wave = np.asarray(wave, dtype=np.float64) <NEW_LINE> self.flux = np.asarray(flux, dtype=np.float64) <NEW_LINE> if self.wave.shape != self.flux.shape: <NEW_LINE> <INDENT> raise ValueError('shape of wavelength and flux must match') <NEW_LINE> <DEDENT> if self.wave.ndim != 1: <NEW_LINE> <INDENT> raise ValueError('only 1-d arrays supported') <NEW_LINE> <DEDENT> if wave_unit != u.AA: <NEW_LINE> <INDENT> self.wave = wave_unit.to(u.AA, self.wave, u.spectral()) <NEW_LINE> <DEDENT> self._wave_unit = u.AA <NEW_LINE> if unit != FLAMBDA_UNIT: <NEW_LINE> <INDENT> self.flux = unit.to(FLAMBDA_UNIT, self.flux, u.spectral_density(u.AA, self.wave)) <NEW_LINE> <DEDENT> self._unit = FLAMBDA_UNIT <NEW_LINE> self._tck = splrep(self.wave, self.flux, k=1) <NEW_LINE> <DEDENT> def bandflux(self, band): <NEW_LINE> <INDENT> band = get_bandpass(band) <NEW_LINE> if (band.minwave() < self.wave[0] or band.maxwave() > self.wave[-1]): <NEW_LINE> <INDENT> raise ValueError('bandpass {0!r:s} [{1:.6g}, .., {2:.6g}] ' 'outside spectral range [{3:.6g}, .., {4:.6g}]' .format(band.name, band.minwave(), band.maxwave(), self.wave[0], self.wave[-1])) <NEW_LINE> <DEDENT> wave, dwave = integration_grid(band.minwave(), band.maxwave(), SPECTRUM_BANDFLUX_SPACING) <NEW_LINE> trans = band(wave) <NEW_LINE> f = splev(wave, self._tck, ext=1) <NEW_LINE> return np.sum(wave * trans * f) * dwave / HC_ERG_AA | A spectrum, representing wavelength and spectral density values.
Parameters
----------
wave : list_like
Wavelength values.
flux : list_like
Spectral flux density values.
wave_unit : `~astropy.units.Unit`
Unit on wavelength.
unit : `~astropy.units.BaseUnit`
For now, only units with flux density in energy (not photon counts). | 62598fa966673b3332c30311 |
class RedactedRecordStatusType(EnumBase): <NEW_LINE> <INDENT> WITHHELD = "Withheld" | Enumeration of the redacted-record-status types. | 62598fa96aa9bd52df0d4e0f |
class ReadOnlySpooledTemporaryFile(MinioStorageFile, ReadOnlyMixin): <NEW_LINE> <INDENT> max_memory_size: int = 1024 * 1024 * 10 <NEW_LINE> def __init__( self, name: str, mode: str, storage: "Storage", max_memory_size: T.Optional[int] = None, **kwargs, ): <NEW_LINE> <INDENT> if mode.find("w") > -1: <NEW_LINE> <INDENT> raise NotImplementedError( "ReadOnlySpooledTemporaryFile storage only support read modes" ) <NEW_LINE> <DEDENT> if max_memory_size is not None: <NEW_LINE> <INDENT> self.max_memory_size = max_memory_size <NEW_LINE> <DEDENT> super().__init__(name, mode, storage) <NEW_LINE> <DEDENT> def _get_file(self): <NEW_LINE> <INDENT> if self._file is None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> obj = self._storage.client.get_object( self._storage.bucket_name, self.name ) <NEW_LINE> self._file = tempfile.SpooledTemporaryFile( max_size=self.max_memory_size ) <NEW_LINE> for d in obj.stream(amt=1024 * 1024): <NEW_LINE> <INDENT> self._file.write(d) <NEW_LINE> <DEDENT> self._file.seek(0) <NEW_LINE> return self._file <NEW_LINE> <DEDENT> except merr.ResponseError as error: <NEW_LINE> <INDENT> raise minio_error(f"File {self.name} does not exist", error) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> obj.release_conn() <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logger.error(str(e)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return self._file <NEW_LINE> <DEDENT> def _set_file(self, value): <NEW_LINE> <INDENT> self._file = value <NEW_LINE> <DEDENT> file = property(_get_file, _set_file) <NEW_LINE> def close(self): <NEW_LINE> <INDENT> if self._file is not None: <NEW_LINE> <INDENT> self._file.close() <NEW_LINE> self._file = None | A django File class which buffers the minio object into a local
SpooledTemporaryFile. | 62598fa9498bea3a75a57a64 |
class CreateReferralPromoCode(Endpoint): <NEW_LINE> <INDENT> ENDPOINTS = [(Verbs.POST, 'resources/referral_promocode')] <NEW_LINE> ALL_DATA = {'referralPromoCode'} <NEW_LINE> REQUIRED_DATA = {'referralPromoCode'} <NEW_LINE> OPTIONAL_DATA = set() <NEW_LINE> DATA_TYPES = {'referralPromoCode': cobjects.ReferralPromoCode} <NEW_LINE> RETURNS = {'referralPromoCode': cobjects.ReferralPromoCode} | FCO REST API createReferralPromoCode endpoint.
This function will return a the newly created Referral promocode
Object.
Remarks:
On an exception, the referral promocode is not created.
Data (type name (required): description):
cobjects.ReferralPromoCode referralPromoCode (T):
The ReferralPromoCode object that has to be created
Returns (type name: description):
cobjects.ReferralPromoCode referralPromoCode:
The ReferralPromoCode object that has been created | 62598fa9090684286d59367f |
class NotEnoughError(Error): <NEW_LINE> <INDENT> code = 400 <NEW_LINE> @property <NEW_LINE> def title(self): <NEW_LINE> <INDENT> return _('Resource NotEnough') <NEW_LINE> <DEDENT> @property <NEW_LINE> def message_format(self): <NEW_LINE> <INDENT> return _('detail: %(resource)s not enough') | 资源不足异常 | 62598fa932920d7e50bc5f9c |
class PoolAdder(object): <NEW_LINE> <INDENT> def __init__(self, upper_threshold): <NEW_LINE> <INDENT> self._upper_threshold = upper_threshold <NEW_LINE> self._conn = RedisClient() <NEW_LINE> self._checker = ValidityChecker() <NEW_LINE> self._crawler = ProxyCrawl() <NEW_LINE> <DEDENT> def is_upper_threshold(self): <NEW_LINE> <INDENT> if self._conn.queueLen >= self._upper_threshold: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def pool_add_proxy(self): <NEW_LINE> <INDENT> logging.info('代理添加器正在运行') <NEW_LINE> proxy_count = 0 <NEW_LINE> while not self.is_upper_threshold(): <NEW_LINE> <INDENT> for callback in self._crawler.__CrawlFunc__: <NEW_LINE> <INDENT> raw_proxies = self._crawler.get_raw_proxies(callback) <NEW_LINE> self._checker.set_raw_proxies(raw_proxies) <NEW_LINE> self._checker.check() <NEW_LINE> proxy_count += len(raw_proxies) <NEW_LINE> if self.is_upper_threshold(): <NEW_LINE> <INDENT> logging.info("代理池达到阈值,停止爬虫") <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if proxy_count == 0: <NEW_LINE> <INDENT> raise ResourceDepletionError | 代理添加器 | 62598fa9097d151d1a2c0f70 |
class Network(_messages.Message): <NEW_LINE> <INDENT> forwardedPorts = _messages.StringField(1, repeated=True) <NEW_LINE> instanceTag = _messages.StringField(2) <NEW_LINE> name = _messages.StringField(3) <NEW_LINE> subnetworkName = _messages.StringField(4) | Extra network settings. Only applicable in the App Engine flexible
environment.
Fields:
forwardedPorts: List of ports, or port pairs, to forward from the virtual
machine to the application container. Only applicable in the App Engine
flexible environment.
instanceTag: Tag to apply to the VM instance during creation. for Only
applicable in the App Engine flexible environment.
name: Google Compute Engine network where the virtual machines are
created. Specify the short name, not the resource path.Defaults to
default.
subnetworkName: Google Cloud Platform sub-network where the virtual
machines are created. Specify the short name, not the resource path.If a
subnetwork name is specified, a network name will also be required
unless it is for the default network. If the network the VM instance is
being created in is a Legacy network, then the IP address is allocated
from the IPv4Range. If the network the VM instance is being created in
is an auto Subnet Mode Network, then only network name should be
specified (not the subnetwork_name) and the IP address is created from
the IPCidrRange of the subnetwork that exists in that zone for that
network. If the network the VM instance is being created in is a custom
Subnet Mode Network, then the subnetwork_name must be specified and the
IP address is created from the IPCidrRange of the subnetwork.If
specified, the subnetwork must exist in the same region as the App
Engine flexible environment application. | 62598fa9d58c6744b42dc279 |
class getVmcInfoListByRoomIds_args: <NEW_LINE> <INDENT> thrift_spec = ( None, (1, TType.LIST, 'roomIdList', (TType.I32,None), None, ), ) <NEW_LINE> def __init__(self, roomIdList=None,): <NEW_LINE> <INDENT> self.roomIdList = roomIdList <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 1: <NEW_LINE> <INDENT> if ftype == TType.LIST: <NEW_LINE> <INDENT> self.roomIdList = [] <NEW_LINE> (_etype68, _size65) = iprot.readListBegin() <NEW_LINE> for _i69 in xrange(_size65): <NEW_LINE> <INDENT> _elem70 = iprot.readI32(); <NEW_LINE> self.roomIdList.append(_elem70) <NEW_LINE> <DEDENT> iprot.readListEnd() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('getVmcInfoListByRoomIds_args') <NEW_LINE> if self.roomIdList is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('roomIdList', TType.LIST, 1) <NEW_LINE> oprot.writeListBegin(TType.I32, len(self.roomIdList)) <NEW_LINE> for iter71 in self.roomIdList: <NEW_LINE> <INDENT> oprot.writeI32(iter71) <NEW_LINE> <DEDENT> oprot.writeListEnd() <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> value = 17 <NEW_LINE> value = (value * 31) ^ hash(self.roomIdList) <NEW_LINE> return value <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.items()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) | Attributes:
- roomIdList | 62598fa956ac1b37e6302133 |
class PatternMatchingProblem(Problem): <NEW_LINE> <INDENT> def successors(self, node): <NEW_LINE> <INDENT> sub = dict(node.state) <NEW_LINE> terms, f_terms, index = node.extra <NEW_LINE> p_terms = [(len(index[subst(sub, t)]) if t in index else 0, len(necessary), random(), t) for necessary in terms if meets_requirements(necessary, sub) for t in terms[necessary] if not is_negated_term(t)] <NEW_LINE> if len(p_terms) == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> p_terms.sort() <NEW_LINE> term = p_terms[0][3] <NEW_LINE> key = index_key(subst(sub, term)) <NEW_LINE> if key not in index: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> facts = [f for f in index[key]] <NEW_LINE> shuffle(facts) <NEW_LINE> for fact in facts: <NEW_LINE> <INDENT> new_sub = unify(term, fact, sub) <NEW_LINE> if new_sub is None: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> new_terms = update_terms(terms, f_terms, new_sub, index) <NEW_LINE> if new_terms is None: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> yield Node(frozenset(new_sub.items()), node, None, 0, (new_terms, f_terms, index)) <NEW_LINE> <DEDENT> <DEDENT> def goal_test(self, node, goal): <NEW_LINE> <INDENT> terms, _, _ = node.extra <NEW_LINE> return not any(True for necessary in terms for t in terms[necessary] if not is_negated_term(t)) | Used to unify a complex first-order pattern. Supports negations in
patterns using negation-as-failure. | 62598fa93617ad0b5ee0609b |
class TypeError(StandardError): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def __new__(S, *more): <NEW_LINE> <INDENT> pass | Inappropriate argument type. | 62598fa9a219f33f346c675e |
class CmptIncrMoveRad(Cmpt): <NEW_LINE> <INDENT> def __init__( self, name, annuli, defval=0., defouter=0., minval=-5., maxval=5., nradbins=5, log=False): <NEW_LINE> <INDENT> Cmpt.__init__(self, name, annuli) <NEW_LINE> self.defval = defval <NEW_LINE> self.defouter = defouter <NEW_LINE> self.minval = minval <NEW_LINE> self.maxval = maxval <NEW_LINE> self.log = log <NEW_LINE> self.nradbins = nradbins <NEW_LINE> self.valparnames = ['%s_%03i' % (self.name, i) for i in range(nradbins)] <NEW_LINE> self.radparnames = ['%s_r_%03i' % (self.name, i) for i in range(nradbins)] <NEW_LINE> <DEDENT> def defPars(self): <NEW_LINE> <INDENT> valspars = { n: Param(self.defval, minval=self.minval, maxval=self.maxval) for n in self.valparnames } <NEW_LINE> rlogannuli = N.log10(self.annuli.midpt_cm / kpc_cm) <NEW_LINE> rlog = N.linspace(rlogannuli[0], rlogannuli[-1], self.nradbins) <NEW_LINE> rpars = { n: Param(r, minval=rlogannuli[0], maxval=rlogannuli[-1], frozen=True) for n, r in zip(self.radparnames, rlog) } <NEW_LINE> valspars.update(rpars) <NEW_LINE> valspars['%s_outer' % self.name] = Param( self.defouter, minval=self.minval, maxval=self.maxval) <NEW_LINE> return valspars <NEW_LINE> <DEDENT> def computeProf(self, pars): <NEW_LINE> <INDENT> rvals = N.array([pars[n].v for n in self.radparnames]) <NEW_LINE> vvals = N.array([pars[n].v for n in self.valparnames]) <NEW_LINE> sortidxs = N.argsort(rvals) <NEW_LINE> rvals = rvals[sortidxs] <NEW_LINE> vvals = vvals[sortidxs] <NEW_LINE> loggradprof = N.interp(self.annuli.massav_logkpc, rvals, vvals) <NEW_LINE> gradprof = 10**loggradprof <NEW_LINE> logekpc = self.annuli.edges_logkpc <NEW_LINE> logwidthkpc = logekpc[1:] - logekpc[:-1] <NEW_LINE> if not N.isfinite(logwidthkpc[0]): <NEW_LINE> <INDENT> ekpc = self.annuli.edges_kpc <NEW_LINE> logwidthkpc[0] = logekpc[1] - 0.5*N.log10(ekpc[0]+ekpc[1]) <NEW_LINE> <DEDENT> deltas = gradprof * logwidthkpc <NEW_LINE> outer = 10**pars['%s_outer' % self.name].v <NEW_LINE> prof = N.cumsum(deltas[::-1])[::-1] + outer <NEW_LINE> return prof | A profile with control points, using interpolation to find the
values in between.
The radii of the control points are model parameters XX_r_YYY (in
log kpc), where YYY is the index of the annulus 000...999. The y
values (XX_YYY) are gradients in log (cm^-3 log kpc^-1).
This model forces the density profile to increase inwards. | 62598fa92ae34c7f260ab029 |
class SimTypeLength(SimTypeInt): <NEW_LINE> <INDENT> _fields = SimTypeInt._fields + ('addr', 'length') <NEW_LINE> def __init__(self, arch, addr=None, length=None, label=None): <NEW_LINE> <INDENT> SimTypeInt.__init__(self, arch.bits, False, label=label) <NEW_LINE> self.addr = addr <NEW_LINE> self.length = length <NEW_LINE> self.signed = False <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'size_t' | SimTypeLength is a type that specifies the length of some buffer in memory. | 62598fa90c0af96317c562ca |
class ContributorsIndexer(ValueIndexer): <NEW_LINE> <INDENT> indexName = 'workitem-contributors' <NEW_LINE> @property <NEW_LINE> def value(self): <NEW_LINE> <INDENT> contributors = getattr(self.context, 'contributor', None) <NEW_LINE> if contributors: <NEW_LINE> <INDENT> return (contributors,) | Indexer for work items with standard parameters. | 62598fa967a9b606de545f13 |
class Spline(Annotation): <NEW_LINE> <INDENT> group = param.String(default='Spline', constant=True) <NEW_LINE> def __init__(self, spline_points, **params): <NEW_LINE> <INDENT> super().__init__(spline_points, **params) <NEW_LINE> <DEDENT> def clone(self, data=None, shared_data=True, new_type=None, *args, **overrides): <NEW_LINE> <INDENT> return Element2D.clone(self, data, shared_data, new_type, *args, **overrides) <NEW_LINE> <DEDENT> def dimension_values(self, dimension, expanded=True, flat=True): <NEW_LINE> <INDENT> index = self.get_dimension_index(dimension) <NEW_LINE> if index in [0, 1]: <NEW_LINE> <INDENT> return np.array([point[index] for point in self.data[0]]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return super().dimension_values(dimension) | Draw a spline using the given handle coordinates and handle
codes. The constructor accepts a tuple in format (coords, codes).
Follows format of matplotlib spline definitions as used in
matplotlib.path.Path with the following codes:
Path.STOP : 0
Path.MOVETO : 1
Path.LINETO : 2
Path.CURVE3 : 3
Path.CURVE4 : 4
Path.CLOSEPLOY: 79 | 62598fa976e4537e8c3ef4f5 |
class SourceCatalogATNF(SourceCatalog): <NEW_LINE> <INDENT> name = 'ATNF' <NEW_LINE> description = 'ATNF pulsar catalog' <NEW_LINE> source_object_class = SourceCatalogObjectATNF <NEW_LINE> def __init__(self, filename=None): <NEW_LINE> <INDENT> if not filename: <NEW_LINE> <INDENT> filename = gammapy_extra.filename('datasets/catalogs/ATNF_v1.54.fits.gz') <NEW_LINE> self.table = Table.read(filename) | ATNF pulsar catalog.
The `ATNF pulsar catalog <http://www.atnf.csiro.au/people/pulsar/psrcat/>`__
is **the** collection of information on all pulsars.
Unfortunately it's only available in a database format that can only
be read with their software.
This function loads a FITS copy of version 1.54 of the ATNF catalog:
http://www.atnf.csiro.au/research/pulsar/psrcat/catalogueHistory.html
The ``ATNF_v1.54.fits.gz`` file and ``make_atnf.py`` script are available
`here <https://github.com/gammapy/gammapy-extra/blob/master/datasets/catalogs/>`__. | 62598fa97047854f4633f321 |
class Note(models.Model): <NEW_LINE> <INDENT> note_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) <NEW_LINE> name = models.CharField(max_length=50) <NEW_LINE> description = models.TextField() <NEW_LINE> privacy_state = models.CharField(max_length=20) <NEW_LINE> creation_date = models.DateTimeField() <NEW_LINE> last_update = models.DateTimeField() <NEW_LINE> is_crypted = models.BooleanField(default=False) <NEW_LINE> author = models.ForeignKey(User) <NEW_LINE> tags = models.ManyToManyField('Tag', null=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def laod_page(self): <NEW_LINE> <INDENT> note_directory = os.path.join(settings.NOTE_DIR, self.author) <NEW_LINE> note_directory = os.path.join(note_directory, self.name) <NEW_LINE> for element in note_directory: <NEW_LINE> <INDENT> if element.endswith('.md'): <NEW_LINE> <INDENT> self.pages.append(Page().load(element)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def save_on_disk(self): <NEW_LINE> <INDENT> passnote_directory = os.path.join(settings.NOTE_DIR, self.author) <NEW_LINE> note_directory = os.path.join(passnote_directory, self.name + '_' + self.note_id) <NEW_LINE> if not os.path.isdir(note_directory): <NEW_LINE> <INDENT> os.mkdir(self.name) <NEW_LINE> <DEDENT> for page in self.pages: <NEW_LINE> <INDENT> page_path = os.path.join(note_directory, page.__str__() + '.md') <NEW_LINE> with open(page_path, 'w') as f: <NEW_LINE> <INDENT> f.truncate() <NEW_LINE> f.write(page.text) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def light_serialization(self): <NEW_LINE> <INDENT> properties = dict() <NEW_LINE> properties['uuid'] = str(self.note_id) <NEW_LINE> properties['name'] = str(self.name) <NEW_LINE> return properties | Représentation d'une note comme un ensemble de page.
La plus part des infos sont stocké de manière physique dans les
dossiers le stockage en BDD sert à faciliter la recherche.
Sur le disque une note est stocké dans le dossier settings.NOTE_DIR,
à l'intérieur d'un dossier portant le nom de l'utilisateur.
Une note est un dossier contenant les pages et les attachments.
Le dossier est nommé nomNote_uuid | 62598fa9b7558d5895463577 |
class VideoAnalyzerOperationResultsOperations(object): <NEW_LINE> <INDENT> models = _models <NEW_LINE> def __init__(self, client, config, serializer, deserializer): <NEW_LINE> <INDENT> self._client = client <NEW_LINE> self._serialize = serializer <NEW_LINE> self._deserialize = deserializer <NEW_LINE> self._config = config <NEW_LINE> <DEDENT> def get( self, location_name, operation_id, **kwargs ): <NEW_LINE> <INDENT> cls = kwargs.pop('cls', None) <NEW_LINE> error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } <NEW_LINE> error_map.update(kwargs.pop('error_map', {})) <NEW_LINE> api_version = "2021-11-01-preview" <NEW_LINE> accept = "application/json" <NEW_LINE> url = self.get.metadata['url'] <NEW_LINE> path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1), 'locationName': self._serialize.url("location_name", location_name, 'str'), 'operationId': self._serialize.url("operation_id", operation_id, 'str'), } <NEW_LINE> url = self._client.format_url(url, **path_format_arguments) <NEW_LINE> query_parameters = {} <NEW_LINE> query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') <NEW_LINE> header_parameters = {} <NEW_LINE> header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') <NEW_LINE> request = self._client.get(url, query_parameters, header_parameters) <NEW_LINE> pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) <NEW_LINE> response = pipeline_response.http_response <NEW_LINE> if response.status_code not in [200, 202]: <NEW_LINE> <INDENT> map_error(status_code=response.status_code, response=response, error_map=error_map) <NEW_LINE> error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) <NEW_LINE> raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) <NEW_LINE> <DEDENT> deserialized = None <NEW_LINE> if response.status_code == 200: <NEW_LINE> <INDENT> deserialized = self._deserialize('VideoAnalyzer', pipeline_response) <NEW_LINE> <DEDENT> if cls: <NEW_LINE> <INDENT> return cls(pipeline_response, deserialized, {}) <NEW_LINE> <DEDENT> return deserialized <NEW_LINE> <DEDENT> get.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Media/locations/{locationName}/videoAnalyzerOperationResults/{operationId}'} | VideoAnalyzerOperationResultsOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~video_analyzer.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer. | 62598fa9eab8aa0e5d30bcd2 |
@delegate_names(delegate=PeriodArray, accessors=PeriodArray._datetimelike_ops, typ="property") <NEW_LINE> @delegate_names(delegate=PeriodArray, accessors=PeriodArray._datetimelike_methods, typ="method") <NEW_LINE> class PeriodProperties(Properties): <NEW_LINE> <INDENT> pass | Accessor object for datetimelike properties of the Series values.
Examples
--------
>>> s.dt.hour
>>> s.dt.second
>>> s.dt.quarter
Returns a Series indexed like the original Series.
Raises TypeError if the Series does not contain datetimelike values. | 62598fa9f548e778e596b4ed |
class InfinitePaginator(Paginator): <NEW_LINE> <INDENT> def __init__(self, object_list, per_page, allow_empty_first_page=True, link_template='/page/%d/', orphans=0): <NEW_LINE> <INDENT> orphans = 0 <NEW_LINE> super(InfinitePaginator, self).__init__(object_list, per_page, orphans, allow_empty_first_page) <NEW_LINE> del self._num_pages, self._count <NEW_LINE> self.link_template = link_template <NEW_LINE> <DEDENT> def validate_number(self, number): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> number = int(number) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise PageNotAnInteger('That page number is not an integer') <NEW_LINE> <DEDENT> if number < 1: <NEW_LINE> <INDENT> raise EmptyPage('That page number is less than 1') <NEW_LINE> <DEDENT> return number <NEW_LINE> <DEDENT> def page(self, number): <NEW_LINE> <INDENT> number = self.validate_number(number) <NEW_LINE> bottom = (number - 1) * self.per_page <NEW_LINE> top = bottom + self.per_page <NEW_LINE> page_items = self.object_list[bottom:top] <NEW_LINE> if not page_items: <NEW_LINE> <INDENT> if number == 1 and self.allow_empty_first_page: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise EmptyPage('That page contains no results') <NEW_LINE> <DEDENT> <DEDENT> return InfinitePage(page_items, number, self) <NEW_LINE> <DEDENT> def _get_count(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> count = property(_get_count) <NEW_LINE> def _get_num_pages(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> num_pages = property(_get_num_pages) <NEW_LINE> def _get_page_range(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> page_range = property(_get_page_range) | Paginator designed for cases when it's not important to know how many
total pages. This is useful for any object_list that has no count()
method or can be used to improve performance for MySQL by removing counts.
The orphans parameter has been removed for simplicity and there's a link
template string for creating the links to the next and previous pages. | 62598fa9dd821e528d6d8e7d |
class RestoreRunner(Strategy): <NEW_LINE> <INDENT> __strategy_type__ = 'restore_runner' <NEW_LINE> __strategy_ns__ = 'trove.guestagent.strategies.restore' <NEW_LINE> restore_cmd = None <NEW_LINE> restore_type = None <NEW_LINE> is_zipped = BACKUP_USE_GZIP <NEW_LINE> is_encrypted = BACKUP_USE_OPENSSL <NEW_LINE> decrypt_key = BACKUP_DECRYPT_KEY <NEW_LINE> def __init__(self, storage, **kwargs): <NEW_LINE> <INDENT> self.storage = storage <NEW_LINE> self.location = kwargs.pop('location') <NEW_LINE> self.checksum = kwargs.pop('checksum') <NEW_LINE> self.restore_location = kwargs.get('restore_location', '/var/lib/mysql') <NEW_LINE> self.restore_cmd = (self.decrypt_cmd + self.unzip_cmd + (self.base_restore_cmd % kwargs)) <NEW_LINE> super(RestoreRunner, self).__init__() <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __exit__(self, exc_type, exc_value, traceback): <NEW_LINE> <INDENT> if exc_type is not None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if hasattr(self, 'process'): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.process.terminate() <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> utils.raise_if_process_errored(self.process, RestoreError) <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> def pre_restore(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def post_restore(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def restore(self): <NEW_LINE> <INDENT> self.pre_restore() <NEW_LINE> content_length = self._run_restore() <NEW_LINE> self.post_restore() <NEW_LINE> return content_length <NEW_LINE> <DEDENT> def _run_restore(self): <NEW_LINE> <INDENT> return self._unpack(self.location, self.checksum, self.restore_cmd) <NEW_LINE> <DEDENT> def _unpack(self, location, checksum, command): <NEW_LINE> <INDENT> stream = self.storage.load(location, checksum) <NEW_LINE> self.process = subprocess.Popen(command, shell=True, stdin=subprocess.PIPE, stderr=subprocess.PIPE) <NEW_LINE> self.pid = self.process.pid <NEW_LINE> content_length = 0 <NEW_LINE> for chunk in stream: <NEW_LINE> <INDENT> self.process.stdin.write(chunk) <NEW_LINE> content_length += len(chunk) <NEW_LINE> <DEDENT> self.process.stdin.close() <NEW_LINE> LOG.info(_("Restored %s bytes from stream.") % content_length) <NEW_LINE> return content_length <NEW_LINE> <DEDENT> @property <NEW_LINE> def decrypt_cmd(self): <NEW_LINE> <INDENT> if self.is_encrypted: <NEW_LINE> <INDENT> return ('openssl enc -d -aes-256-cbc -salt -pass pass:%s | ' % self.decrypt_key) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def unzip_cmd(self): <NEW_LINE> <INDENT> return 'gzip -d -c | ' if self.is_zipped else '' | Base class for Restore Strategy implementations | 62598fa9e5267d203ee6b853 |
class TextTests(InvenioTestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.bad_xml = ( '<record><datafield tag="245" ind1="" ind2="">' '<subfield code="a">\xc3\x81xions, m\xc3\xa1jorons e neutrinos' ' em extens\xc3\xb5es do modelo padr\xc3\xa3o</subfield></datafield>' '<datafield tag="520" ind1="" ind2=""><subfield code="a">' 'based on the SU(3)L \xe2\x8a\x97 U(1)X and SU(2)L \xe2\x8a\x97 U(1)Y \x02 \xe2\x8a\x97 U(1)B\xe2\x88\x92L gauge symmetries.' 'Secondly, an electroweak model based on the gauge symmetry ' 'SU(2)L \xe2\x8a\x97 U(1)Y \x02 \xe2\x8a\x97 U(1)B\xe2\x88\x92L which has right-handed ' 'Finally, a N = 1 supersymmetric extension of the a B \xe2\x88\x92 L model with three' '</subfield></datafield></record>' ) <NEW_LINE> self.good_xml = ( u'<?xml version="1.0" encoding="utf-8"?>\n<record>' u'<datafield ind1="" ind2="" tag="245"><subfield code="a">' u'\xc1xions, m\xe1jorons e neutrinos em extens\xf5es do modelo' u' padr\xe3o</subfield></datafield><datafield ind1="" ind2="" tag="520">' u'<subfield code="a">based on the SU(3)L \u2297 U(1)X and SU(2)L' u' \u2297 U(1)Y \u2297 U(1)B\u2212L gauge symmetries.Secondly, ' u'an electroweak model based on the gauge symmetry SU(2)L' u' \u2297 U(1)Y \u2297 U(1)B\u2212L which has right-handed ' u'Finally, a N = 1 supersymmetric extension of the a B \u2212 L model' u' with three</subfield></datafield></record>' ) <NEW_LINE> self.unicode_xml = "<record>Über</record>" <NEW_LINE> self.good_unicode_xml = u'<?xml version="1.0" encoding="utf-8"?>\n<record>\xdcber</record>' <NEW_LINE> <DEDENT> def test_clean_xml(self): <NEW_LINE> <INDENT> from inspire.utils.text import clean_xml <NEW_LINE> self.assertEqual(clean_xml(self.bad_xml), self.good_xml) <NEW_LINE> <DEDENT> def test_unicode_clean_xml(self): <NEW_LINE> <INDENT> from inspire.utils.text import clean_xml <NEW_LINE> self.assertEqual(clean_xml(self.unicode_xml), self.good_unicode_xml) | Test the text functions. | 62598fa985dfad0860cbfa18 |
class CreateOfficeV2(Resource): <NEW_LINE> <INDENT> parser = reqparse.RequestParser() <NEW_LINE> parser.add_argument( 'name', type=str, required=True, help="Name of the office should be filled" ) <NEW_LINE> parser.add_argument( 'type', type=str, required=True, help="Type of the office should be filled" ) <NEW_LINE> @jwt_required <NEW_LINE> def post(self): <NEW_LINE> <INDENT> data = CreateOfficeV2.parser.parse_args() <NEW_LINE> name = data['name'] <NEW_LINE> type = data['type'] <NEW_LINE> while True: <NEW_LINE> <INDENT> if not name or not type: <NEW_LINE> <INDENT> return {'Message': 'Check for empty fields'} <NEW_LINE> <DEDENT> elif len(data['name']) < 3 or len(data['name']) > 15: <NEW_LINE> <INDENT> return {'Message': 'Name must be between 3 and 15 characters'} <NEW_LINE> <DEDENT> elif len(data['type']) < 3 or len(data['type']) > 20: <NEW_LINE> <INDENT> return {'Message': 'Office type description must be between 3 and 20 characters'} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> try: <NEW_LINE> <INDENT> current_user = get_jwt_identity() <NEW_LINE> cur.execute("SELECT isadmin FROM Users WHERE email = %(email)s;", { 'email': current_user }) <NEW_LINE> user_exists = cur.fetchone() <NEW_LINE> is_admin = user_exists[0] <NEW_LINE> if is_admin: <NEW_LINE> <INDENT> cur.execute("SELECT * FROM Offices WHERE name = %(name)s;", { 'name': data['name'] }) <NEW_LINE> office_exist = cur.fetchone() <NEW_LINE> if office_exist is None: <NEW_LINE> <INDENT> cur.execute("INSERT INTO Offices(name, type) VALUES(%(name)s, %(type)s) RETURNING office_id;", { 'name': data['name'], 'type': data['type'] }) <NEW_LINE> connection.commit() <NEW_LINE> new_id = cur.fetchone() <NEW_LINE> item = { 'id': new_id, 'name': name, 'type': type } <NEW_LINE> return { 'status': 201, 'Message': 'Office successfully added', 'data': item}, 201 <NEW_LINE> <DEDENT> return { 'status': 409, 'Message': 'The office already exists'}, 409 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return { 'status': 403, 'Message': 'This panel is for administrators only'}, 403 <NEW_LINE> <DEDENT> <DEDENT> except (Exception, psycopg2.DatabaseError) as error: <NEW_LINE> <INDENT> cur.execute("rollback;") <NEW_LINE> print(error) <NEW_LINE> return {'Message': 'current transaction is aborted'}, 500 | docstring for CreateOfficeV2. | 62598fa926068e7796d4c8a2 |
class ExpectShellSession(Action): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(ExpectShellSession, self).__init__() <NEW_LINE> self.name = "expect-shell-connection" <NEW_LINE> self.summary = "Expect a shell prompt" <NEW_LINE> self.description = "Wait for a shell" <NEW_LINE> self.prompts = [] <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> super(ExpectShellSession, self).validate() <NEW_LINE> if 'test_image_prompts' not in self.job.device: <NEW_LINE> <INDENT> self.errors = "Unable to identify test image prompts from device configuration." <NEW_LINE> <DEDENT> self.prompts = self.job.device['test_image_prompts'] <NEW_LINE> if 'parameters' in self.parameters: <NEW_LINE> <INDENT> if 'boot_prompt' in self.parameters['parameters']: <NEW_LINE> <INDENT> self.prompts.append(self.parameters['parameters']['boot_prompt']) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def run(self, connection, args=None): <NEW_LINE> <INDENT> connection = super(ExpectShellSession, self).run(connection, args) <NEW_LINE> connection.prompt_str = self.job.device['test_image_prompts'] <NEW_LINE> self.logger.debug("%s: Waiting for prompt", self.name) <NEW_LINE> self.wait(connection) <NEW_LINE> return connection | Waits for a shell connection to the device for the current job.
The shell connection can be over any particular connection,
all that is needed is a prompt. | 62598fa9aad79263cf42e71d |
class StubAggregatorXBlock(XBlock): <NEW_LINE> <INDENT> completion_mode = XBlockCompletionMode.AGGREGATOR | XBlock to test behaviour of BlockCompletionTransformer
when transforming aggregator XBlock. | 62598fa94a966d76dd5eee2b |
class BaseParser(object): <NEW_LINE> <INDENT> def __init__(self, path, **kwargs): <NEW_LINE> <INDENT> self.path = path <NEW_LINE> self.data = [] <NEW_LINE> self.fields = set([]) <NEW_LINE> for k, v in list(kwargs.items()): <NEW_LINE> <INDENT> setattr(self, k, v) <NEW_LINE> <DEDENT> self.open() <NEW_LINE> <DEDENT> def new_entry(self): <NEW_LINE> <INDENT> self.data.append(self.entry_class()) <NEW_LINE> <DEDENT> def _get_handler(self, tag): <NEW_LINE> <INDENT> handler_name = 'handle_{tag}'.format(tag=tag) <NEW_LINE> if hasattr(self, handler_name): <NEW_LINE> <INDENT> return getattr(self, handler_name) <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> def set_value(self, tag, value): <NEW_LINE> <INDENT> setattr(self.data[-1], tag, value) <NEW_LINE> <DEDENT> def postprocess_entry(self): <NEW_LINE> <INDENT> for field in self.fields: <NEW_LINE> <INDENT> processor_name = 'postprocess_{0}'.format(field) <NEW_LINE> if hasattr(self.data[-1], field) and hasattr(self, processor_name): <NEW_LINE> <INDENT> getattr(self, processor_name)(self.data[-1]) | Base class for all data parsers. Do not instantiate directly. | 62598fa966673b3332c30313 |
class UpperLimitCalc(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def lim_range(self, workspace_name): <NEW_LINE> <INDENT> from scharmfit import utils <NEW_LINE> utils.load_susyfit() <NEW_LINE> from ROOT import Util <NEW_LINE> from ROOT import RooStats <NEW_LINE> if not isfile(workspace_name): <NEW_LINE> <INDENT> raise OSError("can't find workspace {}".format(workspace_name)) <NEW_LINE> <DEDENT> workspace = Util.GetWorkspaceFromFile(workspace_name, 'combined') <NEW_LINE> Util.SetInterpolationCode(workspace,4) <NEW_LINE> with OutputFilter(accept_strings={}): <NEW_LINE> <INDENT> inverted = RooStats.DoHypoTestInversion( workspace, 1, 2, 3, True, 20, 0, -1, ) <NEW_LINE> <DEDENT> mean_limit = inverted.GetExpectedUpperLimit(0) <NEW_LINE> lower_limit = inverted.GetExpectedUpperLimit(-1) <NEW_LINE> upper_limit = inverted.GetExpectedUpperLimit(1) <NEW_LINE> return lower_limit, mean_limit, upper_limit | Calculates the upper limit min, mean, and max values | 62598fa9090684286d593680 |
@attrs(**ATTRSCONFIG) <NEW_LINE> class PushTemplate(Resource): <NEW_LINE> <INDENT> RESOURCE_TYPE = "AWS::Pinpoint::PushTemplate" <NEW_LINE> Properties: PushTemplateProperties = attrib( factory=PushTemplateProperties, converter=create_object_converter(PushTemplateProperties), ) | A Push Template for Pinpoint.
See Also:
`AWS Cloud Formation documentation for PushTemplate
<http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-pinpoint-pushtemplate.html>`_ | 62598fa94527f215b58e9e2b |
class OrganisationMembersView(generics.ListAPIView): <NEW_LINE> <INDENT> serializer_class = OrganisationMembersSerializer <NEW_LINE> permission_classes = (IsAuthenticated,) <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> organisation = get_object_or_404(Organisation, slug=self.kwargs['slug'], members=self.request.user) <NEW_LINE> return Membership.objects.filter(organisation=organisation) | List all the members for an organisation. User should be a member of that organisation. | 62598fa932920d7e50bc5f9e |
class TestCase(testtools.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(TestCase, self).setUp() <NEW_LINE> self.context = ironic_context.get_admin_context() <NEW_LINE> test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0) <NEW_LINE> try: <NEW_LINE> <INDENT> test_timeout = int(test_timeout) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> test_timeout = 0 <NEW_LINE> <DEDENT> if test_timeout > 0: <NEW_LINE> <INDENT> self.useFixture(fixtures.Timeout(test_timeout, gentle=True)) <NEW_LINE> <DEDENT> self.useFixture(fixtures.NestedTempfile()) <NEW_LINE> self.useFixture(fixtures.TempHomeDir()) <NEW_LINE> if (os.environ.get('OS_STDOUT_CAPTURE') == 'True' or os.environ.get('OS_STDOUT_CAPTURE') == '1'): <NEW_LINE> <INDENT> stdout = self.useFixture(fixtures.StringStream('stdout')).stream <NEW_LINE> self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout)) <NEW_LINE> <DEDENT> if (os.environ.get('OS_STDERR_CAPTURE') == 'True' or os.environ.get('OS_STDERR_CAPTURE') == '1'): <NEW_LINE> <INDENT> stderr = self.useFixture(fixtures.StringStream('stderr')).stream <NEW_LINE> self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr)) <NEW_LINE> <DEDENT> self.log_fixture = self.useFixture(fixtures.FakeLogger()) <NEW_LINE> self.useFixture(conf_fixture.ConfFixture(CONF)) <NEW_LINE> objects_base.IronicObject.indirection_api = None <NEW_LINE> self._base_test_obj_backup = copy.copy( objects_base.IronicObject._obj_classes) <NEW_LINE> self.addCleanup(self._restore_obj_registry) <NEW_LINE> self.addCleanup(self._clear_attrs) <NEW_LINE> self.addCleanup(hash_ring.HashRingManager().reset) <NEW_LINE> self.useFixture(fixtures.EnvironmentVariable('http_proxy')) <NEW_LINE> self.policy = self.useFixture(policy_fixture.PolicyFixture()) <NEW_LINE> CONF.set_override('fatal_exception_format_errors', True) <NEW_LINE> <DEDENT> def _restore_obj_registry(self): <NEW_LINE> <INDENT> objects_base.IronicObject._obj_classes = self._base_test_obj_backup <NEW_LINE> <DEDENT> def _clear_attrs(self): <NEW_LINE> <INDENT> for key in [k for k in self.__dict__.keys() if k[0] != '_']: <NEW_LINE> <INDENT> del self.__dict__[key] <NEW_LINE> <DEDENT> <DEDENT> def config(self, **kw): <NEW_LINE> <INDENT> group = kw.pop('group', None) <NEW_LINE> for k, v in kw.items(): <NEW_LINE> <INDENT> CONF.set_override(k, v, group) <NEW_LINE> <DEDENT> <DEDENT> def path_get(self, project_file=None): <NEW_LINE> <INDENT> root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', ) ) <NEW_LINE> if project_file: <NEW_LINE> <INDENT> return os.path.join(root, project_file) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return root | Test case base class for all unit tests. | 62598fa991f36d47f2230e49 |
class RemainingTimeUntil(RemainingTime): <NEW_LINE> <INDENT> def __init__(self, deadline: float) -> None: <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self._deadline = deadline <NEW_LINE> <DEDENT> def get(self) -> float: <NEW_LINE> <INDENT> return max(0.0, self._deadline - time.time()) | The remaining wall clock time up to a given absolute deadline in terms of time.time() | 62598fa93617ad0b5ee0609d |
class _compound_list_select_acid(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._compound_type = 'acid' <NEW_LINE> options = get_compound_list('H', 'acid') <NEW_LINE> self._compound = widgets.Select(options=options, layout=widgets.Layout(flex='0 0 auto', width='120px', height=_element_height)) <NEW_LINE> self._massfrac = widgets.BoundedFloatText(min=0., max=1., layout=widgets.Layout(flex='2 1 auto'), width='auto') <NEW_LINE> self._box = widgets.HBox(children=(self._compound, widgets.Label('MF acid'), self._massfrac), layout=widgets.Layout(display='flex', flex_direction='row')) <NEW_LINE> <DEDENT> @property <NEW_LINE> def massfrac(self): <NEW_LINE> <INDENT> return float(self._massfrac.value) <NEW_LINE> <DEDENT> @property <NEW_LINE> def formula(self): <NEW_LINE> <INDENT> return [(self._compound.value, self.massfrac), ('H2O', 1.0 - self.massfrac)] <NEW_LINE> <DEDENT> def set_by_values(self, compound, massfrac): <NEW_LINE> <INDENT> self._compound.value = compound <NEW_LINE> self._massfrac.value = massfrac <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> return dict(compound=self._compound.value, massfrac=self.massfrac) <NEW_LINE> <DEDENT> @property <NEW_LINE> def widget(self): <NEW_LINE> <INDENT> return self._box <NEW_LINE> <DEDENT> def display(self): <NEW_LINE> <INDENT> return self._box | selector for acid with weight frac of water | 62598fa9aad79263cf42e71e |
class IFacetedGlobalSettingsChangedEvent(IFacetedEvent): <NEW_LINE> <INDENT> pass | Faceted global settings updated
| 62598fa94e4d56256637236e |
class CommandLineException(Exception): <NEW_LINE> <INDENT> pass | convenience exception to make it easy to not print traceback when
run from the command line | 62598fa901c39578d7f12cc9 |
class ManageInternalEndpointRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.RegistryId = None <NEW_LINE> self.Operation = None <NEW_LINE> self.VpcId = None <NEW_LINE> self.SubnetId = None <NEW_LINE> self.RegionId = None <NEW_LINE> self.RegionName = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.RegistryId = params.get("RegistryId") <NEW_LINE> self.Operation = params.get("Operation") <NEW_LINE> self.VpcId = params.get("VpcId") <NEW_LINE> self.SubnetId = params.get("SubnetId") <NEW_LINE> self.RegionId = params.get("RegionId") <NEW_LINE> self.RegionName = params.get("RegionName") <NEW_LINE> memeber_set = set(params.keys()) <NEW_LINE> for name, value in vars(self).items(): <NEW_LINE> <INDENT> if name in memeber_set: <NEW_LINE> <INDENT> memeber_set.remove(name) <NEW_LINE> <DEDENT> <DEDENT> if len(memeber_set) > 0: <NEW_LINE> <INDENT> warnings.warn("%s fileds are useless." % ",".join(memeber_set)) | ManageInternalEndpoint请求参数结构体
| 62598fa9fff4ab517ebcd72e |
class LabelSmoothing(nn.Module): <NEW_LINE> <INDENT> def __init__(self, size, padding_idx, smoothing=0.0): <NEW_LINE> <INDENT> super(LabelSmoothing, self).__init__() <NEW_LINE> self.criterion = nn.KLDivLoss(reduction='sum') <NEW_LINE> self.padding_idx = padding_idx <NEW_LINE> self.confidence = 1.0 - smoothing <NEW_LINE> self.smoothing = smoothing <NEW_LINE> self.size = size <NEW_LINE> self.true_dist = None <NEW_LINE> <DEDENT> def forward(self, x: torch.Tensor, target): <NEW_LINE> <INDENT> assert x.size(1) == self.size <NEW_LINE> true_dist = x.data.clone() <NEW_LINE> true_dist.fill_(self.smoothing / (self.size - 2)) <NEW_LINE> true_dist.scatter_(1, target.data.unsqueeze(1).long(), self.confidence) <NEW_LINE> true_dist[:, self.padding_idx] = 0 <NEW_LINE> mask = torch.nonzero(target.data == self.padding_idx) <NEW_LINE> if mask.dim() > 0 and sum(mask.size()) > 0: <NEW_LINE> <INDENT> true_dist.index_fill_(0, mask.squeeze(), 0.0) <NEW_LINE> <DEDENT> self.true_dist = true_dist <NEW_LINE> return self.criterion(x, Variable(true_dist, requires_grad=False)) | Implement label smoothing. | 62598fa9d6c5a102081e2091 |
class NoSection(LogState): <NEW_LINE> <INDENT> def transition(self, sTag, _dAttr): <NEW_LINE> <INDENT> if sTag == 'p': <NEW_LINE> <INDENT> return InSection(RuleDict(self.oLogger), self.oLogger) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self | Not in any ruling section. | 62598fa999fddb7c1ca62d8d |
class DeploymentOutputStream(View): <NEW_LINE> <INDENT> def output_stream_generator(self): <NEW_LINE> <INDENT> if get_task_details(self.object.stage.project, self.object.task.name) is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> preyield = True <NEW_LINE> try: <NEW_LINE> <INDENT> process = subprocess.Popen( build_command(self.object, self.request.session), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True ) <NEW_LINE> all_output = '' <NEW_LINE> yield '<ul class="output">' <NEW_LINE> preyield = False <NEW_LINE> while True: <NEW_LINE> <INDENT> nextline = process.stdout.readline() <NEW_LINE> if nextline == '' and process.poll() is not None: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> nextline = '<li class="outputline">{}</li>'.format(nextline) <NEW_LINE> if nextline.find('\x1b[32m') != -1: <NEW_LINE> <INDENT> nextline = nextline.replace('\x1b[32m', '<ul class="outputgreen"><li class="outputline">') <NEW_LINE> <DEDENT> elif nextline.find('\x1b[31m') != -1: <NEW_LINE> <INDENT> nextline = nextline.replace('\x1b[31m', '<ul class="outputred"><li class="outputline">') <NEW_LINE> <DEDENT> if nextline.find('\x1b[0m') != -1: <NEW_LINE> <INDENT> nextline = nextline.replace('\x1b[0m', '</ul></li>') <NEW_LINE> <DEDENT> all_output += nextline <NEW_LINE> yield nextline <NEW_LINE> sys.stdout.flush() <NEW_LINE> <DEDENT> yield '</ul>' <NEW_LINE> preyield = True <NEW_LINE> self.object.status = self.object.SUCCESS if process.returncode == 0 else self.object.FAILED <NEW_LINE> yield '<span id="finished" style="display:none;">{}</span> {}'.format(self.object.status, ' '*1024) <NEW_LINE> self.object.output = all_output <NEW_LINE> self.object.save() <NEW_LINE> deployment_finished.send(self.object, deployment_id=self.object.pk) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> if not preyield: <NEW_LINE> <INDENT> yield '</ul>' <NEW_LINE> <DEDENT> message = "An error occurred: " + e.message <NEW_LINE> yield '<span class="erroroutput">{} </span><br /> {}'.format(message, ' '*1024) <NEW_LINE> yield '<span id="finished" style="display:none;">failed</span> {}'.format('*1024') <NEW_LINE> <DEDENT> <DEDENT> def get(self, request, *args, **kwargs): <NEW_LINE> <INDENT> self.object = get_object_or_404(models.Deployment, pk=int(kwargs['pk']), status=models.Deployment.PENDING) <NEW_LINE> resp = StreamingHttpResponse(self.output_stream_generator()) <NEW_LINE> return resp | Deployment view does the heavy lifting of calling Fabric Task for a Project Stage | 62598fa9e76e3b2f99fd897f |
class WwwcConfig: <NEW_LINE> <INDENT> def __init__(self, filename, section): <NEW_LINE> <INDENT> self.config = {} <NEW_LINE> self._parse_cfg(filename, section) <NEW_LINE> <DEDENT> def _parse_cfg(self, filename, section): <NEW_LINE> <INDENT> config = ConfigParser.ConfigParser() <NEW_LINE> config.read(filename) <NEW_LINE> for key, value in config.items(section): <NEW_LINE> <INDENT> self.set(key, value) <NEW_LINE> <DEDENT> <DEDENT> def get(self, key): <NEW_LINE> <INDENT> return self.config.get(key, None) <NEW_LINE> <DEDENT> def set(self, key, value): <NEW_LINE> <INDENT> self.config[key] = value | config class | 62598fa9d486a94d0ba2bf17 |
class Len(Function, PyccelAstNode): <NEW_LINE> <INDENT> _rank = 0 <NEW_LINE> _shape = () <NEW_LINE> _precision = default_precision['int'] <NEW_LINE> _dtype = NativeInteger() <NEW_LINE> def __new__(cls, arg): <NEW_LINE> <INDENT> return Basic.__new__(cls, arg) <NEW_LINE> <DEDENT> @property <NEW_LINE> def arg(self): <NEW_LINE> <INDENT> return self._args[0] | Represents a 'len' expression in the code. | 62598fa99c8ee82313040115 |
class WorksheetOrderSubmitView(LoginRequiredMixin, WorksheetMixin, UpdateView): <NEW_LINE> <INDENT> def post(self, request, *args, **kwargs): <NEW_LINE> <INDENT> section = Section.objects.get(slug=kwargs.get('section_slug')) <NEW_LINE> worksheets = Worksheet.objects.filter(section=section) <NEW_LINE> return re_order_features(request, worksheets) | Update order view for Worksheet. | 62598fa930dc7b766599f797 |
class TestKYCDataResponse(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 testKYCDataResponse(self): <NEW_LINE> <INDENT> model = swagger_client.models.kyc_data_response.KYCDataResponse() | KYCDataResponse unit test stubs | 62598fa945492302aabfc41a |
class ControllerGUI(Ui_MainWindow): <NEW_LINE> <INDENT> def __init__(self, window): <NEW_LINE> <INDENT> Ui_MainWindow.__init__(self) <NEW_LINE> self.setupUi(window) <NEW_LINE> self.but_headerfile.clicked.connect(self.read_header) <NEW_LINE> self.timer = QtCore.QTimer() <NEW_LINE> self.timer.setSingleShot(False) <NEW_LINE> self.timer.timeout.connect(self.refresh) <NEW_LINE> self.timer.start(3000) <NEW_LINE> <DEDENT> def read_header(self, arg): <NEW_LINE> <INDENT> print('Clicked read_header button') <NEW_LINE> tcu.parse_header() <NEW_LINE> <DEDENT> def refresh(self): <NEW_LINE> <INDENT> print('refreshing') | docstring for TCUPulseParamsGUILogic. | 62598fa9656771135c4895cb |
class ROPhoneNumberField(RegexField): <NEW_LINE> <INDENT> default_error_messages = { 'invalid': _('Phone numbers must be in XXXX-XXXXXX format.'), } <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(ROPhoneNumberField, self).__init__(r'^[0-9\-\(\)\s]{10,20}$', max_length=20, min_length=10, *args, **kwargs) <NEW_LINE> <DEDENT> def clean(self, value): <NEW_LINE> <INDENT> value = super(ROPhoneNumberField, self).clean(value) <NEW_LINE> if value in EMPTY_VALUES: <NEW_LINE> <INDENT> return u'' <NEW_LINE> <DEDENT> value = value.replace('-','') <NEW_LINE> value = value.replace('(','') <NEW_LINE> value = value.replace(')','') <NEW_LINE> value = value.replace(' ','') <NEW_LINE> if len(value) != 10: <NEW_LINE> <INDENT> raise ValidationError(self.error_messages['invalid']) <NEW_LINE> <DEDENT> return value | Romanian phone number field | 62598fa9cb5e8a47e493c11d |
class TestUserCreateRole(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 testUserCreateRole(self): <NEW_LINE> <INDENT> pass | UserCreateRole unit test stubs | 62598fa956ac1b37e6302136 |
class Query(CommentableMixin, Model): <NEW_LINE> <INDENT> title = models.CharField( max_length=127, ) <NEW_LINE> uploader = models.ForeignKey( to=swapper.get_model_name('kernel', 'Person'), on_delete=models.CASCADE, ) <NEW_LINE> app_name = models.CharField( max_length=63, ) <NEW_LINE> query = models.TextField() <NEW_LINE> uploaded_file = models.FileField( upload_to=UploadTo('helpcentre', 'queries'), blank=True, null=True, ) <NEW_LINE> is_closed = models.BooleanField( default=False, ) <NEW_LINE> assignees = models.ManyToManyField( to=swapper.get_model_name('kernel', 'Maintainer'), blank=True, ) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name_plural = 'queries' <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> uploader = self.uploader <NEW_LINE> app_name = self.app_name <NEW_LINE> title = self.title <NEW_LINE> return f'{uploader} ({app_name}): {title}' | This model holds the information about a query asked by a user of Omniport | 62598fa9a17c0f6771d5c17f |
@zope.interface.implementer(interfaces.IValidator) <NEW_LINE> class Validator(object): <NEW_LINE> <INDENT> def certificate(self, cert, name, alt_host=None, port=443): <NEW_LINE> <INDENT> if alt_host is None: <NEW_LINE> <INDENT> host = socket.gethostbyname(name) <NEW_LINE> <DEDENT> elif isinstance(alt_host, six.binary_type): <NEW_LINE> <INDENT> host = alt_host <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> host = alt_host.encode() <NEW_LINE> <DEDENT> name = name if isinstance(name, six.binary_type) else name.encode() <NEW_LINE> try: <NEW_LINE> <INDENT> presented_cert = crypto_util.probe_sni(name, host, port) <NEW_LINE> <DEDENT> except acme_errors.Error as error: <NEW_LINE> <INDENT> logger.exception(str(error)) <NEW_LINE> return False <NEW_LINE> <DEDENT> return presented_cert.digest("sha256") == cert.digest("sha256") <NEW_LINE> <DEDENT> def redirect(self, name, port=80, headers=None): <NEW_LINE> <INDENT> url = "http://{0}:{1}".format(name, port) <NEW_LINE> if headers: <NEW_LINE> <INDENT> response = requests.get(url, headers=headers, allow_redirects=False) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> response = requests.get(url, allow_redirects=False) <NEW_LINE> <DEDENT> redirect_location = response.headers.get("location", "") <NEW_LINE> if not redirect_location.startswith("https://"): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if response.status_code != 301: <NEW_LINE> <INDENT> logger.error("Server did not redirect with permanent code") <NEW_LINE> return False <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> def any_redirect(self, name, port=80, headers=None): <NEW_LINE> <INDENT> url = "http://{0}:{1}".format(name, port) <NEW_LINE> if headers: <NEW_LINE> <INDENT> response = requests.get(url, headers=headers, allow_redirects=False) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> response = requests.get(url, allow_redirects=False) <NEW_LINE> <DEDENT> return response.status_code in xrange(300, 309) <NEW_LINE> <DEDENT> def hsts(self, name): <NEW_LINE> <INDENT> headers = requests.get("https://" + name).headers <NEW_LINE> hsts_header = headers.get("strict-transport-security") <NEW_LINE> if not hsts_header: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> directives = [d.split("=") for d in hsts_header.split(";")] <NEW_LINE> max_age = [d for d in directives if d[0] == "max-age"] <NEW_LINE> if not max_age: <NEW_LINE> <INDENT> logger.error("Server responded with invalid HSTS header field") <NEW_LINE> return False <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> max_age_value = int(max_age[0][1]) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> logger.error("Server responded with invalid HSTS header field") <NEW_LINE> return False <NEW_LINE> <DEDENT> if max_age_value <= (2 * 7 * 24 * 3600): <NEW_LINE> <INDENT> logger.error("HSTS should not expire in less than two weeks") <NEW_LINE> return False <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> def ocsp_stapling(self, name): <NEW_LINE> <INDENT> raise NotImplementedError() | Collection of functions to test a live webserver's configuration | 62598fa9f548e778e596b4ee |
class CombDirectionType(Enum): <NEW_LINE> <INDENT> Comb = 48 <NEW_LINE> UnComb = 49 <NEW_LINE> def __int__(self): <NEW_LINE> <INDENT> return self.value <NEW_LINE> <DEDENT> def __char__(self): <NEW_LINE> <INDENT> return chr(self.value) | 组合指令方向类型 | 62598fa967a9b606de545f16 |
class Lowest(OperationN): <NEW_LINE> <INDENT> alias = ('MinN',) <NEW_LINE> lines = ('lowest',) <NEW_LINE> func = min | Calculates the lowest value for the data in a given period
Uses the built-in ``min`` for the calculation
Formula:
- lowest = min(data, period) | 62598fa90c0af96317c562cd |
class TestOrderFulfillment(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 testOrderFulfillment(self): <NEW_LINE> <INDENT> model = squareconnect.models.order_fulfillment.OrderFulfillment() | OrderFulfillment unit test stubs | 62598fa98e7ae83300ee8fec |
class ComputerStrategy(metaclass=abc.ABCMeta): <NEW_LINE> <INDENT> @abc.abstractmethod <NEW_LINE> def algorithm_execution(self, computer): <NEW_LINE> <INDENT> pass | Declare an interface common to all supported algorithms. Context
uses this interface to call the algorithm defined by a
ConcreteStrategy. | 62598fa9dd821e528d6d8e80 |
class DBSourceForgeBackend(DBBackend): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.MYSQL_EXT = [DBSourceForgeIssueExtMySQL] <NEW_LINE> <DEDENT> def insert_issue_ext(self, store, issue, issue_id): <NEW_LINE> <INDENT> newIssue = False; <NEW_LINE> try: <NEW_LINE> <INDENT> db_issue_ext = store.find(DBSourceForgeIssueExt, DBSourceForgeIssueExt.issue_id == issue_id).one() <NEW_LINE> if not db_issue_ext: <NEW_LINE> <INDENT> newIssue = True <NEW_LINE> db_issue_ext = DBSourceForgeIssueExt(issue_id) <NEW_LINE> <DEDENT> db_issue_ext.category = unicode(issue.category) <NEW_LINE> db_issue_ext.group = unicode(issue.group) <NEW_LINE> if newIssue == True: <NEW_LINE> <INDENT> store.add(db_issue_ext) <NEW_LINE> <DEDENT> store.flush() <NEW_LINE> return db_issue_ext <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> store.rollback() <NEW_LINE> raise <NEW_LINE> <DEDENT> <DEDENT> def insert_comment_ext(self, store, comment, comment_id): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def insert_attachment_ext(self, store, attch, attch_id): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def insert_change_ext(self, store, change, change_id): <NEW_LINE> <INDENT> pass | Adapter for SourceForge backend. | 62598fa97d847024c075c30e |
class uranium_decay: <NEW_LINE> <INDENT> def __init__(self,number_of_A=100,number_of_B=0,time_constant=1,time_of_duration=5,time_step=0.05): <NEW_LINE> <INDENT> self.na = [number_of_A] <NEW_LINE> self.nb = [number_of_B] <NEW_LINE> self.t=[0] <NEW_LINE> self.tau = time_constant <NEW_LINE> self.dt=time_step <NEW_LINE> self.time=time_of_duration <NEW_LINE> self.nsteps=int(time_of_duration//time_step+1) <NEW_LINE> print("initial_number_of_A->",number_of_A) <NEW_LINE> print("initial_number_of_B->",number_of_B) <NEW_LINE> print("Time_constant->",time_constant) <NEW_LINE> print("total_time->",time_of_duration) <NEW_LINE> <DEDENT> def calcualtion(self): <NEW_LINE> <INDENT> for i in range(self.nsteps): <NEW_LINE> <INDENT> temp_A=self.na[i]+(self.nb[i]-self.na[i])/self.tau*self.dt <NEW_LINE> temp_B=self.nb[i]+(self.na[i]-self.nb[i])/self.tau*self.dt <NEW_LINE> self.na.append(temp_A) <NEW_LINE> self.nb.append(temp_B) <NEW_LINE> self.t.append(self.t[i]+self.dt) <NEW_LINE> <DEDENT> <DEDENT> def show_result(self): <NEW_LINE> <INDENT> plot_a,=pl.plot(self.t,self.na,"g") <NEW_LINE> plot_b,=pl.plot(self.t,self.nb,"r") <NEW_LINE> pl.xlabel('time ($s$)') <NEW_LINE> pl.ylabel('Number') <NEW_LINE> pl.legend([plot_a, plot_b], ['A', 'B'],loc="best") <NEW_LINE> pl.title('decay of two nuclei A and B') <NEW_LINE> pl.show() <NEW_LINE> <DEDENT> def store_results(self): <NEW_LINE> <INDENT> myfile = open('decay_of_nuclei A and B_data.txt', 'w') <NEW_LINE> for i in range(len(self.t)): <NEW_LINE> <INDENT> print(self.t[i], self.na[i], self.nb[i], file = myfile) <NEW_LINE> <DEDENT> myfile.close() | Simulation of radioactive decay
Nuclei of type A decay into ones of type B,while nuclei of type B decay
into ones of type A
Program to accompany 'Computation Physics' by Cai Hao | 62598fa9090684286d593681 |
class Embargoed(_SimpleAttr): <NEW_LINE> <INDENT> def __init__(self, is_embargoed: bool): <NEW_LINE> <INDENT> super().__init__(bool(is_embargoed)) | Current embargo status of a dataset.
Parameters
----------
is_embargoed: `bool`
A boolean determining if a dataset currently under embargo. | 62598fa93539df3088ecc1ff |
class TCPClient(Actor): <NEW_LINE> <INDENT> @manage(['address', 'port', 'mode', 'delimiter']) <NEW_LINE> def init(self, mode="delimiter", delimiter="\r\n"): <NEW_LINE> <INDENT> self.address = None <NEW_LINE> self.port = None <NEW_LINE> self.EOST_token_received = False <NEW_LINE> self.cc = None <NEW_LINE> self.mode = mode <NEW_LINE> self.delimiter = delimiter <NEW_LINE> self.setup() <NEW_LINE> if self.address is not None: <NEW_LINE> <INDENT> self.connect() <NEW_LINE> <DEDENT> <DEDENT> def connect(self): <NEW_LINE> <INDENT> self.cc = self['socket'].connect(self.address, self.port, mode=self.mode, delimiter=self.delimiter) <NEW_LINE> <DEDENT> def will_migrate(self): <NEW_LINE> <INDENT> if self.cc: <NEW_LINE> <INDENT> self.cc.disconnect() <NEW_LINE> <DEDENT> <DEDENT> def did_migrate(self): <NEW_LINE> <INDENT> self.setup() <NEW_LINE> if self.address is not None: <NEW_LINE> <INDENT> self.connect() <NEW_LINE> <DEDENT> <DEDENT> def setup(self): <NEW_LINE> <INDENT> self.use('calvinsys.network.socketclienthandler', shorthand='socket') <NEW_LINE> self.use('calvinsys.native.python-re', shorthand='regexp') <NEW_LINE> <DEDENT> @condition(action_input=['data_in']) <NEW_LINE> @guard(lambda self, token: self.cc and self.cc.is_connected()) <NEW_LINE> def send(self, token): <NEW_LINE> <INDENT> self.cc.send(token) <NEW_LINE> return ActionResult(production=()) <NEW_LINE> <DEDENT> @condition(action_output=['data_out']) <NEW_LINE> @guard(lambda self: self.cc and self.cc.is_connected() and self.cc.have_data()) <NEW_LINE> def receive(self): <NEW_LINE> <INDENT> data = self.cc.get_data() <NEW_LINE> return ActionResult(production=(data,)) <NEW_LINE> <DEDENT> URI_REGEXP = r'([^:]+)://([^/:]*)(:[0-9]+)' <NEW_LINE> @condition(action_input=['control_in']) <NEW_LINE> @guard(lambda self, control: control['control'] == 'connect' and not self.cc) <NEW_LINE> def new_connection(self, control): <NEW_LINE> <INDENT> uri = self['regexp'].findall(self.URI_REGEXP, control['uri']) <NEW_LINE> uri_parts = uri[0] <NEW_LINE> protocol = uri_parts[0] <NEW_LINE> if protocol != 'tcp': <NEW_LINE> <INDENT> _log.warn("Protocol '%s' not suuported" % (protocol,)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.address = uri_parts[1] <NEW_LINE> self.port = int(uri_parts[2][1:]) <NEW_LINE> self.connect() <NEW_LINE> <DEDENT> return ActionResult(production=()) <NEW_LINE> <DEDENT> @condition(action_input=['control_in']) <NEW_LINE> @guard(lambda self, control: control['control'] == 'disconnect' and self.cc) <NEW_LINE> def close_connection(self, control): <NEW_LINE> <INDENT> self.cc.disconnect() <NEW_LINE> self.cc = None <NEW_LINE> return ActionResult(production=()) <NEW_LINE> <DEDENT> def exception_handler(self, action, args, context): <NEW_LINE> <INDENT> self.EOST_token_received = True <NEW_LINE> return ActionResult(production=()) <NEW_LINE> <DEDENT> action_priority = (new_connection, close_connection, receive, send) <NEW_LINE> requires = ['calvinsys.network.socketclienthandler', 'calvinsys.native.python-re'] | Etablish a TCP connection and forward all tokens.
Any recevied data on the TCP connection is forwarded according to protocol.
Input:
data_in : Each received token will be sent out through the TCP connection.
control_in : Each received token will be sent out through the TCP connection.
Output:
data_out : Data received on the TCP connection will be sent as tokens. | 62598fa932920d7e50bc5fa0 |
class PermissionVideoUploadError(OAuthException): <NEW_LINE> <INDENT> error_code = 261 <NEW_LINE> error_id = "PERMISSION_VIDEO_UPLOAD" <NEW_LINE> error_description = 'Modifying existing photos requires the extended permission photo_upload' | Autogenerated exception class for API error code 261 | 62598fa90a50d4780f705328 |
class Square(): <NEW_LINE> <INDENT> def __init__(self, size=0): <NEW_LINE> <INDENT> if type(size) is not int: <NEW_LINE> <INDENT> raise TypeError("size must be an integer") <NEW_LINE> <DEDENT> if size < 0: <NEW_LINE> <INDENT> raise ValueError("size must be >= 0") <NEW_LINE> <DEDENT> self.__size = size | Class that defines a Square | 62598fa9d6c5a102081e2093 |
class LogDriver(notifier._Driver): <NEW_LINE> <INDENT> LOGGER_BASE = 'oslo.messaging.notification' <NEW_LINE> def notify(self, ctxt, message, priority): <NEW_LINE> <INDENT> logger = logging.getLogger('%s.%s' % (self.LOGGER_BASE, message['event_type'])) <NEW_LINE> getattr(logger, priority.lower())(jsonutils.dumps(message)) | Publish notifications via Python logging infrastructure. | 62598fa938b623060ffa8fe3 |
class V1alpha1ClusterRoleBindingList(object): <NEW_LINE> <INDENT> swagger_types = { 'api_version': 'str', 'items': 'list[V1alpha1ClusterRoleBinding]', 'kind': 'str', 'metadata': 'V1ListMeta' } <NEW_LINE> attribute_map = { 'api_version': 'apiVersion', 'items': 'items', 'kind': 'kind', 'metadata': 'metadata' } <NEW_LINE> def __init__(self, api_version=None, items=None, kind=None, metadata=None): <NEW_LINE> <INDENT> self._api_version = None <NEW_LINE> self._items = None <NEW_LINE> self._kind = None <NEW_LINE> self._metadata = None <NEW_LINE> self.discriminator = None <NEW_LINE> if api_version is not None: <NEW_LINE> <INDENT> self.api_version = api_version <NEW_LINE> <DEDENT> self.items = items <NEW_LINE> if kind is not None: <NEW_LINE> <INDENT> self.kind = kind <NEW_LINE> <DEDENT> if metadata is not None: <NEW_LINE> <INDENT> self.metadata = metadata <NEW_LINE> <DEDENT> <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 items(self): <NEW_LINE> <INDENT> return self._items <NEW_LINE> <DEDENT> @items.setter <NEW_LINE> def items(self, items): <NEW_LINE> <INDENT> if items is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `items`, must not be `None`") <NEW_LINE> <DEDENT> self._items = items <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 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> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, V1alpha1ClusterRoleBindingList): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 62598fa944b2445a339b6915 |
class HADES_RADIUS_ACCOUNTING_PORT(Option): <NEW_LINE> <INDENT> type = int <NEW_LINE> default = 1813 | RADIUS accounting port | 62598fa916aa5153ce40044e |
class Config(object): <NEW_LINE> <INDENT> DEBUG = False <NEW_LINE> CSRF_ENABLED = True <NEW_LINE> JWT_SECRET_KEY = "fiona" | docstring for Config. | 62598fa901c39578d7f12ccb |
class Ganalytics(object): <NEW_LINE> <INDENT> def __init__(self, enable=None, utm_source=None, utm_medium=None, utm_term=None, utm_content=None, utm_campaign=None): <NEW_LINE> <INDENT> self._enable = None <NEW_LINE> self._utm_source = None <NEW_LINE> self._utm_medium = None <NEW_LINE> self._utm_term = None <NEW_LINE> self._utm_content = None <NEW_LINE> self._utm_campaign = None <NEW_LINE> self.__set_field("enable", enable) <NEW_LINE> self.__set_field("utm_source", utm_source) <NEW_LINE> self.__set_field("utm_medium", utm_medium) <NEW_LINE> self.__set_field("utm_term", utm_term) <NEW_LINE> self.__set_field("utm_content", utm_content) <NEW_LINE> self.__set_field("utm_campaign", utm_campaign) <NEW_LINE> <DEDENT> def __set_field(self, field, value): <NEW_LINE> <INDENT> if value is not None: <NEW_LINE> <INDENT> setattr(self, field, value) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def enable(self): <NEW_LINE> <INDENT> return self._enable <NEW_LINE> <DEDENT> @enable.setter <NEW_LINE> def enable(self, value): <NEW_LINE> <INDENT> self._enable = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def utm_source(self): <NEW_LINE> <INDENT> return self._utm_source <NEW_LINE> <DEDENT> @utm_source.setter <NEW_LINE> def utm_source(self, value): <NEW_LINE> <INDENT> self._utm_source = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def utm_medium(self): <NEW_LINE> <INDENT> return self._utm_medium <NEW_LINE> <DEDENT> @utm_medium.setter <NEW_LINE> def utm_medium(self, value): <NEW_LINE> <INDENT> self._utm_medium = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def utm_term(self): <NEW_LINE> <INDENT> return self._utm_term <NEW_LINE> <DEDENT> @utm_term.setter <NEW_LINE> def utm_term(self, value): <NEW_LINE> <INDENT> self._utm_term = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def utm_content(self): <NEW_LINE> <INDENT> return self._utm_content <NEW_LINE> <DEDENT> @utm_content.setter <NEW_LINE> def utm_content(self, value): <NEW_LINE> <INDENT> self._utm_content = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def utm_campaign(self): <NEW_LINE> <INDENT> return self._utm_campaign <NEW_LINE> <DEDENT> @utm_campaign.setter <NEW_LINE> def utm_campaign(self, value): <NEW_LINE> <INDENT> self._utm_campaign = value <NEW_LINE> <DEDENT> def get(self): <NEW_LINE> <INDENT> keys = ["enable", "utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign"] <NEW_LINE> ganalytics = {} <NEW_LINE> for key in keys: <NEW_LINE> <INDENT> value = getattr(self, key, None) <NEW_LINE> if value is not None: <NEW_LINE> <INDENT> ganalytics[key] = value <NEW_LINE> <DEDENT> <DEDENT> return ganalytics | Allows you to enable tracking provided by Google Analytics. | 62598fa98da39b475be0312f |
class whoswho(base.ATCTContent): <NEW_LINE> <INDENT> implements(Iwhoswho) <NEW_LINE> security = ClassSecurityInfo() <NEW_LINE> portal_type = "whoswho" <NEW_LINE> schema = whoswhoSchema <NEW_LINE> title = ATFieldProperty('title') <NEW_LINE> description = ATFieldProperty('description') <NEW_LINE> security.declarePublic('getWhoswho_type_vocabulary') <NEW_LINE> def getWhoswho_type_vocabulary(self): <NEW_LINE> <INDENT> return self._Vocabulary('WhosWhoType') <NEW_LINE> <DEDENT> def _Vocabulary(self, vocab_name): <NEW_LINE> <INDENT> dl = DisplayList() <NEW_LINE> pv = getToolByName(self, 'portal_vocabularies') <NEW_LINE> VOCAB = getattr(pv, vocab_name, None) <NEW_LINE> if VOCAB: <NEW_LINE> <INDENT> for k, v in VOCAB.getVocabularyDict().items(): <NEW_LINE> <INDENT> dl.add(k, v) <NEW_LINE> <DEDENT> <DEDENT> return dl | Description of the Example Type | 62598fa99c8ee82313040116 |
class StatsQtWidgetsQMainWindow(QtWidgets.QMainWindow): <NEW_LINE> <INDENT> def __init__(self, *args): <NEW_LINE> <INDENT> super().__init__(*args) <NEW_LINE> from ..utils.analytics import AnalyticsClient <NEW_LINE> name = self.__class__.__name__ <NEW_LINE> name = re.sub(r"([A-Z])", r" \1", name).strip() <NEW_LINE> AnalyticsClient.instance().sendScreenView(name) | Send stats from all the QMainWindow | 62598fa9925a0f43d25e7f8a |
class StackListResource(ListMongoResource): <NEW_LINE> <INDENT> method_decorators = [requires_auth_api] <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super(ListMongoResource, self).__init__(Stack) <NEW_LINE> self.document = Stack <NEW_LINE> <DEDENT> @catch_all <NEW_LINE> def post(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> user = User.objects.get(username=session['username']) <NEW_LINE> <DEDENT> except DoesNotExist: <NEW_LINE> <INDENT> return ({'error':'could not retrieve user object'}),500 <NEW_LINE> <DEDENT> doc = self.document() <NEW_LINE> Marshaller(doc).loads(request.json) <NEW_LINE> doc.owner = user <NEW_LINE> doc.createdat = datetime.now().strftime('%Y%m%d%H%M%S') <NEW_LINE> try: <NEW_LINE> <INDENT> doc.save() <NEW_LINE> <DEDENT> except NotUniqueError: <NEW_LINE> <INDENT> return {'error':'stack title not unique'}, 500 <NEW_LINE> <DEDENT> toReturn = Marshaller(doc).dumps() <NEW_LINE> toReturn['owner'] = None <NEW_LINE> return toReturn, 201 <NEW_LINE> <DEDENT> @catch_all <NEW_LINE> def get(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> user = User.objects.get(username=session['username']) <NEW_LINE> <DEDENT> except DoesNotExist: <NEW_LINE> <INDENT> return {'error':'could not retrieve user object'}, 500 <NEW_LINE> <DEDENT> filter_args, skip, limit, order = self.get_filter_args() <NEW_LINE> filter_args['owner'] = user <NEW_LINE> docs = self.document.objects.filter(**filter_args) <NEW_LINE> if order: <NEW_LINE> <INDENT> docs = docs.order_by(order) <NEW_LINE> <DEDENT> if limit: <NEW_LINE> <INDENT> if not skip: <NEW_LINE> <INDENT> skip = 0 <NEW_LINE> <DEDENT> docs = docs[skip: skip + limit] <NEW_LINE> <DEDENT> toReturn = [] <NEW_LINE> for doc in docs: <NEW_LINE> <INDENT> temp = Marshaller(doc).dumps() <NEW_LINE> temp['owner'] = None <NEW_LINE> toReturn.append(temp) <NEW_LINE> <DEDENT> return toReturn, 200 | GET MULTIPLE, POST
I overwrite these classes to filter by owner and hide owner from client | 62598fa967a9b606de545f17 |
class UserFeedbackCheckFailure(commands.CheckFailure): <NEW_LINE> <INDENT> def __init__(self, message=None, *args): <NEW_LINE> <INDENT> self.message = message <NEW_LINE> super().__init__(message, *args) | A version of CheckFailure which isn't suppressed. | 62598fa9442bda511e95c3a1 |
class PulpTaskGroupError(Exception): <NEW_LINE> <INDENT> def __init__(self, task_group): <NEW_LINE> <INDENT> super().__init__(self, f"Pulp task group failed ({task_group})") <NEW_LINE> self.task_group = task_group | Exception to describe task group errors. | 62598fa9851cf427c66b8214 |
class PasswordChange(GenericAPIView): <NEW_LINE> <INDENT> serializer_class = PasswordChangeSerializer <NEW_LINE> permission_classes = (IsAuthenticated,) <NEW_LINE> def post(self, request): <NEW_LINE> <INDENT> serializer = self.get_serializer(data=request.data) <NEW_LINE> if not serializer.is_valid(): <NEW_LINE> <INDENT> return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST ) <NEW_LINE> <DEDENT> serializer.save() <NEW_LINE> return Response({"success": "New password has been saved."}) | Calls Django Auth SetPasswordForm save method.
Accepts the following POST parameters: new_password1, new_password2
Returns the success/fail message. | 62598fa921bff66bcd722bb2 |
class CaseInsensitiveDict(MutableMapping): <NEW_LINE> <INDENT> def __init__(self, data=None, **kwargs): <NEW_LINE> <INDENT> self._store = OrderedDict() <NEW_LINE> if data is None: <NEW_LINE> <INDENT> data = {} <NEW_LINE> <DEDENT> self.update(data, **kwargs) <NEW_LINE> <DEDENT> def __setitem__(self, key, value): <NEW_LINE> <INDENT> self._store[key.lower()] = (key, value) <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> return self._store[key.lower()][1] <NEW_LINE> <DEDENT> def __delitem__(self, key): <NEW_LINE> <INDENT> del self._store[key.lower()] <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return (casedkey for casedkey, mappedvalue in self._store.values()) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self._store) <NEW_LINE> <DEDENT> def lower_items(self): <NEW_LINE> <INDENT> return ( (lowerkey, keyval[1]) for (lowerkey, keyval) in self._store.items() ) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if isinstance(other, Mapping): <NEW_LINE> <INDENT> other = CaseInsensitiveDict(other) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> return dict(self.lower_items()) == dict(other.lower_items()) <NEW_LINE> <DEDENT> def copy(self): <NEW_LINE> <INDENT> return CaseInsensitiveDict(self._store.values()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return str(dict(self.items())) | A case-insensitive ``dict``-like object.
Implements all methods and operations of
``MutableMapping`` as well as dict's ``copy``. Also
provides ``lower_items``.
All keys are expected to be strings. The structure remembers the
case of the last key to be set, and ``iter(instance)``,
``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()``
will contain case-sensitive keys. However, querying and contains
testing is case insensitive::
cid = CaseInsensitiveDict()
cid['Accept'] = 'application/json'
cid['aCCEPT'] == 'application/json' # True
list(cid) == ['Accept'] # True
For example, ``headers['content-encoding']`` will return the
value of a ``'Content-Encoding'`` response header, regardless
of how the header name was originally stored.
If the constructor, ``.update``, or equality comparison
operations are given keys that have equal ``.lower()``s, the
behavior is undefined. | 62598fa9b7558d589546357b |
class Mgm2GainMessage(Message): <NEW_LINE> <INDENT> def __init__(self, value): <NEW_LINE> <INDENT> super().__init__("gain", None) <NEW_LINE> self._value = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def value(self): <NEW_LINE> <INDENT> return self._value <NEW_LINE> <DEDENT> @property <NEW_LINE> def size(self): <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "Mgm2GainMessage({})".format(self.value) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Mgm2GainMessage({})".format(self.value) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if type(other) != Mgm2GainMessage: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if self.value == other.value: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False | Class to send to neighbors what best gain can be achieved by the agent if
it moves alone | 62598fa93539df3088ecc200 |
class InfrastructureType(StructureOrNoneRelated, OptionalPictogramMixin): <NEW_LINE> <INDENT> label = models.CharField(max_length=128) <NEW_LINE> type = models.CharField(max_length=1, choices=INFRASTRUCTURE_TYPES) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = _("Infrastructure Type") <NEW_LINE> verbose_name_plural = _("Infrastructure Types") <NEW_LINE> ordering = ['label', 'type'] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> if self.structure: <NEW_LINE> <INDENT> return "{} ({})".format(self.label, self.structure.name) <NEW_LINE> <DEDENT> return self.label <NEW_LINE> <DEDENT> def get_pictogram_url(self): <NEW_LINE> <INDENT> pictogram_url = super().get_pictogram_url() <NEW_LINE> if pictogram_url: <NEW_LINE> <INDENT> return pictogram_url <NEW_LINE> <DEDENT> return os.path.join(settings.STATIC_URL, 'infrastructure/picto-infrastructure.png') | Types of infrastructures (bridge, WC, stairs, ...) | 62598fa945492302aabfc41d |
@Producer(UberCar, host = 'http://ucigridb.nacs.uci.edu:12000') <NEW_LINE> @GetterSetter(InactiveUberCar, ActiveUberCar, CarAndCarInfront, Vehicle, host = 'http://ucigridb.nacs.uci.edu:12000') <NEW_LINE> class TrafficSimulation(IApplication): <NEW_LINE> <INDENT> frame = None <NEW_LINE> ticks = 0 <NEW_LINE> cars = [] <NEW_LINE> def __init__(self, frame): <NEW_LINE> <INDENT> self.frame = frame <NEW_LINE> <DEDENT> def initialize(self): <NEW_LINE> <INDENT> logger.debug("%s Initializing", LOG_HEADER) <NEW_LINE> for i in xrange(2): <NEW_LINE> <INDENT> self.frame.add(UberCar()) <NEW_LINE> <DEDENT> self.cars = self.frame.get(UberCar) <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> logger.info("%s %d Tick", LOG_HEADER, self.ticks) <NEW_LINE> cars = self.frame.get(UberCar) <NEW_LINE> activeCars = self.frame.get(ActiveUberCar) <NEW_LINE> inActiveCars = self.frame.get(InactiveUberCar) <NEW_LINE> logger.info("total cars: %d", len(cars)) <NEW_LINE> logger.info("active cars: %d, inactive cars: %d", len(activeCars), len(inActiveCars)) <NEW_LINE> speedDict = {} <NEW_LINE> for c in self.frame.get(CarAndCarInfront): <NEW_LINE> <INDENT> vx = c.frontCar.Velocity.X <NEW_LINE> vy = c.frontCar.Velocity.Y <NEW_LINE> speedDict[c.car1.ID] = math.sqrt(vx * vx + vy * vy) <NEW_LINE> <DEDENT> for car in activeCars: <NEW_LINE> <INDENT> if car.ID in speedDict: <NEW_LINE> <INDENT> car.adjustSpeed(speedDict[car.ID]) <NEW_LINE> <DEDENT> car.move() <NEW_LINE> car.reportStatus() <NEW_LINE> <DEDENT> self.ticks += 1 <NEW_LINE> <DEDENT> def shutdown(self): <NEW_LINE> <INDENT> logger.info("traffic sim shut down") <NEW_LINE> pass | classdocs | 62598fa9be383301e0253744 |
class IRCReplyBot(irc.IRCClient): <NEW_LINE> <INDENT> def connectionMade(self): <NEW_LINE> <INDENT> self.nickname = self.factory.nickname <NEW_LINE> self.password = self.factory.password <NEW_LINE> irc.IRCClient.connectionMade(self) <NEW_LINE> <DEDENT> def signedOn(self): <NEW_LINE> <INDENT> channel = self.factory.channel <NEW_LINE> self.join(channel) <NEW_LINE> <DEDENT> def privmsg(self, user, channel, msg): <NEW_LINE> <INDENT> user = user.split('!')[0] <NEW_LINE> if self.nickname.lower() == channel.lower(): <NEW_LINE> <INDENT> self.handlePrivateMessage(user, channel, msg) <NEW_LINE> <DEDENT> elif msg.startswith(self.nickname + ':'): <NEW_LINE> <INDENT> direct = msg[len(self.nickname + ':'):].strip() <NEW_LINE> self.handleDirectMessage(user, channel, direct) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.handlePublicMessage(user, channel, msg) <NEW_LINE> <DEDENT> <DEDENT> def handlePrivateMessage(self, user, channel, msg): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def handleDirectMessage(self, user, channel, msg): <NEW_LINE> <INDENT> if re.match('s$', msg): <NEW_LINE> <INDENT> stats = self.factory.getShortStats() <NEW_LINE> self.msg(channel, stats) <NEW_LINE> <DEDENT> elif re.match('stat$', msg): <NEW_LINE> <INDENT> for stat in self.factory.getLongStats(): <NEW_LINE> <INDENT> self.msg(channel, stat) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def handlePublicMessage(self, user, channel, msg): <NEW_LINE> <INDENT> self.filters = [self.pastebin, self.ujeb] <NEW_LINE> for filter in self.filters: <NEW_LINE> <INDENT> msg = filter(user, channel, msg) <NEW_LINE> if msg is None: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def pastebin(self, user, channel, msg): <NEW_LINE> <INDENT> pastebin = re.compile('https?://(' + 'pastebin\.com|' + 'wklej\.to|' + 'paste\.pocoo\.org|' + 'pastebin\.pl|' + 'codepad\.org|' + 'pastebin\.ca|' + 'pastie\.org|' + 'pastebin\.4programmers\.net)') <NEW_LINE> if pastebin.search(msg): <NEW_LINE> <INDENT> self.msg(channel, 'I will kick you, Bastard! wklej.org RULEZZZZ') <NEW_LINE> return <NEW_LINE> <DEDENT> return msg <NEW_LINE> <DEDENT> def ujeb(self, user, channel, msg): <NEW_LINE> <INDENT> http = re.compile('(https?://[^\s]+)') <NEW_LINE> if http.search(msg): <NEW_LINE> <INDENT> for url in http.findall(msg): <NEW_LINE> <INDENT> ujebany = self.factory.shortenURL(url) <NEW_LINE> ujebany.addCallback( lambda u: len(u) < len(url) and self.msg(channel, u) ) <NEW_LINE> <DEDENT> <DEDENT> return msg | IRC Bot, have fun! | 62598fa94e4d562566372371 |
class IpPatchInput(object): <NEW_LINE> <INDENT> openapi_types = { 'data': 'IpPatchIn', 'operations': 'list[JsonPatchOperation]', 'q': 'QuerybuilderRuleGroupSchema' } <NEW_LINE> attribute_map = { 'data': 'data', 'operations': 'operations', 'q': 'q' } <NEW_LINE> def __init__(self, data=None, operations=None, q=None, local_vars_configuration=None): <NEW_LINE> <INDENT> if local_vars_configuration is None: <NEW_LINE> <INDENT> local_vars_configuration = Configuration() <NEW_LINE> <DEDENT> self.local_vars_configuration = local_vars_configuration <NEW_LINE> self._data = None <NEW_LINE> self._operations = None <NEW_LINE> self._q = None <NEW_LINE> self.discriminator = None <NEW_LINE> if data is not None: <NEW_LINE> <INDENT> self.data = data <NEW_LINE> <DEDENT> if operations is not None: <NEW_LINE> <INDENT> self.operations = operations <NEW_LINE> <DEDENT> if q is not None: <NEW_LINE> <INDENT> self.q = q <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def data(self): <NEW_LINE> <INDENT> return self._data <NEW_LINE> <DEDENT> @data.setter <NEW_LINE> def data(self, data): <NEW_LINE> <INDENT> self._data = data <NEW_LINE> <DEDENT> @property <NEW_LINE> def operations(self): <NEW_LINE> <INDENT> return self._operations <NEW_LINE> <DEDENT> @operations.setter <NEW_LINE> def operations(self, operations): <NEW_LINE> <INDENT> self._operations = operations <NEW_LINE> <DEDENT> @property <NEW_LINE> def q(self): <NEW_LINE> <INDENT> return self._q <NEW_LINE> <DEDENT> @q.setter <NEW_LINE> def q(self, q): <NEW_LINE> <INDENT> self._q = q <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.openapi_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, IpPatchInput): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.to_dict() == other.to_dict() <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, IpPatchInput): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.to_dict() != other.to_dict() | NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually. | 62598fa999cbb53fe6830e22 |
class Listing(object): <NEW_LINE> <INDENT> def __init__(self, fname): <NEW_LINE> <INDENT> self.listing = [(0, [])] <NEW_LINE> self.filename = fname <NEW_LINE> <DEDENT> def listInstruction(self, inst): <NEW_LINE> <INDENT> self.listing.append(inst) <NEW_LINE> <DEDENT> def listDivider(self, newpc): <NEW_LINE> <INDENT> self.listing.append((newpc, [])) <NEW_LINE> <DEDENT> def listData(self, vals, pc): <NEW_LINE> <INDENT> if type(self.listing[-1]) is not tuple: <NEW_LINE> <INDENT> self.listing.append((pc, [])) <NEW_LINE> <DEDENT> self.listing[-1][1].extend(vals) <NEW_LINE> <DEDENT> def dump(self): <NEW_LINE> <INDENT> if self.filename == "-": <NEW_LINE> <INDENT> out = sys.stdout <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> out = file(self.filename, "w") <NEW_LINE> <DEDENT> for x in self.listing: <NEW_LINE> <INDENT> if type(x) is str: <NEW_LINE> <INDENT> print>>out, x <NEW_LINE> <DEDENT> elif type(x) is tuple: <NEW_LINE> <INDENT> i = 0 <NEW_LINE> pc = x[0] <NEW_LINE> while True: <NEW_LINE> <INDENT> row = x[1][i:i + 16] <NEW_LINE> if row == []: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> dataline = " %04X " % (pc + i) <NEW_LINE> dataline += (" %02X" * len(row)) % tuple(row) <NEW_LINE> charline = "" <NEW_LINE> for c in row: <NEW_LINE> <INDENT> if c < 32 or c > 126: <NEW_LINE> <INDENT> charline += "." <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> charline += chr(c) <NEW_LINE> <DEDENT> <DEDENT> print>>out, "%-54s |%-16s|" % (dataline, charline) <NEW_LINE> i += 16 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if self.filename != "-": <NEW_LINE> <INDENT> out.close() | Encapsulates the program listing. Accepts fully formatted
instruction strings, or batches of data bytes. Batches of data
bytes are assumed to be contiguous unless a divider is explicitly
requested. | 62598fa97d43ff24874273a8 |
class RatedItem(models.Model): <NEW_LINE> <INDENT> rating_average = models.DecimalField(max_digits=7, decimal_places=2) <NEW_LINE> rating_count = models.PositiveIntegerField() <NEW_LINE> date_last_rated = models.DateTimeField(editable=False, null=True) <NEW_LINE> content_type = models.ForeignKey(ContentType) <NEW_LINE> object_id = models.PositiveIntegerField() <NEW_LINE> object = generic.GenericForeignKey('content_type', 'object_id') <NEW_LINE> objects = RatedItemManager() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> unique_together = (('content_type', 'object_id'),) <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return u'Rating for %s' % self.object <NEW_LINE> <DEDENT> def add_or_update_rating(self, value, user): <NEW_LINE> <INDENT> now = datetime.datetime.now() <NEW_LINE> rating, created = Rating.objects.get_or_create( user = user, rated_object = self, defaults = { 'date': now, 'rating': value, } ) <NEW_LINE> if not created: <NEW_LINE> <INDENT> rating.rating = value <NEW_LINE> rating.date = now <NEW_LINE> rating.save() <NEW_LINE> <DEDENT> self.rating_count = self.ratings.count() <NEW_LINE> self.rating_average = str(Rating.objects.rating_average(self.object)) <NEW_LINE> self.date_last_rated = now <NEW_LINE> self.save() <NEW_LINE> return self <NEW_LINE> <DEDENT> def get_average(self): <NEW_LINE> <INDENT> return '%.1f' % self.rating_average <NEW_LINE> <DEDENT> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> if not self.id: <NEW_LINE> <INDENT> self.rating_count = 0 <NEW_LINE> self.rating_average = 0 <NEW_LINE> <DEDENT> super(RatedItem, self).save(*args, **kwargs) | Rate info for an object. | 62598fa98e7ae83300ee8fed |
class CliListScripts(BaseScriptCli): <NEW_LINE> <INDENT> def take_action(self, parsed_args): <NEW_LINE> <INDENT> resp = utils.get_client_from_osc(self).rating.pyscripts.list_scripts( **vars(parsed_args)) <NEW_LINE> resp = resp.get('scripts') or [] <NEW_LINE> values = utils.list_to_cols(resp, self.columns) <NEW_LINE> return [col[1] for col in self.columns], values <NEW_LINE> <DEDENT> def get_parser(self, prog_name): <NEW_LINE> <INDENT> parser = super(CliListScripts, self).get_parser(prog_name) <NEW_LINE> parser.add_argument( '-n', '--no-data', action='store_true', help='Set to true to remove script data from output') <NEW_LINE> return parser | List existing PyScripts. | 62598fa910dbd63aa1c70aff |
class TooManyRequests(object): <NEW_LINE> <INDENT> swagger_types = { 'errors': 'list[TooManyRequestsErrors]' } <NEW_LINE> attribute_map = { 'errors': 'errors' } <NEW_LINE> def __init__(self, errors=None): <NEW_LINE> <INDENT> self._errors = None <NEW_LINE> self.discriminator = None <NEW_LINE> self.errors = errors <NEW_LINE> <DEDENT> @property <NEW_LINE> def errors(self): <NEW_LINE> <INDENT> return self._errors <NEW_LINE> <DEDENT> @errors.setter <NEW_LINE> def errors(self, errors): <NEW_LINE> <INDENT> if errors is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `errors`, must not be `None`") <NEW_LINE> <DEDENT> self._errors = errors <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, TooManyRequests): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 62598fa9dd821e528d6d8e82 |
class TimeSeriesName(object): <NEW_LINE> <INDENT> def __init__(self, metric, tags): <NEW_LINE> <INDENT> self.metric = metric <NEW_LINE> self.tags = tags <NEW_LINE> <DEDENT> @property <NEW_LINE> def tags(self): <NEW_LINE> <INDENT> return self._tags <NEW_LINE> <DEDENT> @tags.setter <NEW_LINE> def tags(self, tags): <NEW_LINE> <INDENT> if tags: <NEW_LINE> <INDENT> for key in tags: <NEW_LINE> <INDENT> if not key: <NEW_LINE> <INDENT> raise ValueError("Tag key can't be '%s'" % key) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self._tags = tags <NEW_LINE> <DEDENT> @property <NEW_LINE> def metric(self): <NEW_LINE> <INDENT> return self._metric <NEW_LINE> <DEDENT> @metric.setter <NEW_LINE> def metric(self, metric): <NEW_LINE> <INDENT> if not metric: <NEW_LINE> <INDENT> raise ValueError("metric name cannot be None or empty") <NEW_LINE> <DEDENT> self._metric = metric <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.metric + json.dumps(self.tags, sort_keys=True) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def encode_metric(metric_name, metric_tags): <NEW_LINE> <INDENT> if not isinstance(metric_name, str): <NEW_LINE> <INDENT> raise ValueError("metric_name should be a string") <NEW_LINE> <DEDENT> if metric_name == "": <NEW_LINE> <INDENT> raise ValueError("metric_name cannot be empty") <NEW_LINE> <DEDENT> if not isinstance(metric_tags, dict): <NEW_LINE> <INDENT> raise ValueError("metric_tags must be a dictionary") <NEW_LINE> <DEDENT> encoded_metric_name = metric_name + json.dumps(metric_tags, sort_keys=True) <NEW_LINE> return encoded_metric_name <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> @lru_cache(maxsize=2048) <NEW_LINE> def decode_metric(encoded_metric_name): <NEW_LINE> <INDENT> if encoded_metric_name is None or encoded_metric_name == "": <NEW_LINE> <INDENT> raise ValueError("Invalid value for encoded_metric_name") <NEW_LINE> <DEDENT> metric_tags = {} <NEW_LINE> metric_name = encoded_metric_name.strip() <NEW_LINE> brace_index = encoded_metric_name.find('{') <NEW_LINE> if brace_index > -1: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> metric_tags = json.loads(encoded_metric_name[brace_index:]) <NEW_LINE> metric_name = encoded_metric_name[:brace_index].strip() <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> raise ValueError("Failed to parse the encoded_metric_name %s, invalid format" % encoded_metric_name, err) <NEW_LINE> <DEDENT> <DEDENT> return metric_name, metric_tags | Encapsulates a timeseries name representation by using the metric name and tags | 62598fa9627d3e7fe0e06df9 |
class Canvas: <NEW_LINE> <INDENT> def __init__(self, width, height, window_title: str): <NEW_LINE> <INDENT> glutInit(sys.argv) <NEW_LINE> glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB) <NEW_LINE> glutInitWindowSize(width, height) <NEW_LINE> glutInitWindowPosition(0, 0) <NEW_LINE> glutCreateWindow(window_title.encode('ascii')) <NEW_LINE> self.window = [0, width, 0, height] <NEW_LINE> self.viewport = [0, width, 0, height] <NEW_LINE> self.color = [0, 0, 0] <NEW_LINE> self.set_window(0, width, 0, height) <NEW_LINE> self.set_viewport(0, width, 0, height) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def swap(): <NEW_LINE> <INDENT> glutSwapBuffers() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def clear_screen(): <NEW_LINE> <INDENT> glClear(GL_COLOR_BUFFER_BIT) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def set_bc(r, g, b): <NEW_LINE> <INDENT> glClearColor(r, g, b, 0.0) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def thick(t): <NEW_LINE> <INDENT> glLineWidth(t) <NEW_LINE> <DEDENT> def set_color(self, r, g, b): <NEW_LINE> <INDENT> self.color = [r, g, b] <NEW_LINE> glColor3f(r, g, b) <NEW_LINE> <DEDENT> def set_window(self, l, r, b, t): <NEW_LINE> <INDENT> glMatrixMode(GL_PROJECTION) <NEW_LINE> glLoadIdentity() <NEW_LINE> gluOrtho2D(l, r, b, t) <NEW_LINE> self.window = [l , r, b, t] <NEW_LINE> <DEDENT> def set_viewport(self, left, right, bottom, top): <NEW_LINE> <INDENT> glViewport(left, bottom, right - left, top - bottom) <NEW_LINE> self.viewport = [left, right, bottom, top] | viewport and window are lists (left, right, bottom, top)
color is used for drawing (red, green, blue) | 62598fa91b99ca400228f4d6 |
class itkShotNoiseImageFilterIUC3IUC3(itkInPlaceImageFilterAPython.itkInPlaceImageFilterIUC3IUC3): <NEW_LINE> <INDENT> thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> InputConvertibleToOutputCheck = _itkShotNoiseImageFilterPython.itkShotNoiseImageFilterIUC3IUC3_InputConvertibleToOutputCheck <NEW_LINE> def __New_orig__(): <NEW_LINE> <INDENT> return _itkShotNoiseImageFilterPython.itkShotNoiseImageFilterIUC3IUC3___New_orig__() <NEW_LINE> <DEDENT> __New_orig__ = staticmethod(__New_orig__) <NEW_LINE> def GetScale(self): <NEW_LINE> <INDENT> return _itkShotNoiseImageFilterPython.itkShotNoiseImageFilterIUC3IUC3_GetScale(self) <NEW_LINE> <DEDENT> def SetScale(self, *args): <NEW_LINE> <INDENT> return _itkShotNoiseImageFilterPython.itkShotNoiseImageFilterIUC3IUC3_SetScale(self, *args) <NEW_LINE> <DEDENT> __swig_destroy__ = _itkShotNoiseImageFilterPython.delete_itkShotNoiseImageFilterIUC3IUC3 <NEW_LINE> def cast(*args): <NEW_LINE> <INDENT> return _itkShotNoiseImageFilterPython.itkShotNoiseImageFilterIUC3IUC3_cast(*args) <NEW_LINE> <DEDENT> cast = staticmethod(cast) <NEW_LINE> def GetPointer(self): <NEW_LINE> <INDENT> return _itkShotNoiseImageFilterPython.itkShotNoiseImageFilterIUC3IUC3_GetPointer(self) <NEW_LINE> <DEDENT> def New(*args, **kargs): <NEW_LINE> <INDENT> obj = itkShotNoiseImageFilterIUC3IUC3.__New_orig__() <NEW_LINE> import itkTemplate <NEW_LINE> itkTemplate.New(obj, *args, **kargs) <NEW_LINE> return obj <NEW_LINE> <DEDENT> New = staticmethod(New) | Proxy of C++ itkShotNoiseImageFilterIUC3IUC3 class | 62598fa95fc7496912d48229 |
class ClassName: <NEW_LINE> <INDENT> class_variable = 'Class variable' <NEW_LINE> def class_method(self): <NEW_LINE> <INDENT> print('You called the class method') <NEW_LINE> <DEDENT> def print_class_variable(self): <NEW_LINE> <INDENT> print('This is the class variable', self.class_variable) | class-documentation-string | 62598fa9462c4b4f79dbb95a |
class ConstType(Const): <NEW_LINE> <INDENT> pass | -------------------------------------------------------------------------*
Flags for setting to white or black *
-------------------------------------------------------------------------*/
enum {
L_SET_WHITE = 1, /* set pixels to white */
L_SET_BLACK = 2 /* set pixels to black */
}
| 62598fa960cbc95b0636429a |
class AesEnable(Structure): <NEW_LINE> <INDENT> _fields_ = [('Enable', c_uint8, 1), ('Reserved', c_uint8, 6)] <NEW_LINE> _pack_ = 1 | AES Enable (608) Field Definition | 62598fa9ac7a0e7691f72458 |
class GenShellCompletions(argparse.Action): <NEW_LINE> <INDENT> def __call__(self, parser, namespace, values, option_string=None): <NEW_LINE> <INDENT> path = os.path.split(sys.argv[0])[1] <NEW_LINE> c = genzshcomp.CompletionGenerator(path, parser, parser_type='argparse', output_format=values) <NEW_LINE> print(c.get()) <NEW_LINE> sys.exit(0) | Class to generate arguments and exit | 62598fa9e76e3b2f99fd8983 |
class _FileReaderRows: <NEW_LINE> <INDENT> def __init__(self, csvreader): <NEW_LINE> <INDENT> self.data = [] <NEW_LINE> self.maxlength = 0 <NEW_LINE> lineno = 1 <NEW_LINE> try: <NEW_LINE> <INDENT> for line in csvreader: <NEW_LINE> <INDENT> self.maxlength = max(self.maxlength, len(line)) <NEW_LINE> self.data.append(line) <NEW_LINE> lineno += 1 <NEW_LINE> <DEDENT> <DEDENT> except csv.Error as e: <NEW_LINE> <INDENT> raise ImportingError("Error in line %i: %s" % (lineno, str(e))) <NEW_LINE> <DEDENT> self.counter = 0 <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __next__(self): <NEW_LINE> <INDENT> if self.counter == self.maxlength: <NEW_LINE> <INDENT> raise StopIteration <NEW_LINE> <DEDENT> retn = [] <NEW_LINE> for row in self.data: <NEW_LINE> <INDENT> if self.counter >= len(row): <NEW_LINE> <INDENT> retn.append('') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> retn.append(row[self.counter]) <NEW_LINE> <DEDENT> <DEDENT> self.counter += 1 <NEW_LINE> return retn | Read a CSV file in columns. This acts as an iterator.
This means we have to read the whole file in, then return cols :-( | 62598fa98da39b475be03131 |
class Change(ModelNormal): <NEW_LINE> <INDENT> allowed_values = { } <NEW_LINE> validations = { } <NEW_LINE> additional_properties_type = None <NEW_LINE> _nullable = False <NEW_LINE> @cached_property <NEW_LINE> def openapi_types(): <NEW_LINE> <INDENT> return { 'parameter': (str,), 'current_value': (str,), 'requested_value': (str,), } <NEW_LINE> <DEDENT> @cached_property <NEW_LINE> def discriminator(): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> attribute_map = { 'parameter': 'parameter', 'current_value': 'currentValue', 'requested_value': 'requestedValue', } <NEW_LINE> _composed_schemas = {} <NEW_LINE> required_properties = set([ '_data_store', '_check_type', '_spec_property_naming', '_path_to_item', '_configuration', '_visited_composed_classes', ]) <NEW_LINE> @convert_js_args_to_python_args <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> _check_type = kwargs.pop('_check_type', True) <NEW_LINE> _spec_property_naming = kwargs.pop('_spec_property_naming', False) <NEW_LINE> _path_to_item = kwargs.pop('_path_to_item', ()) <NEW_LINE> _configuration = kwargs.pop('_configuration', None) <NEW_LINE> _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) <NEW_LINE> if args: <NEW_LINE> <INDENT> raise ApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, ), path_to_item=_path_to_item, valid_classes=(self.__class__,), ) <NEW_LINE> <DEDENT> self._data_store = {} <NEW_LINE> self._check_type = _check_type <NEW_LINE> self._spec_property_naming = _spec_property_naming <NEW_LINE> self._path_to_item = _path_to_item <NEW_LINE> self._configuration = _configuration <NEW_LINE> self._visited_composed_classes = _visited_composed_classes + (self.__class__,) <NEW_LINE> for var_name, var_value in kwargs.items(): <NEW_LINE> <INDENT> if var_name not in self.attribute_map and self._configuration is not None and self._configuration.discard_unknown_keys and self.additional_properties_type is None: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> setattr(self, var_name, var_value) | NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
with a capitalized key describing the allowed value and an allowed
value. These dicts store the allowed enum values.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
discriminator_value_class_map (dict): A dict to go from the discriminator
variable value to the discriminator class name.
validations (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values. | 62598fa97047854f4633f327 |
class TwoLineListItem(BaseListItem): <NEW_LINE> <INDENT> _txt_top_pad = NumericProperty("20dp") <NEW_LINE> _txt_bot_pad = NumericProperty("15dp") <NEW_LINE> _height = NumericProperty() <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super().__init__(**kwargs) <NEW_LINE> self.height = dp(72) if not self._height else self._height | A two line list item. | 62598fa9cb5e8a47e493c11f |
class UnknownTrackType(Error): <NEW_LINE> <INDENT> pass | A subclass of `Error` raised if a file is of an unsupported type. | 62598fa9cc0a2c111447af5e |
class SnapshotCreateError(ProminenceError): <NEW_LINE> <INDENT> pass | Raised when there is an error creating a snapshot | 62598fa9435de62698e9bd44 |
class TextSegmentWithTwoTargetsAdmin(BaseMetadataAdmin): <NEW_LINE> <INDENT> list_display = [ '__str__', 'itemID', 'itemType', 'segmentID', 'segmentText', 'target1ID', 'target1Text', 'target2ID', 'target2Text' ] + BaseMetadataAdmin.list_display <NEW_LINE> list_filter = [ 'metadata__corpusName', 'metadata__versionInfo', 'metadata__market__sourceLanguageCode', 'metadata__market__targetLanguageCode', 'metadata__market__domainName', 'itemType' ] + BaseMetadataAdmin.list_filter <NEW_LINE> search_fields = [ 'segmentID', 'segmentText', 'target1ID', 'target1Text', 'target2ID', 'target2Text' ] + BaseMetadataAdmin.search_fields <NEW_LINE> fieldsets = ( (None, { 'fields': (['metadata', 'itemID', 'itemType', 'segmentID', 'segmentText', 'target1ID', 'target1Text', 'target2ID', 'target2Text']) }), ) + BaseMetadataAdmin.fieldsets | Model admin for TextPair instances. | 62598fa92c8b7c6e89bd3713 |
class TestCollatz(TestCase): <NEW_LINE> <INDENT> def test_read_1(self): <NEW_LINE> <INDENT> temp1 = "70 70000\n" <NEW_LINE> temp2, temp3 = collatz_read(temp1) <NEW_LINE> self.assertEqual(temp2, 70) <NEW_LINE> self.assertEqual(temp3, 70000) <NEW_LINE> <DEDENT> def test_read_2(self): <NEW_LINE> <INDENT> temp1 = "1234 95685\n" <NEW_LINE> temp2, temp3 = collatz_read(temp1) <NEW_LINE> self.assertEqual(temp2, 1234) <NEW_LINE> self.assertEqual(temp3, 95685) <NEW_LINE> <DEDENT> def test_eval_1(self): <NEW_LINE> <INDENT> temp = collatz_eval(796489, 910767) <NEW_LINE> self.assertEqual(temp, 525) <NEW_LINE> <DEDENT> def test_eval_2(self): <NEW_LINE> <INDENT> temp = collatz_eval(85371, 230974) <NEW_LINE> self.assertEqual(temp, 443) <NEW_LINE> <DEDENT> def test_eval_3(self): <NEW_LINE> <INDENT> temp = collatz_eval(185217, 663797) <NEW_LINE> self.assertEqual(temp, 509) <NEW_LINE> <DEDENT> def test_eval_4(self): <NEW_LINE> <INDENT> temp = collatz_eval(100, 100) <NEW_LINE> self.assertEqual(temp, 26) <NEW_LINE> <DEDENT> def test_eval_5(self): <NEW_LINE> <INDENT> temp = collatz_eval(1, 1000000) <NEW_LINE> self.assertEqual(temp, 525) <NEW_LINE> <DEDENT> def test_helper_1(self): <NEW_LINE> <INDENT> temp = eval_helper(1) <NEW_LINE> self.assertEqual(temp, 1) <NEW_LINE> <DEDENT> def test_helper_2(self): <NEW_LINE> <INDENT> temp = eval_helper(3) <NEW_LINE> self.assertEqual(temp, 8) <NEW_LINE> <DEDENT> def test_helper_3(self): <NEW_LINE> <INDENT> temp = eval_helper(500) <NEW_LINE> self.assertEqual(temp, 111) <NEW_LINE> <DEDENT> def test_helper_4(self): <NEW_LINE> <INDENT> temp = eval_helper(1000) <NEW_LINE> self.assertEqual(temp, 112) <NEW_LINE> <DEDENT> def test_print_1(self): <NEW_LINE> <INDENT> temp1 = StringIO() <NEW_LINE> collatz_print(temp1, 1234, 1234, 133) <NEW_LINE> self.assertEqual(temp1.getvalue(), "1234 1234 133\n") <NEW_LINE> <DEDENT> def test_print_2(self): <NEW_LINE> <INDENT> temp1 = StringIO() <NEW_LINE> collatz_print(temp1, 1, 1, 1) <NEW_LINE> self.assertEqual(temp1.getvalue(), "1 1 1\n") <NEW_LINE> <DEDENT> def test_print_3(self): <NEW_LINE> <INDENT> temp1 = StringIO() <NEW_LINE> collatz_print(temp1, 666, 666, 114) <NEW_LINE> self.assertEqual(temp1.getvalue(), "666 666 114\n") <NEW_LINE> <DEDENT> def test_solve(self): <NEW_LINE> <INDENT> read = StringIO("796489 910767\n85371 230974\n663797 185217\n140945 399307\n") <NEW_LINE> write = StringIO() <NEW_LINE> collatz_solve(read, write) <NEW_LINE> self.assertEqual(write.getvalue(), "796489 910767 525\n85371 230974 443\n663797 185217 509\n140945 399307 443\n") | docstring | 62598fa92c8b7c6e89bd3714 |
class AvailabilityHomeView(MonthCalendarMixin, WeekWithAvailabilityMixin, generic.TemplateView): <NEW_LINE> <INDENT> template_name = 'shifts/availability.html' <NEW_LINE> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super().get_context_data(**kwargs) <NEW_LINE> week = self.get_week_calendar() <NEW_LINE> context['week'] = self.get_week_calendar() <NEW_LINE> context['month'] = self.get_month_calendar() <NEW_LINE> context['week_row'] = zip( week['week_names'], week['days'], week['availability_list'], ) <NEW_LINE> context['user'] = self.request.user <NEW_LINE> return context | home view for availability input | 62598fa966673b3332c30319 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.