code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
@python_2_unicode_compatible <NEW_LINE> class link_attribute_type(models.Model): <NEW_LINE> <INDENT> id = models.AutoField(primary_key=True) <NEW_LINE> parent = models.ForeignKey('self', related_name='children', null=True) <NEW_LINE> root = models.ForeignKey('self', null=True) <NEW_LINE> child_order = models.IntegerField(default=0) <NEW_LINE> gid = models.UUIDField(default=uuid.uuid4) <NEW_LINE> name = models.CharField(max_length=255) <NEW_LINE> description = models.TextField(null=True) <NEW_LINE> last_updated = models.DateTimeField(auto_now=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> db_table = 'link_attribute_type'
Not all parameters are listed here, only those that present some interest in their Django implementation. :param gid: this is interesting because it cannot be NULL but a default is not defined in SQL. The default `uuid.uuid4` in Django will generate a UUID during the creation of an instance.
62598f9e6aa9bd52df0d4cca
class writeabledict(dict): <NEW_LINE> <INDENT> pass
dict with all (especially write) methods allowed by security
62598f9e3d592f4c4edbaccb
class DiceLoss(keras.losses.Loss): <NEW_LINE> <INDENT> def __init__(self, eps=1e-8,log_cosh=False, **kwargs): <NEW_LINE> <INDENT> self.eps = eps <NEW_LINE> self.log_cosh = log_cosh <NEW_LINE> super().__init__(**kwargs) <NEW_LINE> <DEDENT> def call(self, y_true, y_pred): <NEW_LINE> <INDENT> num_classes = tf.shape(y_pred)[-1] <NEW_LINE> y_true = tf.one_hot(y_true, depth=num_classes) <NEW_LINE> input_soft= tf.nn.softmax(y_pred, axis=-1) <NEW_LINE> intersection = tf.reduce_sum(input_soft * y_true, axis=-1) <NEW_LINE> cardinality = tf.reduce_sum(input_soft + y_true, axis=-1) <NEW_LINE> dice_score = 2. * intersection / (cardinality + self.eps) <NEW_LINE> dice_loss = tf.reduce_mean(-dice_score + 1.) <NEW_LINE> if self.log_cosh: <NEW_LINE> <INDENT> return tf.math.log((tf.exp(dice_loss) + tf.exp(-dice_loss)) / 2.0) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return dice_loss <NEW_LINE> <DEDENT> <DEDENT> def get_config(self): <NEW_LINE> <INDENT> base_config = super().get_config() <NEW_LINE> return { **base_config, "eps": self.eps, "log_cosh": self.log_cosh }
Dice loss for segmentation task
62598f9e76e4537e8c3ef3b4
class GitImportRequest(Model): <NEW_LINE> <INDENT> _attribute_map = { '_links': {'key': '_links', 'type': 'ReferenceLinks'}, 'detailed_status': {'key': 'detailedStatus', 'type': 'GitImportStatusDetail'}, 'import_request_id': {'key': 'importRequestId', 'type': 'int'}, 'parameters': {'key': 'parameters', 'type': 'GitImportRequestParameters'}, 'repository': {'key': 'repository', 'type': 'GitRepository'}, 'status': {'key': 'status', 'type': 'object'}, 'url': {'key': 'url', 'type': 'str'} } <NEW_LINE> def __init__(self, _links=None, detailed_status=None, import_request_id=None, parameters=None, repository=None, status=None, url=None): <NEW_LINE> <INDENT> super(GitImportRequest, self).__init__() <NEW_LINE> self._links = _links <NEW_LINE> self.detailed_status = detailed_status <NEW_LINE> self.import_request_id = import_request_id <NEW_LINE> self.parameters = parameters <NEW_LINE> self.repository = repository <NEW_LINE> self.status = status <NEW_LINE> self.url = url
GitImportRequest. :param _links: Links to related resources. :type _links: :class:`ReferenceLinks <git.v4_1.models.ReferenceLinks>` :param detailed_status: Detailed status of the import, including the current step and an error message, if applicable. :type detailed_status: :class:`GitImportStatusDetail <git.v4_1.models.GitImportStatusDetail>` :param import_request_id: The unique identifier for this import request. :type import_request_id: int :param parameters: Parameters for creating the import request. :type parameters: :class:`GitImportRequestParameters <git.v4_1.models.GitImportRequestParameters>` :param repository: The target repository for this import. :type repository: :class:`GitRepository <git.v4_1.models.GitRepository>` :param status: Current status of the import. :type status: object :param url: A link back to this import request resource. :type url: str
62598f9e63d6d428bbee25af
class TemplatesSourceFiles: <NEW_LINE> <INDENT> def __init__(self, templates_directory): <NEW_LINE> <INDENT> self.templates_directory = templates_directory <NEW_LINE> <DEDENT> @property <NEW_LINE> def imports_(self): <NEW_LINE> <INDENT> return self.templates_directory + 'client/imports.txt' <NEW_LINE> <DEDENT> @property <NEW_LINE> def class_(self): <NEW_LINE> <INDENT> return self.templates_directory + 'client/class.txt' <NEW_LINE> <DEDENT> @property <NEW_LINE> def property_(self): <NEW_LINE> <INDENT> return self.templates_directory + 'client/property.txt' <NEW_LINE> <DEDENT> @property <NEW_LINE> def request_(self): <NEW_LINE> <INDENT> return self.templates_directory + 'client/request.txt' <NEW_LINE> <DEDENT> @property <NEW_LINE> def api_client(self): <NEW_LINE> <INDENT> return self.templates_directory + 'client/api_client.txt' <NEW_LINE> <DEDENT> @property <NEW_LINE> def init_(self): <NEW_LINE> <INDENT> return self.templates_directory + 'package/init.txt' <NEW_LINE> <DEDENT> @property <NEW_LINE> def setup_(self): <NEW_LINE> <INDENT> return self.templates_directory + 'package/setup.txt' <NEW_LINE> <DEDENT> @property <NEW_LINE> def licence_(self): <NEW_LINE> <INDENT> return self.templates_directory + 'package/license.txt' <NEW_LINE> <DEDENT> @property <NEW_LINE> def requirements_(self): <NEW_LINE> <INDENT> return self.templates_directory + 'package/requirements.txt' <NEW_LINE> <DEDENT> @property <NEW_LINE> def pypirc_(self): <NEW_LINE> <INDENT> return self.templates_directory + 'pypi/pypirc.txt'
Source files of needed templates handler.
62598f9e656771135c489481
class MySensorsIRSwitch(MySensorsSwitch): <NEW_LINE> <INDENT> def __init__(self, *args): <NEW_LINE> <INDENT> super().__init__(*args) <NEW_LINE> self._ir_code = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_on(self): <NEW_LINE> <INDENT> set_req = self.gateway.const.SetReq <NEW_LINE> return self._values.get(set_req.V_LIGHT) == STATE_ON <NEW_LINE> <DEDENT> async def async_turn_on(self, **kwargs): <NEW_LINE> <INDENT> set_req = self.gateway.const.SetReq <NEW_LINE> if ATTR_IR_CODE in kwargs: <NEW_LINE> <INDENT> self._ir_code = kwargs[ATTR_IR_CODE] <NEW_LINE> <DEDENT> self.gateway.set_child_value( self.node_id, self.child_id, self.value_type, self._ir_code ) <NEW_LINE> self.gateway.set_child_value( self.node_id, self.child_id, set_req.V_LIGHT, 1, ack=1 ) <NEW_LINE> if self.gateway.optimistic: <NEW_LINE> <INDENT> self._values[self.value_type] = self._ir_code <NEW_LINE> self._values[set_req.V_LIGHT] = STATE_ON <NEW_LINE> self.async_write_ha_state() <NEW_LINE> await self.async_turn_off() <NEW_LINE> <DEDENT> <DEDENT> async def async_turn_off(self, **kwargs): <NEW_LINE> <INDENT> set_req = self.gateway.const.SetReq <NEW_LINE> self.gateway.set_child_value( self.node_id, self.child_id, set_req.V_LIGHT, 0, ack=1 ) <NEW_LINE> if self.gateway.optimistic: <NEW_LINE> <INDENT> self._values[set_req.V_LIGHT] = STATE_OFF <NEW_LINE> self.async_write_ha_state() <NEW_LINE> <DEDENT> <DEDENT> async def async_update(self): <NEW_LINE> <INDENT> await super().async_update() <NEW_LINE> self._ir_code = self._values.get(self.value_type)
IR switch child class to MySensorsSwitch.
62598f9ea8ecb0332587100b
class ClickHandler(logging.Handler): <NEW_LINE> <INDENT> def __init__(self, level=logging.NOTSET, err=True): <NEW_LINE> <INDENT> super(ClickHandler, self).__init__(level=level) <NEW_LINE> self.err = err <NEW_LINE> <DEDENT> def emit(self, record): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> msg = self.format(record) <NEW_LINE> try: <NEW_LINE> <INDENT> self.acquire() <NEW_LINE> click.echo(message=msg, err=self.err) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> self.release() <NEW_LINE> <DEDENT> <DEDENT> except (KeyboardInterrupt, SystemExit): <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> self.handleError(record) <NEW_LINE> <DEDENT> <DEDENT> def createLock(self): <NEW_LINE> <INDENT> self.lock = multiprocessing.RLock()
Logging handler that prints colorful messages with click.echo.
62598f9efbf16365ca793eb7
class ThrowerAnt(Ant): <NEW_LINE> <INDENT> name = 'Thrower' <NEW_LINE> implemented = True <NEW_LINE> damage = 1 <NEW_LINE> food_cost = 3 <NEW_LINE> min_range = 0 <NEW_LINE> max_range = 1000000 <NEW_LINE> def nearest_bee(self, hive): <NEW_LINE> <INDENT> checking_place = self.place <NEW_LINE> location = 0 <NEW_LINE> while 1 > 0: <NEW_LINE> <INDENT> if random_or_none(checking_place.bees) != None and (self.min_range <= location <= self.max_range): <NEW_LINE> <INDENT> return random_or_none(checking_place.bees) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> checking_place = checking_place.entrance <NEW_LINE> location += 1 <NEW_LINE> <DEDENT> if checking_place == hive: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def throw_at(self, target): <NEW_LINE> <INDENT> if target is not None: <NEW_LINE> <INDENT> target.reduce_armor(self.damage) <NEW_LINE> <DEDENT> <DEDENT> def action(self, colony): <NEW_LINE> <INDENT> self.throw_at(self.nearest_bee(colony.hive))
ThrowerAnt throws a leaf each turn at the nearest Bee in its range.
62598f9ee76e3b2f99fd8835
class TempHumidBaro(SensorPacket): <NEW_LINE> <INDENT> TYPES = {0x01: 'BTHR918', 0x02: 'BTHR918N, BTHR968'} <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return ("TempHumidBaro [subtype={0}, seqnbr={1}, id={2}, temp={3}, " + "humidity={4}, humidity_status={5}, baro={6}, forecast={7}, " + "battery={8}, rssi={9}]") .format(self.type_string, self.seqnbr, self.id_string, self.temp, self.humidity, self.humidity_status, self.baro, self.forecast, self.battery, self.rssi) <NEW_LINE> <DEDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.id1 = None <NEW_LINE> self.id2 = None <NEW_LINE> self.temphigh = None <NEW_LINE> self.templow = None <NEW_LINE> self.temp = None <NEW_LINE> self.humidity = None <NEW_LINE> self.humidity_status = None <NEW_LINE> self.humidity_status_string = None <NEW_LINE> self.baro1 = None <NEW_LINE> self.baro2 = None <NEW_LINE> self.baro = None <NEW_LINE> self.forecast = None <NEW_LINE> self.forecast_string = None <NEW_LINE> self.battery = None <NEW_LINE> <DEDENT> def load_receive(self, data): <NEW_LINE> <INDENT> self.data = data <NEW_LINE> self.packetlength = data[0] <NEW_LINE> self.packettype = data[1] <NEW_LINE> self.subtype = data[2] <NEW_LINE> self.seqnbr = data[3] <NEW_LINE> self.id1 = data[4] <NEW_LINE> self.id2 = data[5] <NEW_LINE> self.temphigh = data[6] <NEW_LINE> self.templow = data[7] <NEW_LINE> self.temp = float(((self.temphigh & 0x7f) << 8) + self.templow) / 10 <NEW_LINE> if self.temphigh >= 0x80: <NEW_LINE> <INDENT> self.temp = -1 * self.temp <NEW_LINE> <DEDENT> self.humidity = data[8] <NEW_LINE> self.humidity_status = data[9] <NEW_LINE> self.baro1 = data[10] <NEW_LINE> self.baro2 = data[11] <NEW_LINE> self.baro = (self.baro1 << 8) + self.baro2 <NEW_LINE> self.forecast = data[12] <NEW_LINE> self.rssi_byte = data[13] <NEW_LINE> self.battery = self.rssi_byte & 0x0f <NEW_LINE> self.rssi = self.rssi_byte >> 4 <NEW_LINE> self._set_strings() <NEW_LINE> <DEDENT> def _set_strings(self): <NEW_LINE> <INDENT> self.id_string = "{0:02x}:{1:02x}".format(self.id1, self.id2) <NEW_LINE> if self.subtype in self.TYPES: <NEW_LINE> <INDENT> self.type_string = self.TYPES[self.subtype] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.type_string = self._UNKNOWN_TYPE.format(self.packettype, self.subtype) <NEW_LINE> <DEDENT> if self.humidity_status in self.HUMIDITY_TYPES: <NEW_LINE> <INDENT> self.humidity_status_string = self.HUMIDITY_TYPES[self.humidity_status] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.humidity_status_string = self.HUMIDITY_TYPES[-1] <NEW_LINE> <DEDENT> if self.forecast in self.FORECAST_TYPES: <NEW_LINE> <INDENT> self.forecast_string = self.FORECAST_TYPES[self.forecast] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.forecast_string = self.FORECAST_TYPES[-1]
Data class for the TempHumidBaro packet type
62598f9ee5267d203ee6b70b
class DiscoverYandexTransport(SensorEntity): <NEW_LINE> <INDENT> def __init__(self, requester: YandexMapsRequester, stop_id, routes, name): <NEW_LINE> <INDENT> self.requester = requester <NEW_LINE> self._stop_id = stop_id <NEW_LINE> self._routes = routes <NEW_LINE> self._state = None <NEW_LINE> self._name = name <NEW_LINE> self._attrs = None <NEW_LINE> <DEDENT> async def async_update(self, *, tries=0): <NEW_LINE> <INDENT> attrs = {} <NEW_LINE> closer_time = None <NEW_LINE> try: <NEW_LINE> <INDENT> yandex_reply = await self.requester.get_stop_info(self._stop_id) <NEW_LINE> <DEDENT> except CaptchaError as ex: <NEW_LINE> <INDENT> _LOGGER.error( "%s. You may need to disable the integration for some time", ex, ) <NEW_LINE> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> data = yandex_reply["data"] <NEW_LINE> <DEDENT> except KeyError as key_error: <NEW_LINE> <INDENT> _LOGGER.warning( "Exception KeyError was captured, missing key is %s. Yandex returned: %s", key_error, yandex_reply, ) <NEW_LINE> if tries > 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> await self.requester.set_new_session() <NEW_LINE> await self.async_update(tries=tries + 1) <NEW_LINE> return <NEW_LINE> <DEDENT> stop_name = data["name"] <NEW_LINE> transport_list = data["transports"] <NEW_LINE> for transport in transport_list: <NEW_LINE> <INDENT> for thread in transport["threads"]: <NEW_LINE> <INDENT> if "Events" not in thread["BriefSchedule"]: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if thread.get("noBoarding") is True: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> for event in thread["BriefSchedule"]["Events"]: <NEW_LINE> <INDENT> if "railway" in transport["Types"]: <NEW_LINE> <INDENT> route = " - ".join( [x["name"] for x in thread["EssentialStops"]] ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> route = transport["name"] <NEW_LINE> <DEDENT> if self._routes and route not in self._routes: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if "Estimated" not in event and "Scheduled" not in event: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> departure = event.get("Estimated") or event["Scheduled"] <NEW_LINE> posix_time_next = int(departure["value"]) <NEW_LINE> if closer_time is None or closer_time > posix_time_next: <NEW_LINE> <INDENT> closer_time = posix_time_next <NEW_LINE> <DEDENT> if route not in attrs: <NEW_LINE> <INDENT> attrs[route] = [] <NEW_LINE> <DEDENT> attrs[route].append(departure["text"]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> attrs[STOP_NAME] = stop_name <NEW_LINE> attrs[ATTR_ATTRIBUTION] = ATTRIBUTION <NEW_LINE> if closer_time is None: <NEW_LINE> <INDENT> self._state = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._state = dt_util.utc_from_timestamp(closer_time).replace(microsecond=0) <NEW_LINE> <DEDENT> self._attrs = attrs <NEW_LINE> <DEDENT> @property <NEW_LINE> def native_value(self): <NEW_LINE> <INDENT> return self._state <NEW_LINE> <DEDENT> @property <NEW_LINE> def device_class(self): <NEW_LINE> <INDENT> return DEVICE_CLASS_TIMESTAMP <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @property <NEW_LINE> def extra_state_attributes(self): <NEW_LINE> <INDENT> return self._attrs <NEW_LINE> <DEDENT> @property <NEW_LINE> def icon(self): <NEW_LINE> <INDENT> return ICON
Implementation of yandex_transport sensor.
62598f9ed7e4931a7ef3be96
class MotorMixDriver: <NEW_LINE> <INDENT> def __init__(self, strips): <NEW_LINE> <INDENT> self.__strips = strips <NEW_LINE> self.__currStripIndex = 0 <NEW_LINE> <DEDENT> def getStrip(self, i): <NEW_LINE> <INDENT> return self.__strips[i] <NEW_LINE> <DEDENT> def ctrlIn(self, ctrl, val): <NEW_LINE> <INDENT> if ctrl == IN_BLOCKSELECT_CTRL: <NEW_LINE> <INDENT> if val >= 0 and val < NUM_STRIPS: <NEW_LINE> <INDENT> self.__currStripIndex = val <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print >> sys.stderr, "channel strip number out of range: %d" % val <NEW_LINE> <DEDENT> <DEDENT> elif ctrl == IN_SWITCH_CTRL: <NEW_LINE> <INDENT> strip = self.__strips[self.__currStripIndex] <NEW_LINE> if val == ON_BASE: <NEW_LINE> <INDENT> strip.doTouch(True) <NEW_LINE> <DEDENT> elif val > ON_BASE and val < ON_BASE + NUM_STRIPLEDS + 1: <NEW_LINE> <INDENT> strip.doPress(BUTTONVALTOROW[val - ON_BASE], True) <NEW_LINE> <DEDENT> elif val == OFF_BASE: <NEW_LINE> <INDENT> strip.doTouch(False) <NEW_LINE> <DEDENT> elif val > OFF_BASE and val < OFF_BASE + NUM_STRIPLEDS + 1: <NEW_LINE> <INDENT> strip.doPress(BUTTONVALTOROW[val - OFF_BASE], False) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print >> sys.stderr, "channel LED index out of range: %d" % val <NEW_LINE> <DEDENT> <DEDENT> elif ctrl >= FADER_MSB_BASE_CTRL and ctrl < FADER_MSB_BASE_CTRL + NUM_STRIPS: <NEW_LINE> <INDENT> strip = self.__strips[ctrl - FADER_MSB_BASE_CTRL] <NEW_LINE> strip.doFader(val) <NEW_LINE> <DEDENT> elif ctrl >= FADER_LSB_BASE_CTRL and ctrl < FADER_LSB_BASE_CTRL + NUM_STRIPS: <NEW_LINE> <INDENT> pass
MIDI receiver wrapped around an array of strip receivers. We currently ignore events for the mini-buttons (blocks 8 to 11 inclusive). >>> sr = StripDriver(None, 3) >>> def press(idx, how): print "[press %d -> %d]" % (idx, how) >>> sr.doPress = press >>> strips = [StripDriver(None, i) for i in range(8)] >>> strips[3] = sr >>> mmr = MotorMixDriver(strips) >>> mmr.ctrlIn(0x0F, 3) >>> mmr.ctrlIn(0x2F, 0x43) [press 3 -> 1] >>> mmr.ctrlIn(0x2F, 0x04) [press 1 -> 0] >>> sr = StripDriver(None, 5) >>> def touch(how): print "[touch %d]" % how >>> sr.doTouch = touch >>> strips = [StripDriver(None, i) for i in range(8)] >>> strips[5] = sr >>> mmr = MotorMixDriver(strips) >>> mmr.ctrlIn(0x0F, 5) >>> mmr.ctrlIn(0x2F, 0x40) [touch 1] >>> mmr.ctrlIn(0x2F, 0x00) [touch 0] >>> sr = StripDriver(None, 6) >>> def fader(pos): print "[fader %d]" % pos >>> sr.doFader = fader >>> strips = [StripDriver(None, i) for i in range(8)] >>> strips[6] = sr >>> mmr = MotorMixDriver(strips) >>> mmr.ctrlIn(0x06, 23) [fader 23] >>> mmr.ctrlIn(0x26, 00)
62598f9e45492302aabfc2d4
class IMDBTitleBasics(db.Model): <NEW_LINE> <INDENT> __tablename__ = 'imdb_title_basics' <NEW_LINE> tconst = db.Column(db.Integer, primary_key=True, autoincrement=True) <NEW_LINE> titleType = db.Column(db.String, default='Movie') <NEW_LINE> primaryTitle = db.Column(db.String, nullable=False) <NEW_LINE> originalTitle = db.Column(db.String, nullable=False) <NEW_LINE> isAdult = db.Column(db.Boolean, default=False) <NEW_LINE> startYear = db.Column(db.Integer, nullable=False) <NEW_LINE> endYear = db.Column(db.String, nullable=True) <NEW_LINE> runtimeMinutes = db.Column(db.Integer, nullable=True) <NEW_LINE> genres = db.Column(db.String, default='user') <NEW_LINE> crew = db.relationship("IMDBTitleCrew", backref="imdb_title_crew", lazy="joined") <NEW_LINE> ratings = db.relationship("IMDBTitleRatings", backref="imdb_title_ratings", lazy="joined") <NEW_LINE> def __init__(self, title_id, titleType, primaryTitle, originalTitle, isAdult, startYear, endYear, runtimeMinutes, genres): <NEW_LINE> <INDENT> self.title_id = title_id <NEW_LINE> self.titleType = titleType <NEW_LINE> self.primaryTitle = primaryTitle <NEW_LINE> self.originalTitle = originalTitle <NEW_LINE> self.isAdult = isAdult <NEW_LINE> self.startYear = startYear <NEW_LINE> self.endYear = endYear <NEW_LINE> self.runtimeMinutes = runtimeMinutes <NEW_LINE> self.genres = genres <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return u'<Title {}>'.format(self.primaryTitle)
Contains the imdb titles information
62598f9e8c0ade5d55dc358e
class HelloWorldBlock(XBlock): <NEW_LINE> <INDENT> def fallback_view(self, _view_name, context): <NEW_LINE> <INDENT> return Fragment(u"Hello, world!")
A simple block: just show some fixed content.
62598f9e7cff6e4e811b5821
class AuthorAdmin(MonitorAdmin): <NEW_LINE> <INDENT> list_display = ('__unicode__',)
Monitored model. So the admin inherited from MonitorAdmin.
62598f9e796e427e5384e591
class BTModel(model.Model): <NEW_LINE> <INDENT> def __init__(self, beta=0., rd=0., H=1., U=0., **kwargs): <NEW_LINE> <INDENT> self.beta = beta <NEW_LINE> self.rd = rd <NEW_LINE> self.H = H <NEW_LINE> self.Hi = np.array(H)[np.newaxis,...] <NEW_LINE> self.U = U <NEW_LINE> self.nz = 1 <NEW_LINE> if rd: <NEW_LINE> <INDENT> self.kd2 = rd**-2 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.kd2 = 0. <NEW_LINE> <DEDENT> super(BTModel, self).__init__(**kwargs) <NEW_LINE> self.set_q(1e-3*np.random.rand(1,self.ny,self.nx)) <NEW_LINE> <DEDENT> def _initialize_background(self): <NEW_LINE> <INDENT> self.Qy = np.asarray(self.beta)[np.newaxis, ...] <NEW_LINE> self.set_U(self.U) <NEW_LINE> self.ikQy = self.Qy * 1j * self.k <NEW_LINE> self.ilQx = 0. <NEW_LINE> <DEDENT> def _initialize_inversion_matrix(self): <NEW_LINE> <INDENT> self.a = -(self.wv2i+self.kd2)[np.newaxis, np.newaxis, :, :] <NEW_LINE> <DEDENT> def _initialize_forcing(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def set_U(self, U): <NEW_LINE> <INDENT> self.Ubg = np.asarray(U)[np.newaxis, ...] <NEW_LINE> <DEDENT> def _calc_diagnostics(self): <NEW_LINE> <INDENT> if (self.t>=self.dt) and (self.tc%self.taveints==0): <NEW_LINE> <INDENT> self._increment_diagnostics() <NEW_LINE> <DEDENT> <DEDENT> def _calc_cfl(self): <NEW_LINE> <INDENT> return np.abs( np.hstack([self.u + self.Ubg, self.v]) ).max()*self.dt/self.dx <NEW_LINE> <DEDENT> def _calc_ke(self): <NEW_LINE> <INDENT> ke = .5*self.spec_var(self.wv*self.ph) <NEW_LINE> return ke.sum() <NEW_LINE> <DEDENT> def _calc_eddy_time(self): <NEW_LINE> <INDENT> ens = .5*self.H * self.spec_var(self.wv2*self.ph) <NEW_LINE> return 2.*pi*np.sqrt( self.H / ens ) / year
Single-layer (barotropic) quasigeostrophic model. This class can represent both pure two-dimensional flow and also single reduced-gravity layers with deformation radius ``rd``. The equivalent-barotropic quasigeostrophic evolution equations is .. math:: \partial_t q + J(\psi, q ) + \beta \psi_x = \text{ssd} The potential vorticity anomaly is .. math:: q = \nabla^2 \psi - \kappa_d^2 \psi
62598f9ef7d966606f747de5
class ParticipantAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> list_display = ('name', 'email', 'affiliation') <NEW_LINE> search_fields = ('name', 'affiliation')
Administration interface for participants.
62598f9e8e7ae83300ee8e9e
class Script: <NEW_LINE> <INDENT> def __init__(self, flavor): <NEW_LINE> <INDENT> self.events = {} <NEW_LINE> self.integers = [] <NEW_LINE> self.strings = [] <NEW_LINE> self.variables = [] <NEW_LINE> self.targets = [] <NEW_LINE> self.builtins = [] <NEW_LINE> self.flavor = flavor <NEW_LINE> self.code = [] <NEW_LINE> <DEDENT> def get_event_target(self, name): <NEW_LINE> <INDENT> return Target(self, self.events[name]) <NEW_LINE> <DEDENT> def dump(self, out=None): <NEW_LINE> <INDENT> from .parser import Kind, quote_string <NEW_LINE> if out is None: <NEW_LINE> <INDENT> out = sys.stdout <NEW_LINE> <DEDENT> evl = {} <NEW_LINE> for name, offset in self.events.items(): <NEW_LINE> <INDENT> evl[offset] = '\non ' + name <NEW_LINE> <DEDENT> for script, offset in self.targets: <NEW_LINE> <INDENT> if script is not self: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if offset in evl: <NEW_LINE> <INDENT> evl[offset] += '\nlabel #%d' % offset <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> evl[offset] = '\nlabel #%d' % offset <NEW_LINE> <DEDENT> <DEDENT> evl[0] = evl[0][1:] <NEW_LINE> for offset, (opi, arg) in enumerate(self.code): <NEW_LINE> <INDENT> if offset in evl: <NEW_LINE> <INDENT> print(evl[offset], file=out) <NEW_LINE> <DEDENT> func = self.flavor._funcs[opi] <NEW_LINE> name = func.__name__ <NEW_LINE> assert self.flavor._indices[name] == opi <NEW_LINE> kind = self.flavor._kinds[name] <NEW_LINE> if kind is Kind.LOCATION: <NEW_LINE> <INDENT> lscr, loff = self.targets[arg] <NEW_LINE> if lscr is self: <NEW_LINE> <INDENT> loc = '#%d' % loff <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for lscrn, lscrp in self.flavor._scripts.items(): <NEW_LINE> <INDENT> if lscrp is lscr: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> assert False, 'Bad script: %s' % lscr <NEW_LINE> <DEDENT> for evn, evo in script.events.items(): <NEW_LINE> <INDENT> if evo == loff: <NEW_LINE> <INDENT> loc = '%s.%s' % (lscrn, evn) <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> assert False, 'No such event: %s' % loff <NEW_LINE> <DEDENT> <DEDENT> print(name, loc, file=out) <NEW_LINE> <DEDENT> elif kind is Kind.INTEGER: <NEW_LINE> <INDENT> print(name, self.integers[arg], file=out) <NEW_LINE> <DEDENT> elif kind is Kind.STRING: <NEW_LINE> <INDENT> print(name, quote_string(self.strings[arg]), file=out) <NEW_LINE> <DEDENT> elif kind is Kind.VARIABLE: <NEW_LINE> <INDENT> print(name, self.variables[arg], file=out) <NEW_LINE> <DEDENT> elif kind is Kind.BUILTIN: <NEW_LINE> <INDENT> print(name, self.builtins[arg].__name__, file=out) <NEW_LINE> <DEDENT> elif kind is Kind.NONE: <NEW_LINE> <INDENT> assert arg == 0 <NEW_LINE> print(name, file=out) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert False, 'Bad kind: %s' % kind
A sequence of instructions and associated data.
62598f9e91f36d47f2230d9f
class rgb24: <NEW_LINE> <INDENT> def __init__(self, r=[0, 0, 0], g=None, b=None): <NEW_LINE> <INDENT> if(isinstance(r, list) and g is None and b is None): <NEW_LINE> <INDENT> self.value = r <NEW_LINE> <DEDENT> elif(isinstance(r, (int,long)) and isinstance(g, (int,long)) and isinstance(b, (int,long))): <NEW_LINE> <INDENT> self.value = [r, g, b] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.value = [0, 0, 0] <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return 'rgb24[R:%d, G:%d, B:%d]' % (self.value[0], self.value[1], self.value[2]) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> assert isinstance(other, rgb24) <NEW_LINE> return self.value == other.value <NEW_LINE> <DEDENT> def __add__(self, other): <NEW_LINE> <INDENT> assert isinstance(other, rgb24) <NEW_LINE> return self.value + other.value <NEW_LINE> <DEDENT> def __sub__(self, other): <NEW_LINE> <INDENT> assert isinstance(other, rgb24) <NEW_LINE> return self.value - other.value <NEW_LINE> <DEDENT> def setValue(self, value): <NEW_LINE> <INDENT> assert isinstance(value, list) <NEW_LINE> if(len(value) == 3): <NEW_LINE> <INDENT> self.value = value <NEW_LINE> <DEDENT> <DEDENT> def setRGB(self, r, g, b): <NEW_LINE> <INDENT> self.value = [r, g, b] <NEW_LINE> <DEDENT> def setRed(self, r): <NEW_LINE> <INDENT> self.value[0] = r <NEW_LINE> <DEDENT> def setGreen(self, g): <NEW_LINE> <INDENT> self.value[1] = r <NEW_LINE> <DEDENT> def setBlue(self, b): <NEW_LINE> <INDENT> self.value[2] = r <NEW_LINE> <DEDENT> def getRGB(self): <NEW_LINE> <INDENT> return self.value <NEW_LINE> <DEDENT> def getRed(self): <NEW_LINE> <INDENT> return self.value[0] <NEW_LINE> <DEDENT> def getGreen(self): <NEW_LINE> <INDENT> return self.value[1] <NEW_LINE> <DEDENT> def getBlue(self): <NEW_LINE> <INDENT> return self.value[2]
24bit pixel color value class for LEDMatrix.
62598f9ed7e4931a7ef3be97
class PybridReport(object): <NEW_LINE> <INDENT> def write(self, output_dir): <NEW_LINE> <INDENT> if hasattr(self, 'write_string'): <NEW_LINE> <INDENT> res_string = self.write_string(output_dir) <NEW_LINE> f = file(os.path.join(output_dir, 'index.html'), 'w') <NEW_LINE> f.write(res_string) <NEW_LINE> f.close() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> <DEDENT> def _get_metadata(self, name): <NEW_LINE> <INDENT> if hasattr(self, name): <NEW_LINE> <INDENT> return getattr(self, name) <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def get_author(self): <NEW_LINE> <INDENT> return self._get_metadata('AUTHOR') <NEW_LINE> <DEDENT> def get_name(self): <NEW_LINE> <INDENT> return self._get_metadata('NAME') <NEW_LINE> <DEDENT> def get_groups(self): <NEW_LINE> <INDENT> return self._get_metadata('GROUPS')
The base class for pybrid reports. A PybridReport mainly just outputs itself when write() is called with an output directory. If you give it a NAME, AUTHOR, or GROUPS, it will return those when requested via get_author, get_name, or get_groups. Lastly, if you implement a write_string() method, PybridReport will call your method and write out your returned string as {output_dir}/index.html.
62598f9e07f4c71912baf249
class UDPEmitter(object): <NEW_LINE> <INDENT> def __init__(self, daemon_address=DEFAULT_DAEMON_ADDRESS): <NEW_LINE> <INDENT> self._socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) <NEW_LINE> self._socket.setblocking(0) <NEW_LINE> self.set_daemon_address(daemon_address) <NEW_LINE> <DEDENT> def send_entity(self, entity): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> message = "%s%s%s" % (PROTOCOL_HEADER, PROTOCOL_DELIMITER, entity.serialize()) <NEW_LINE> log.debug("sending: %s to %s:%s." % (message, self._ip, self._port)) <NEW_LINE> self._send_data(message) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> log.exception("Failed to send entity to Daemon.") <NEW_LINE> <DEDENT> <DEDENT> def set_daemon_address(self, address): <NEW_LINE> <INDENT> if address: <NEW_LINE> <INDENT> daemon_config = DaemonConfig(address) <NEW_LINE> self._ip, self._port = daemon_config.udp_ip, daemon_config.udp_port <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def ip(self): <NEW_LINE> <INDENT> return self._ip <NEW_LINE> <DEDENT> @property <NEW_LINE> def port(self): <NEW_LINE> <INDENT> return self._port <NEW_LINE> <DEDENT> def _send_data(self, data): <NEW_LINE> <INDENT> self._socket.sendto(data.encode('utf-8'), (self._ip, self._port)) <NEW_LINE> <DEDENT> def _parse_address(self, daemon_address): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> val = daemon_address.split(':') <NEW_LINE> return val[0], int(val[1]) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> raise InvalidDaemonAddressException('Invalid daemon address %s specified.' % daemon_address)
The default emitter the X-Ray recorder uses to send segments/subsegments to the X-Ray daemon over UDP using a non-blocking socket. If there is an exception on the actual data transfer between the socket and the daemon, it logs the exception and continue.
62598f9e460517430c431f5a
class MetadataViewer(Gramplet): <NEW_LINE> <INDENT> def init(self): <NEW_LINE> <INDENT> self.gui.WIDGET = self.build_gui() <NEW_LINE> self.gui.get_container_widget().remove(self.gui.textview) <NEW_LINE> self.gui.get_container_widget().add_with_viewport(self.gui.WIDGET) <NEW_LINE> self.gui.WIDGET.show() <NEW_LINE> self.connect_signal('Media', self.update) <NEW_LINE> <DEDENT> def build_gui(self): <NEW_LINE> <INDENT> self.view = MetadataView() <NEW_LINE> return self.view <NEW_LINE> <DEDENT> def main(self): <NEW_LINE> <INDENT> active_handle = self.get_active('Media') <NEW_LINE> media = self.dbstate.db.get_object_from_handle(active_handle) <NEW_LINE> if media: <NEW_LINE> <INDENT> full_path = Utils.media_path_full(self.dbstate.db, media.get_path()) <NEW_LINE> has_data = self.view.display_exif_tags(full_path) <NEW_LINE> self.set_has_data(has_data) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.set_has_data(False) <NEW_LINE> <DEDENT> <DEDENT> def update_has_data(self): <NEW_LINE> <INDENT> active_handle = self.get_active('Media') <NEW_LINE> active = self.dbstate.db.get_object_from_handle(active_handle) <NEW_LINE> self.set_has_data(self.get_has_data(active)) <NEW_LINE> <DEDENT> def get_has_data(self, media): <NEW_LINE> <INDENT> if media is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> full_path = Utils.media_path_full(self.dbstate.db, media.get_path()) <NEW_LINE> return self.view.get_has_data(full_path)
Displays the exif tags of an image.
62598f9e7b25080760ed72a6
@pytest.mark.parametrize("algo", [EmbedGreedy, EmbedBalanced, EmbedILP, EmbedPartition]) <NEW_LINE> class TestGroupInterfaces(object): <NEW_LINE> <INDENT> def test_unfesible(self, algo, virtual_nw): <NEW_LINE> <INDENT> physical_topo = PhysicalNetwork.create_test_nw( cores=4, memory=4000, rate=10000, group_interfaces=False ) <NEW_LINE> prob = algo(virtual_nw, physical_topo) <NEW_LINE> time_solution, status = prob.solve() <NEW_LINE> assert status == Infeasible <NEW_LINE> assert time_solution > 0 <NEW_LINE> <DEDENT> def test_feasible(self, algo, virtual_nw): <NEW_LINE> <INDENT> physical_topo = PhysicalNetwork.create_test_nw( cores=4, memory=4000, rate=10000, group_interfaces=True ) <NEW_LINE> prob = algo(virtual_nw, physical_topo) <NEW_LINE> time_solution, status = prob.solve() <NEW_LINE> assert status == Solved <NEW_LINE> assert time_solution > 0 <NEW_LINE> solution = prob.solution <NEW_LINE> assert solution.node_info("Node_0") != solution.node_info("Node_1") <NEW_LINE> assert len(solution.path_info(("Node_0", "Node_1"))) == 2 <NEW_LINE> for path in solution.path_info(("Node_0", "Node_1")): <NEW_LINE> <INDENT> assert path.f_rate == 0.5 <NEW_LINE> assert len(path.path) == 2 <NEW_LINE> <DEDENT> for link_map in solution.link_info(("Node_0", "Node_1")): <NEW_LINE> <INDENT> assert link_map.s_node == solution.node_info("Node_0") <NEW_LINE> assert link_map.d_node == solution.node_info("Node_1")
Test the group interface option for a physical node.
62598f9e8a43f66fc4bf1f7a
class ReadWriteLock(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._lock = RLock() <NEW_LINE> self._can_read = Semaphore(0) <NEW_LINE> self._can_write = Semaphore(0) <NEW_LINE> self._active_readers = 0 <NEW_LINE> self._active_writers = 0 <NEW_LINE> self._waiting_readers = 0 <NEW_LINE> self._waiting_writers = 0 <NEW_LINE> <DEDENT> def rlock(self): <NEW_LINE> <INDENT> return ReadLock(self) <NEW_LINE> <DEDENT> def rlock_acquire(self): <NEW_LINE> <INDENT> with self._lock: <NEW_LINE> <INDENT> if self._active_writers == 0 and self._waiting_writers == 0: <NEW_LINE> <INDENT> self._active_readers += 1 <NEW_LINE> self._can_read.release() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._waiting_readers += 1 <NEW_LINE> <DEDENT> <DEDENT> self._can_read.acquire() <NEW_LINE> <DEDENT> def rlock_release(self): <NEW_LINE> <INDENT> with self._lock: <NEW_LINE> <INDENT> self._active_readers -= 1 <NEW_LINE> if self._active_readers == 0 and self._waiting_writers != 0: <NEW_LINE> <INDENT> self._active_writers += 1 <NEW_LINE> self._waiting_writers -= 1 <NEW_LINE> self._can_write.release() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def wlock(self): <NEW_LINE> <INDENT> return WriteLock(self) <NEW_LINE> <DEDENT> def wlock_acquire(self): <NEW_LINE> <INDENT> with self._lock: <NEW_LINE> <INDENT> if self._active_writers == 0 and self._waiting_writers == 0 and self._active_readers == 0: <NEW_LINE> <INDENT> self._active_writers += 1 <NEW_LINE> self._can_write.release() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._waiting_writers += 1 <NEW_LINE> <DEDENT> <DEDENT> self._can_write.acquire() <NEW_LINE> <DEDENT> def wlock_release(self): <NEW_LINE> <INDENT> with self._lock: <NEW_LINE> <INDENT> self._active_writers -= 1 <NEW_LINE> if self._waiting_writers != 0: <NEW_LINE> <INDENT> self._active_writers += 1 <NEW_LINE> self._waiting_writers -= 1 <NEW_LINE> self._can_write.release() <NEW_LINE> <DEDENT> elif self._waiting_readers != 0: <NEW_LINE> <INDENT> t = self._waiting_readers <NEW_LINE> self._waiting_readers = 0 <NEW_LINE> self._active_readers += t <NEW_LINE> while t > 0: <NEW_LINE> <INDENT> self._can_read.release() <NEW_LINE> t -= 1
Reader-writer lock with preference to writers.
62598f9e498bea3a75a57920
class DbPackage(db.Model): <NEW_LINE> <INDENT> __tablename__ = 'package' <NEW_LINE> id = db.Column(db.String, primary_key=True) <NEW_LINE> name = db.Column(db.String(120)) <NEW_LINE> stime = db.Column(db.DateTime) <NEW_LINE> duration = db.Column(db.Time) <NEW_LINE> success = db.Column(db.Boolean) <NEW_LINE> version = db.Column(db.String(16)) <NEW_LINE> release_id = db.Column(db.Integer, db.ForeignKey("release.id")) <NEW_LINE> release = db.relationship("DbRelease", backref=db.backref('packages', order_by=id)) <NEW_LINE> def __init__(self, id, release_id, name, version): <NEW_LINE> <INDENT> self.id = id <NEW_LINE> self.name = name <NEW_LINE> self.version = version <NEW_LINE> self.release_id = release_id <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> self.stime = datetime.now() <NEW_LINE> <DEDENT> def stop(self, success): <NEW_LINE> <INDENT> if not self.ftime: <NEW_LINE> <INDENT> self.duration = datetime.now() - self.stime <NEW_LINE> <DEDENT> self.success = success
A deployed instance of a package
62598f9ec432627299fa2dd7
class BackupImage(object): <NEW_LINE> <INDENT> def __init__(self, backup_url): <NEW_LINE> <INDENT> self.url = urlparse.urlparse(backup_url) <NEW_LINE> <DEDENT> def backup_server(self, server, database): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def restore_server(self, server): <NEW_LINE> <INDENT> pass
A backup image.
62598f9e60cbc95b0636414b
class AristotleCompanion(SpecialCompanion): <NEW_LINE> <INDENT> NAME = 'aristotle' <NEW_LINE> def __init__(self, max_charge=6, dot_count=4): <NEW_LINE> <INDENT> super().__init__(ButterflyDot, max_charge, dot_count=dot_count) <NEW_LINE> <DEDENT> def activate(self, game): <NEW_LINE> <INDENT> game.place_random_dots(self._dot_type, kind=0, dot_count=self._dot_count)
Captain America doesn't have a laser gun, but he could give you some Beam Dots
62598f9ecb5e8a47e493c074
class _Completion(base.Completion, collections.namedtuple('_Completion', ( 'terminal_metadata', 'code', 'message', ))): <NEW_LINE> <INDENT> pass
A trivial implementation of base.Completion.
62598f9e7d847024c075c1d1
class BinaryOperatorExpr(Expr): <NEW_LINE> <INDENT> def __init__(self, op, left, right): <NEW_LINE> <INDENT> self.op = op <NEW_LINE> self.left = left <NEW_LINE> self.right = right <NEW_LINE> <DEDENT> def evaluate(self, node, pos, size, context): <NEW_LINE> <INDENT> return self.operate(self.left.evaluate(node, pos, size, context), self.right.evaluate(node, pos, size, context)) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '(%s %s %s)' % (self.left, self.op, self.right)
Base class for all binary operators.
62598f9e44b2445a339b686d
class TextTranslateBatchResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Source = None <NEW_LINE> self.Target = None <NEW_LINE> self.TargetTextList = None <NEW_LINE> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.Source = params.get("Source") <NEW_LINE> self.Target = params.get("Target") <NEW_LINE> self.TargetTextList = params.get("TargetTextList") <NEW_LINE> self.RequestId = params.get("RequestId")
TextTranslateBatch返回参数结构体
62598f9ea8ecb0332587100d
class Scorer: <NEW_LINE> <INDENT> def score_prefix(self, prefix): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def final_prefix_score(self, prefix): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def is_valid_prefix(self, value): <NEW_LINE> <INDENT> pass
Base class for a external scorer. This can be used to integrate for example a language model.
62598f9e99cbb53fe6830cd2
class ExportDeviceEnvironment(Action): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(ExportDeviceEnvironment, self).__init__() <NEW_LINE> self.name = "export-device-env" <NEW_LINE> self.summary = "Exports environment variables action" <NEW_LINE> self.description = "Exports environment variables to the device" <NEW_LINE> self.env = [] <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> shell_file = self.get_common_data('environment', 'shell_file') <NEW_LINE> environment = self.get_common_data('environment', 'env_dict') <NEW_LINE> if not environment: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for key in environment: <NEW_LINE> <INDENT> self.env.append("echo export %s=\\'%s\\' >> %s" % ( key, environment[key], shell_file)) <NEW_LINE> <DEDENT> <DEDENT> def run(self, connection, args=None): <NEW_LINE> <INDENT> if not connection: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> connection = super(ExportDeviceEnvironment, self).run(connection, args) <NEW_LINE> shell_file = self.get_common_data('environment', 'shell_file') <NEW_LINE> for line in self.env: <NEW_LINE> <INDENT> connection.sendline(line, delay=self.character_delay) <NEW_LINE> <DEDENT> if shell_file: <NEW_LINE> <INDENT> connection.sendline('. %s' % shell_file, delay=self.character_delay) <NEW_LINE> <DEDENT> return connection
Exports environment variables found in common data on to the device.
62598f9e0a50d4780f7051da
class Tank(object): <NEW_LINE> <INDENT> def __init__(self, num_frogs, zpool_init, growth_params): <NEW_LINE> <INDENT> self.num_frogs = num_frogs <NEW_LINE> self.frogs = [Frog(0, growth_params) for i in range(num_frogs)] <NEW_LINE> self.zpool = zpool_init <NEW_LINE> self.growth_params = growth_params <NEW_LINE> <DEDENT> def update_zpool(self, frog_loads): <NEW_LINE> <INDENT> mu = self.zpool*np.exp(-self.growth_params['zdeath']) + frog_loads + 2000 <NEW_LINE> zpool_next = np.random.normal(loc=np.log(mu) - 0.5, scale=self.growth_params['zsd'], size=1)[0] <NEW_LINE> return(zpool_next) <NEW_LINE> <DEDENT> def update_tank(self): <NEW_LINE> <INDENT> prev_zpool = self.zpool <NEW_LINE> frog_loads = np.sum([frog.load for frog in self.frogs]) <NEW_LINE> self.zpool = np.exp(self.update_zpool(frog_loads)) <NEW_LINE> num_inf = np.sum([frog.is_infected() for frog in self.frogs]) <NEW_LINE> trajs = [frog.update_bd_load(num_inf, np.log(prev_zpool + 1)) for frog in self.frogs] <NEW_LINE> return((self.zpool, trajs))
A tank holds some number of frogs
62598f9e4e4d562566372224
class _Adder(metaclass=abc.ABCMeta): <NEW_LINE> <INDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self.__class__.__name__ <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def can_add(self, op1, op2): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def _add(self, op1, op2, operator_name, hints): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def add(self, op1, op2, operator_name, hints=None): <NEW_LINE> <INDENT> updated_hints = _infer_hints_allowing_override(op1, op2, hints) <NEW_LINE> if operator_name is None: <NEW_LINE> <INDENT> operator_name = "Add/" + op1.name + "__" + op2.name + "/" <NEW_LINE> <DEDENT> scope_name = self.name <NEW_LINE> if scope_name.startswith("_"): <NEW_LINE> <INDENT> scope_name = scope_name[1:] <NEW_LINE> <DEDENT> with ops.name_scope(scope_name): <NEW_LINE> <INDENT> return self._add(op1, op2, operator_name, updated_hints)
Abstract base class to add two operators. Each `Adder` acts independently, adding everything it can, paying no attention as to whether another `Adder` could have done the addition more efficiently.
62598f9efff4ab517ebcd5ee
class ApplicationBundlePackager(object): <NEW_LINE> <INDENT> def __init__(self, package): <NEW_LINE> <INDENT> self.package = package <NEW_LINE> <DEDENT> def create_bundle(self, tmp=None): <NEW_LINE> <INDENT> tmp = tmp or tempfile.mkdtemp() <NEW_LINE> contents = os.path.join(tmp, 'Contents') <NEW_LINE> macos = os.path.join(contents, 'MacOS') <NEW_LINE> resources = os.path.join(contents, 'Resources') <NEW_LINE> for p in [contents, macos, resources]: <NEW_LINE> <INDENT> if not os.path.exists(p): <NEW_LINE> <INDENT> os.makedirs(p) <NEW_LINE> <DEDENT> <DEDENT> plist_tpl = None <NEW_LINE> if os.path.exists(self.package.resources_info_plist): <NEW_LINE> <INDENT> plist_tpl = open(self.package.resources_info_plist).read() <NEW_LINE> <DEDENT> framework_plist = ApplicationPlist(self.package.app_name, self.package.org, self.package.version, self.package.shortdesc, os.path.basename(self.package.resources_icon_icns), plist_tpl) <NEW_LINE> framework_plist.save(os.path.join(contents, 'Info.plist')) <NEW_LINE> shutil.copy(self.package.resources_icon_icns, resources) <NEW_LINE> for name, path, use_wrapper, wrapper in self.package.get_commands(): <NEW_LINE> <INDENT> filename = os.path.join(macos, name) <NEW_LINE> if use_wrapper: <NEW_LINE> <INDENT> wrapper = self.package.get_wrapper(path, wrapper) <NEW_LINE> if not wrapper: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> with open(filename, 'w') as f: <NEW_LINE> <INDENT> f.write(wrapper) <NEW_LINE> <DEDENT> shell.call('chmod +x %s' % filename) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> shutil.copy(os.path.join(contents, 'Home', path), filename) <NEW_LINE> <DEDENT> <DEDENT> return tmp
Creates a package with the basic structure of an Application bundle.
62598f9e91f36d47f2230da0
class TestDiaryCreateView(LoggedInTestCase): <NEW_LINE> <INDENT> def test_create_diary_success(self): <NEW_LINE> <INDENT> params = {'title':'テストタイトル', 'content':'本文', 'photo1':'', 'photo2': '', 'photo3': '', } <NEW_LINE> response = self.client.post(reverse_lazy('diary:diary_create'), params) <NEW_LINE> self.assertRedirects(response, reverse_lazy('diary:diary_list')) <NEW_LINE> self.assertEqual(Diary.objects.filter(title='テストタイトル').count(), 1) <NEW_LINE> <DEDENT> def test_create_diary_failure(self): <NEW_LINE> <INDENT> response = self.client.post(reverse_lazy('diary:diary_create')) <NEW_LINE> self.assertFormError(response, 'form', 'title', 'このフィールドは必須です。')
DiaryCreateView用のテストクラス
62598f9ed7e4931a7ef3be99
class PolyScaler(DarkScaler): <NEW_LINE> <INDENT> def __init__(self, data_in, data_out, rank=2): <NEW_LINE> <INDENT> super(PolyScaler, self).__init__(data_in, data_out) <NEW_LINE> self.rank = rank <NEW_LINE> self.name = 'Poly'+str(self.rank) <NEW_LINE> <DEDENT> @property <NEW_LINE> def rank(self): <NEW_LINE> <INDENT> return self._rank <NEW_LINE> <DEDENT> @rank.setter <NEW_LINE> def rank(self, value): <NEW_LINE> <INDENT> self._rank = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def poly(self): <NEW_LINE> <INDENT> return np.poly1d(self.p) <NEW_LINE> <DEDENT> def model(self, x=None, p=None): <NEW_LINE> <INDENT> if x is None: <NEW_LINE> <INDENT> x = self.data_in <NEW_LINE> <DEDENT> if p is None: <NEW_LINE> <INDENT> p = self.p <NEW_LINE> <DEDENT> poly = np.poly1d(p) <NEW_LINE> return poly(x) <NEW_LINE> <DEDENT> def do_fit(self): <NEW_LINE> <INDENT> self.p = np.polyfit(self.data_in.ravel(), self.data_out.ravel(), self.rank) <NEW_LINE> <DEDENT> @property <NEW_LINE> def perr(self): <NEW_LINE> <INDENT> print("Not defined yet for PolyFitter.") <NEW_LINE> return <NEW_LINE> <DEDENT> @property <NEW_LINE> def p_dict(self): <NEW_LINE> <INDENT> d = dict() <NEW_LINE> for i, item in enumerate(self.p[::-1]): <NEW_LINE> <INDENT> d['poly{}_{}'.format(self.rank, i)] = item <NEW_LINE> <DEDENT> return d
Manage polynomial fits. Default rank is 2.
62598f9e66656f66f7d5a1f1
class Rectangle(Base): <NEW_LINE> <INDENT> def __init__(self, width, height, x=0, y=0, id=None): <NEW_LINE> <INDENT> super().__init__(id) <NEW_LINE> self.width = width <NEW_LINE> self.height = height <NEW_LINE> self.x = x <NEW_LINE> self.y = y <NEW_LINE> <DEDENT> @property <NEW_LINE> def width(self): <NEW_LINE> <INDENT> return self.__width <NEW_LINE> <DEDENT> @width.setter <NEW_LINE> def width(self, value): <NEW_LINE> <INDENT> if type(value) is not int: <NEW_LINE> <INDENT> raise TypeError("width must be an integer") <NEW_LINE> <DEDENT> elif value <= 0: <NEW_LINE> <INDENT> raise ValueError("width must be > 0") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.__width = value <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def height(self): <NEW_LINE> <INDENT> return self.__height <NEW_LINE> <DEDENT> @height.setter <NEW_LINE> def height(self, value): <NEW_LINE> <INDENT> if type(value) is not int: <NEW_LINE> <INDENT> raise TypeError("height must be an integer") <NEW_LINE> <DEDENT> elif value <= 0: <NEW_LINE> <INDENT> raise ValueError("height must be > 0") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.__height = value <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def x(self): <NEW_LINE> <INDENT> return self.__x <NEW_LINE> <DEDENT> @x.setter <NEW_LINE> def x(self, value): <NEW_LINE> <INDENT> if type(value) is not int: <NEW_LINE> <INDENT> raise TypeError("x must be an integer") <NEW_LINE> <DEDENT> elif value < 0: <NEW_LINE> <INDENT> raise ValueError("x must be >= 0") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.__x = value <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def y(self): <NEW_LINE> <INDENT> return self.__y <NEW_LINE> <DEDENT> @y.setter <NEW_LINE> def y(self, value): <NEW_LINE> <INDENT> if type(value) is not int: <NEW_LINE> <INDENT> raise TypeError("y must be an integer") <NEW_LINE> <DEDENT> elif value < 0: <NEW_LINE> <INDENT> raise ValueError("y must be >= 0") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.__y = value <NEW_LINE> <DEDENT> <DEDENT> def area(self): <NEW_LINE> <INDENT> return self.height * self.width <NEW_LINE> <DEDENT> def display(self): <NEW_LINE> <INDENT> if self.width == 0: <NEW_LINE> <INDENT> print("") <NEW_LINE> <DEDENT> for i in range(self.y): <NEW_LINE> <INDENT> print("") <NEW_LINE> <DEDENT> for i in range(self.height): <NEW_LINE> <INDENT> print(" " * self.x, end="") <NEW_LINE> for j in range(self.width): <NEW_LINE> <INDENT> print("{}".format("#"), end="") <NEW_LINE> <DEDENT> print("") <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return("[Rectangle] ({}) {}/{} - {}/{}" .format(self.id, self.x, self.y, self.width, self.height)) <NEW_LINE> <DEDENT> def update(self, *args, **kwargs): <NEW_LINE> <INDENT> item_list = ["id", "width", "height", "x", "y"] <NEW_LINE> if args: <NEW_LINE> <INDENT> count = 0 <NEW_LINE> for i in args: <NEW_LINE> <INDENT> setattr(self, item_list[count], i) <NEW_LINE> count += 1 <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for key, value in kwargs.items(): <NEW_LINE> <INDENT> setattr(self, key, value) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def to_dictionary(self): <NEW_LINE> <INDENT> return({"id": self.id, "width": self.width, "height": self.height, "x": self.x, "y": self.y})
class rectangle that inherites from base
62598f9e56b00c62f0fb26b0
class FilterCondition(ComplexObject): <NEW_LINE> <INDENT> ALL_ATTRIBS = {'field', 'condition', 'value'} <NEW_LINE> REQUIRED_ATTRIBS = {'field', 'value', 'condition'} <NEW_LINE> OPTIONAL_ATTRIBS = set() <NEW_LINE> TYPES = {'field': str, 'value': List(str), 'condition': enums.Condition}
FCO REST API FilterCondition complex object. Name. Attributes (type name (required): description: str field (T): The field the filter condition must match List(str) value (T): The value or values the filter condition must match enums.Condition condition (T): The filter condition (defaults to IS_EQUAL_TO)
62598f9e435de62698e9bbf4
class LeftShift(_ShiftOperator): <NEW_LINE> <INDENT> mapper_method = intern("map_left_shift")
.. attribute:: shiftee .. attribute:: shift
62598f9e24f1403a926857b2
class NotebookAlreadyExistsError(CloudCacheError): <NEW_LINE> <INDENT> pass
Raised when attempting to create a Notebook for a specific user, and a Notebook with that name already exists for that user.
62598f9ea79ad16197769e65
class StorageHeader: <NEW_LINE> <INDENT> DATA_LENGTH = 16 <NEW_LINE> DLT_PATTERN = b"\x44\x4C\x54\x01" <NEW_LINE> STRUCT_FORMAT = "<Ii4s" <NEW_LINE> def __init__(self, seconds: int, microseconds: int, ecu_id: str) -> None: <NEW_LINE> <INDENT> self.seconds = seconds <NEW_LINE> self.microseconds = microseconds <NEW_LINE> self.ecu_id = ecu_id <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def create_from_bytes(cls, data: bytes) -> "StorageHeader": <NEW_LINE> <INDENT> data_length = len(data) <NEW_LINE> if data_length < cls.DATA_LENGTH: <NEW_LINE> <INDENT> raise ValueError( f"Unexpected length of the data: {data_length} / " f"Storage Header must be {cls.DATA_LENGTH} or more" ) <NEW_LINE> <DEDENT> dlt_pattern = data[:4] <NEW_LINE> if dlt_pattern != cls.DLT_PATTERN: <NEW_LINE> <INDENT> raise ValueError( f"DLT-Pattern is not found in the data: {dlt_pattern} / " f"Beginning of Storage Header must be {cls.DLT_PATTERN}" ) <NEW_LINE> <DEDENT> entries = struct.unpack_from(cls.STRUCT_FORMAT, data, 4) <NEW_LINE> seconds = entries[0] <NEW_LINE> microseconds = entries[1] <NEW_LINE> ecu_id = _ascii_decode(entries[2]) <NEW_LINE> return cls(seconds, microseconds, ecu_id) <NEW_LINE> <DEDENT> def to_bytes(self) -> bytes: <NEW_LINE> <INDENT> return self.DLT_PATTERN + struct.pack( self.STRUCT_FORMAT, self.seconds, self.microseconds, _ascii_encode(self.ecu_id), ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def bytes_length(self) -> int: <NEW_LINE> <INDENT> return self.DATA_LENGTH
The Storage Header of a DLT Message.
62598f9e57b8e32f5250801c
class UserNameDialog(QDialog): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.ok_pressed = False <NEW_LINE> self.setWindowTitle('Привет!') <NEW_LINE> self.setFixedSize(300, 120) <NEW_LINE> self.label = QLabel('Введите имя пользователя:', self) <NEW_LINE> self.label.move(10, 10) <NEW_LINE> self.label.setFixedSize(150, 10) <NEW_LINE> self.client_name = QLineEdit(self) <NEW_LINE> self.client_name.setFixedSize(154, 20) <NEW_LINE> self.client_name.move(10, 30) <NEW_LINE> self.btn_ok = QPushButton('Начать', self) <NEW_LINE> self.btn_ok.move(10, 60) <NEW_LINE> self.btn_ok.clicked.connect(self.click) <NEW_LINE> self.btn_cancel = QPushButton('Выход', self) <NEW_LINE> self.btn_cancel.move(90, 60) <NEW_LINE> self.btn_cancel.clicked.connect(qApp.exit) <NEW_LINE> self.label_passwd = QLabel('Введите пароль:', self) <NEW_LINE> self.label_passwd.move(10, 55) <NEW_LINE> self.label_passwd.setFixedSize(150, 15) <NEW_LINE> self.client_passwd = QLineEdit(self) <NEW_LINE> self.client_passwd.setFixedSize(154, 20) <NEW_LINE> self.client_passwd.move(10, 75) <NEW_LINE> self.client_passwd.setEchoMode(QLineEdit.Password) <NEW_LINE> self.show() <NEW_LINE> <DEDENT> def click(self): <NEW_LINE> <INDENT> if self.client_name.text() and self.client_passwd.text(): <NEW_LINE> <INDENT> self.ok_pressed = True <NEW_LINE> qApp.exit()
Класс - интерфейс входа пользователя в систему
62598f9e3c8af77a43b67e3f
class DescribeEdgeUnitCloudRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.EdgeUnitId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.EdgeUnitId = params.get("EdgeUnitId") <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))
DescribeEdgeUnitCloud请求参数结构体
62598f9e60cbc95b0636414d
class CrawlTimeoutError(CrawlError): <NEW_LINE> <INDENT> pass
Indicates some error during crawling.
62598f9e32920d7e50bc5e56
class FunctionIterator(Iterator): <NEW_LINE> <INDENT> def __iter__(self): <NEW_LINE> <INDENT> for x in CodebaseIterator(verbose=self.verbose): <NEW_LINE> <INDENT> if isinstance(x, types.FunctionType): <NEW_LINE> <INDENT> yield x <NEW_LINE> <DEDENT> <DEDENT> raise StopIteration
Iterates over music21's packagesystem, yielding all functions discovered: :: >>> from music21 import documentation >>> iterator = documentation.FunctionIterator(verbose=False) >>> functions = [x for x in iterator] >>> for function in sorted(functions, ... key=lambda x: (x.__module__, x.__name__))[:10]: ... function.__module__, function.__name__ ... ('music21.abcFormat.__init__', 'mergeLeadingMetaData') ('music21.abcFormat.translate', 'abcToStreamOpus') ('music21.abcFormat.translate', 'abcToStreamPart') ('music21.abcFormat.translate', 'abcToStreamScore') ('music21.abcFormat.translate', 'parseTokens') ('music21.abcFormat.translate', 'reBar') ('music21.analysis.discrete', 'analyzeStream') ('music21.analysis.metrical', 'labelBeatDepth') ('music21.analysis.metrical', 'thomassenMelodicAccent') ('music21.analysis.neoRiemannian', 'L')
62598f9eeab8aa0e5d30bb86
class TestOrganizationApi(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.api = swagger_client.api.organization_api.OrganizationApi() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_create_org_repo(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_org_add_team_member(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_org_add_team_repository(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_org_conceal_member(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_org_create_hook(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_org_create_team(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_org_delete_hook(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_org_delete_member(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_org_delete_team(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_org_edit(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_org_edit_hook(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_org_edit_team(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_org_get(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_org_get_hook(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_org_get_team(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_org_is_member(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_org_is_public_member(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_org_list_current_user_orgs(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_org_list_hooks(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_org_list_members(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_org_list_public_members(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_org_list_repos(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_org_list_team_members(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_org_list_team_repos(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_org_list_teams(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_org_list_user_orgs(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_org_publicize_member(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_org_remove_team_member(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_org_remove_team_repository(self): <NEW_LINE> <INDENT> pass
OrganizationApi unit test stubs
62598f9e30bbd72246469877
class ShufflingBatchIteratorMixin(object): <NEW_LINE> <INDENT> def __iter__(self): <NEW_LINE> <INDENT> self.X, self.y = shuffle(self.X, self.y) <NEW_LINE> for res in super(ShufflingBatchIteratorMixin, self).__iter__(): <NEW_LINE> <INDENT> yield res
Mixin for shuffling data after each epoch
62598f9e0c0af96317c56182
class Jongsung: <NEW_LINE> <INDENT> _START_HANGLE = START_HANGLE <NEW_LINE> _J_IDX = J_INDEX <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> raise JongsungInstantiationException <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def is_hangle(string: str) -> bool: <NEW_LINE> <INDENT> last_char = string[-1] <NEW_LINE> if re.match('.*[ㄱ-ㅎㅏ-ㅣ가-힣]+.*', last_char) is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def has_jongsung(cls, string: str) -> bool: <NEW_LINE> <INDENT> if not cls.is_hangle(string): <NEW_LINE> <INDENT> raise NotHangleException <NEW_LINE> <DEDENT> last_char = string[-1] <NEW_LINE> if (ord(last_char) - cls._START_HANGLE) % cls._J_IDX > 0: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False
글자가 한글인지 체크 및 종성이 있는지 체크하는 클래스
62598f9ed58c6744b42dc1d3
class urlbar(SortFind): <NEW_LINE> <INDENT> def __init__(self,sortedurlph): <NEW_LINE> <INDENT> f=open(sortedurlph) <NEW_LINE> c=f.readlines() <NEW_LINE> f.close() <NEW_LINE> self.urlbar=[] <NEW_LINE> for l in c: <NEW_LINE> <INDENT> self.urlbar.append(hash(l.split()[1])) <NEW_LINE> <DEDENT> SortFind.__init__(self,self.urlbar) <NEW_LINE> <DEDENT> def gvalue(self,url): <NEW_LINE> <INDENT> return hash(url)
url库查询
62598f9e009cb60464d01326
class DisjunctionMaxMatcher(UnionMatcher): <NEW_LINE> <INDENT> def __init__(self, a, b, tiebreak=0.0): <NEW_LINE> <INDENT> super(DisjunctionMaxMatcher, self).__init__(a, b) <NEW_LINE> self.tiebreak = tiebreak <NEW_LINE> <DEDENT> def copy(self): <NEW_LINE> <INDENT> return self.__class__(self.a.copy(), self.b.copy(), tiebreak=self.tiebreak) <NEW_LINE> <DEDENT> def replace(self, minquality=0): <NEW_LINE> <INDENT> a = self.a <NEW_LINE> b = self.b <NEW_LINE> a_active = a.is_active() <NEW_LINE> b_active = b.is_active() <NEW_LINE> if minquality and a_active and b_active: <NEW_LINE> <INDENT> a_max = a.max_quality() <NEW_LINE> b_max = b.max_quality() <NEW_LINE> if a_max < minquality and b_max < minquality: <NEW_LINE> <INDENT> return mcore.NullMatcher() <NEW_LINE> <DEDENT> elif b_max < minquality: <NEW_LINE> <INDENT> return a.replace(minquality) <NEW_LINE> <DEDENT> elif a_max < minquality: <NEW_LINE> <INDENT> return b.replace(minquality) <NEW_LINE> <DEDENT> <DEDENT> if not (a_active or b_active): <NEW_LINE> <INDENT> return mcore.NullMatcher() <NEW_LINE> <DEDENT> elif not a_active: <NEW_LINE> <INDENT> return b.replace(minquality) <NEW_LINE> <DEDENT> elif not b_active: <NEW_LINE> <INDENT> return a.replace(minquality) <NEW_LINE> <DEDENT> a = a.replace(minquality) <NEW_LINE> b = b.replace(minquality) <NEW_LINE> a_active = a.is_active() <NEW_LINE> b_active = b.is_active() <NEW_LINE> if not (a_active and b_active): <NEW_LINE> <INDENT> return mcore.NullMatcher() <NEW_LINE> <DEDENT> elif not a_active: <NEW_LINE> <INDENT> return b <NEW_LINE> <DEDENT> elif not b_active: <NEW_LINE> <INDENT> return a <NEW_LINE> <DEDENT> elif a is not self.a or b is not self.b: <NEW_LINE> <INDENT> return self.__class__(a, b) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> <DEDENT> def score(self): <NEW_LINE> <INDENT> if not self.a.is_active(): <NEW_LINE> <INDENT> return self.b.score() <NEW_LINE> <DEDENT> elif not self.b.is_active(): <NEW_LINE> <INDENT> return self.a.score() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return max(self.a.score(), self.b.score()) <NEW_LINE> <DEDENT> <DEDENT> def max_quality(self): <NEW_LINE> <INDENT> return max(self.a.max_quality(), self.b.max_quality()) <NEW_LINE> <DEDENT> def block_quality(self): <NEW_LINE> <INDENT> return max(self.a.block_quality(), self.b.block_quality()) <NEW_LINE> <DEDENT> def skip_to_quality(self, minquality): <NEW_LINE> <INDENT> a = self.a <NEW_LINE> b = self.b <NEW_LINE> if not a.is_active(): <NEW_LINE> <INDENT> sk = b.skip_to_quality(minquality) <NEW_LINE> return sk <NEW_LINE> <DEDENT> elif not b.is_active(): <NEW_LINE> <INDENT> return a.skip_to_quality(minquality) <NEW_LINE> <DEDENT> skipped = 0 <NEW_LINE> aq = a.block_quality() <NEW_LINE> bq = b.block_quality() <NEW_LINE> while a.is_active() and b.is_active() and max(aq, bq) <= minquality: <NEW_LINE> <INDENT> if aq <= minquality: <NEW_LINE> <INDENT> skipped += a.skip_to_quality(minquality) <NEW_LINE> aq = a.block_quality() <NEW_LINE> <DEDENT> if bq <= minquality: <NEW_LINE> <INDENT> skipped += b.skip_to_quality(minquality) <NEW_LINE> bq = b.block_quality() <NEW_LINE> <DEDENT> <DEDENT> return skipped
Matches the union (OR) of two sub-matchers. Where both sub-matchers match the same posting, returns the weight/score of the higher-scoring posting.
62598f9e3539df3088ecc0b7
class ValidationError(object): <NEW_LINE> <INDENT> openapi_types = { 'loc': 'list[str]', 'msg': 'str', 'type': 'str' } <NEW_LINE> attribute_map = { 'loc': 'loc', 'msg': 'msg', 'type': 'type' } <NEW_LINE> def __init__(self, loc=None, msg=None, type=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._loc = None <NEW_LINE> self._msg = None <NEW_LINE> self._type = None <NEW_LINE> self.discriminator = None <NEW_LINE> self.loc = loc <NEW_LINE> self.msg = msg <NEW_LINE> self.type = type <NEW_LINE> <DEDENT> @property <NEW_LINE> def loc(self): <NEW_LINE> <INDENT> return self._loc <NEW_LINE> <DEDENT> @loc.setter <NEW_LINE> def loc(self, loc): <NEW_LINE> <INDENT> if self.local_vars_configuration.client_side_validation and loc is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `loc`, must not be `None`") <NEW_LINE> <DEDENT> self._loc = loc <NEW_LINE> <DEDENT> @property <NEW_LINE> def msg(self): <NEW_LINE> <INDENT> return self._msg <NEW_LINE> <DEDENT> @msg.setter <NEW_LINE> def msg(self, msg): <NEW_LINE> <INDENT> if self.local_vars_configuration.client_side_validation and msg is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `msg`, must not be `None`") <NEW_LINE> <DEDENT> self._msg = msg <NEW_LINE> <DEDENT> @property <NEW_LINE> def type(self): <NEW_LINE> <INDENT> return self._type <NEW_LINE> <DEDENT> @type.setter <NEW_LINE> def type(self, type): <NEW_LINE> <INDENT> if self.local_vars_configuration.client_side_validation and type is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `type`, must not be `None`") <NEW_LINE> <DEDENT> self._type = type <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, ValidationError): <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, ValidationError): <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.
62598f9ed53ae8145f918290
class DeletePost(BlogHandler): <NEW_LINE> <INDENT> def get(self, post_id): <NEW_LINE> <INDENT> if not self.user: <NEW_LINE> <INDENT> return self.redirect('/login') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> key = db.Key.from_path('Post', int(post_id), parent=blog_key()) <NEW_LINE> post = db.get(key) <NEW_LINE> author = post.author <NEW_LINE> loggedUser = self.user.name <NEW_LINE> if author == loggedUser: <NEW_LINE> <INDENT> key = db.Key.from_path('Post', int(post_id), parent=blog_key()) <NEW_LINE> post = db.get(key) <NEW_LINE> post.delete() <NEW_LINE> self.render("delete.html") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.redirect("/")
user can delete a post.
62598f9ea8ecb0332587100f
class PushParam(tuple): <NEW_LINE> <INDENT> def __new__(cls, src): <NEW_LINE> <INDENT> return tuple.__new__(cls, (src,)) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "%s(src=%r)" % (type(self).__name__, self.src) <NEW_LINE> <DEDENT> src = property(lambda self: self[0])
An operation that pushes the source onto the parameter stack for a future function call
62598f9ea17c0f6771d5c03c
class Filer(models.Model): <NEW_LINE> <INDENT> filer_id = models.CharField(max_length=20, null=False) <NEW_LINE> name = models.TextField()
Not from Voter Information Project. A filer in the state of California.
62598f9e91f36d47f2230da1
class PyICONINFO(object): <NEW_LINE> <INDENT> def __new__(cls): <NEW_LINE> <INDENT> raise Exception('This class just for typing, can not be instanced!')
Tuple describing an icon or cursor
62598f9e851cf427c66b80ca
class HashtagSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = Hashtag <NEW_LINE> fields = ('name',)
Serializing all the Hashtags
62598f9ee64d504609df92b9
class ToggleBreakpoint (gdb.Command): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(ToggleBreakpoint, self).__init__("toggle-break", gdb.COMMAND_USER) <NEW_LINE> <DEDENT> def invoke(self, args, from_tty): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> sal = gdb.selected_frame().find_sal() <NEW_LINE> fname = sal.symtab.fullname() <NEW_LINE> lnum = sal.line <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> gdb.write(str(e) + '\n') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> gdb.execute(f'clear {fname}:{lnum}') <NEW_LINE> <DEDENT> except gdb.error: <NEW_LINE> <INDENT> gdb.execute(f'break {fname}:{lnum}')
Toggle breakpoint
62598f9e460517430c431f5c
class LogBodyWeightInputSet(InputSet): <NEW_LINE> <INDENT> def set_AccessTokenSecret(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'AccessTokenSecret', value) <NEW_LINE> <DEDENT> def set_AccessToken(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'AccessToken', value) <NEW_LINE> <DEDENT> def set_ConsumerKey(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'ConsumerKey', value) <NEW_LINE> <DEDENT> def set_ConsumerSecret(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'ConsumerSecret', value) <NEW_LINE> <DEDENT> def set_Date(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'Date', value) <NEW_LINE> <DEDENT> def set_ResponseFormat(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'ResponseFormat', value) <NEW_LINE> <DEDENT> def set_Time(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'Time', value) <NEW_LINE> <DEDENT> def set_UserID(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'UserID', value) <NEW_LINE> <DEDENT> def set_Weight(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'Weight', value)
An InputSet with methods appropriate for specifying the inputs to the LogBodyWeight Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
62598f9ee5267d203ee6b710
class DocumentReference(Base): <NEW_LINE> <INDENT> __tablename__ = 'document_reference' <NEW_LINE> __table_args__ = {'schema': 'motorways_building_lines'} <NEW_LINE> id = sa.Column(sa.String, primary_key=True, autoincrement=False) <NEW_LINE> document_id = sa.Column( sa.String, sa.ForeignKey(Document.id), nullable=False ) <NEW_LINE> reference_document_id = sa.Column( sa.String, sa.ForeignKey(Document.id), nullable=False ) <NEW_LINE> document = relationship( Document, backref='referenced_documents', foreign_keys=[document_id] ) <NEW_LINE> referenced_document = relationship( Document, foreign_keys=[reference_document_id] ) <NEW_LINE> article_numbers = sa.Column(sa.String, nullable=True) <NEW_LINE> liefereinheit = sa.Column(sa.Integer, nullable=True)
Meta bucket (join table) for the relationship between documents. Attributes: id (int): The identifier. This is used in the database only and must not be set manually. If you don't like it - don't care about. document_id (int): The foreign key to the document which references to another document. reference_document_id (int): The foreign key to the document which is referenced. document (pyramid_oereb.standard.models.motorways_building_lines.Document): The dedicated relation to the document (which references) instance from database. referenced_document (pyramid_oereb.standard.models.motorways_building_lines.Document): The dedicated relation to the document (which is referenced) instance from database. article_numbers (str): A colon of article numbers which clarify the reference. This is a string separated by '|'.
62598f9e7d43ff2487427303
class CircularLinkedlist(Linked): <NEW_LINE> <INDENT> def __init__(self, root=None): <NEW_LINE> <INDENT> super().__init__(root) <NEW_LINE> <DEDENT> def add(self, item): <NEW_LINE> <INDENT> if self.size == 0: <NEW_LINE> <INDENT> self.root = Node(item) <NEW_LINE> self.root.next_node = self.root <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> new_node = Node(item, self.root.next_node) <NEW_LINE> self.root.next_node = new_node <NEW_LINE> <DEDENT> self.size += 1 <NEW_LINE> <DEDENT> def find(self, item): <NEW_LINE> <INDENT> this_node = self.root <NEW_LINE> while True: <NEW_LINE> <INDENT> if this_node.data == item: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif this_node.next_node == self.root: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> this_node = this_node.next_node <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def remove(self, item): <NEW_LINE> <INDENT> this_node = self.root <NEW_LINE> prev_node = None <NEW_LINE> while True: <NEW_LINE> <INDENT> if this_node.data == item: <NEW_LINE> <INDENT> if prev_node is not None: <NEW_LINE> <INDENT> prev_node.next_node = this_node.next_node <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> while this_node.next_node != self.root: <NEW_LINE> <INDENT> this_node = this_node.next_node <NEW_LINE> <DEDENT> this_node.next_node = self.root.next_node <NEW_LINE> self.root = this_node.next_node <NEW_LINE> <DEDENT> self.size -= 1 <NEW_LINE> return True <NEW_LINE> <DEDENT> elif this_node.next_node == self.root: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> prev_node = this_node <NEW_LINE> this_node = this_node.next_node <NEW_LINE> <DEDENT> <DEDENT> def _print_condition(self, node): <NEW_LINE> <INDENT> return node.next_node != self.root
A variant of linked list, where the first element points to the last element and the last element points to the first element.
62598f9e097d151d1a2c0e2a
class Order2StringTest(unittest.TestCase): <NEW_LINE> <INDENT> def test_order2string(self): <NEW_LINE> <INDENT> self.assertEquals("1st", util.order2string(1)) <NEW_LINE> self.assertEquals("2nd", util.order2string(2)) <NEW_LINE> self.assertEquals("3rd", util.order2string(3)) <NEW_LINE> self.assertEquals("4th", util.order2string(4)) <NEW_LINE> self.assertEquals("11th", util.order2string(11)) <NEW_LINE> self.assertEquals("12th", util.order2string(12)) <NEW_LINE> self.assertEquals("21st", util.order2string(21)) <NEW_LINE> self.assertEquals("22nd", util.order2string(22)) <NEW_LINE> self.assertEquals("23rd", util.order2string(23))
Test class for order2string
62598f9e4f6381625f1993bd
@cbook.deprecated("3.0") <NEW_LINE> class TempCache(object): <NEW_LINE> <INDENT> invalidating_rcparams = ( 'font.serif', 'font.sans-serif', 'font.cursive', 'font.fantasy', 'font.monospace') <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self._lookup_cache = {} <NEW_LINE> self._last_rcParams = self.make_rcparams_key() <NEW_LINE> <DEDENT> def make_rcparams_key(self): <NEW_LINE> <INDENT> return [id(fontManager)] + [ rcParams[param] for param in self.invalidating_rcparams] <NEW_LINE> <DEDENT> def get(self, prop): <NEW_LINE> <INDENT> key = self.make_rcparams_key() <NEW_LINE> if key != self._last_rcParams: <NEW_LINE> <INDENT> self._lookup_cache = {} <NEW_LINE> self._last_rcParams = key <NEW_LINE> <DEDENT> return self._lookup_cache.get(prop) <NEW_LINE> <DEDENT> def set(self, prop, value): <NEW_LINE> <INDENT> key = self.make_rcparams_key() <NEW_LINE> if key != self._last_rcParams: <NEW_LINE> <INDENT> self._lookup_cache = {} <NEW_LINE> self._last_rcParams = key <NEW_LINE> <DEDENT> self._lookup_cache[prop] = value
A class to store temporary caches that are (a) not saved to disk and (b) invalidated whenever certain font-related rcParams---namely the family lookup lists---are changed or the font cache is reloaded. This avoids the expensive linear search through all fonts every time a font is looked up.
62598f9e8e71fb1e983bb8b9
class RequestsWebClient(AbstractWebClient): <NEW_LINE> <INDENT> __USER_AGENT = 'ultimate_sitemap_parser/{}'.format(__version__) <NEW_LINE> __HTTP_REQUEST_TIMEOUT = 60 <NEW_LINE> __slots__ = [ '__max_response_data_length', '__timeout', '__proxies', ] <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.__max_response_data_length = None <NEW_LINE> self.__timeout = self.__HTTP_REQUEST_TIMEOUT <NEW_LINE> self.__proxies = {} <NEW_LINE> <DEDENT> def set_timeout(self, timeout: int) -> None: <NEW_LINE> <INDENT> self.__timeout = timeout <NEW_LINE> <DEDENT> def set_proxies(self, proxies: Dict[str, str]) -> None: <NEW_LINE> <INDENT> self.__proxies = proxies <NEW_LINE> <DEDENT> def set_max_response_data_length(self, max_response_data_length: int) -> None: <NEW_LINE> <INDENT> self.__max_response_data_length = max_response_data_length <NEW_LINE> <DEDENT> def get(self, url: str) -> AbstractWebClientResponse: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> response = requests.get( url, timeout=self.__timeout, stream=True, headers={'User-Agent': self.__USER_AGENT}, proxies=self.__proxies ) <NEW_LINE> <DEDENT> except requests.exceptions.Timeout as ex: <NEW_LINE> <INDENT> return RequestsWebClientErrorResponse(message=str(ex), retryable=True) <NEW_LINE> <DEDENT> except requests.exceptions.RequestException as ex: <NEW_LINE> <INDENT> return RequestsWebClientErrorResponse(message=str(ex), retryable=False) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if 200 <= response.status_code < 300: <NEW_LINE> <INDENT> return RequestsWebClientSuccessResponse( requests_response=response, max_response_data_length=self.__max_response_data_length, ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> message = '{} {}'.format(response.status_code, response.reason) <NEW_LINE> if response.status_code in RETRYABLE_HTTP_STATUS_CODES: <NEW_LINE> <INDENT> return RequestsWebClientErrorResponse(message=message, retryable=True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return RequestsWebClientErrorResponse(message=message, retryable=False)
requests-based web client to be used by the sitemap fetcher.
62598f9ecb5e8a47e493c076
class Product: <NEW_LINE> <INDENT> pass
A Base Model Representation of Product Entity.
62598f9e442bda511e95c25e
@dataclass(frozen=True) <NEW_LINE> class Route: <NEW_LINE> <INDENT> filt: Optional[Filter] = None <NEW_LINE> def get_dests( self, data_set: Dataset ) -> Optional[Tuple[DataBucket[Any, Any], ...]]: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def get_filtered(self, data_set: Dataset) -> Optional[Dataset]: <NEW_LINE> <INDENT> if self.filt is None: <NEW_LINE> <INDENT> return data_set <NEW_LINE> <DEDENT> return self.filt(data_set)
Abstract base class for all Routes The main functionality of routes is to map datasets to destinations. Routes can have a filter associated with them, which take a dataset as input and return one as output. The dataset can be modified and None can be returned to reject the dataset.
62598f9f097d151d1a2c0e2b
class search: <NEW_LINE> <INDENT> def __init__(self, number): <NEW_LINE> <INDENT> URL = 'https://search5.truecaller.com/v2/search?' <NEW_LINE> raw_params = { 'q': number, 'countryCode': 'IN', 'type': '4', 'locAddr': '', 'placement': 'SEARCHRESULTS,HISTORY,DETAILS', 'clientId': '1', 'myNumber': 'lS5757de85c2804a87d452c139OpYeO6gR6qlj0QFJJQMpo1', 'registerId': '285661581', 'encoding': 'json', } <NEW_LINE> params = urllib.urlencode(raw_params) <NEW_LINE> url_params = URL + params <NEW_LINE> response = urllib.urlopen(url_params).read() <NEW_LINE> parsed = json.loads(response) <NEW_LINE> basic = parsed['data'][0] <NEW_LINE> phone_parsed = parsed['data'][0]['phones'][0] <NEW_LINE> address_parsed = parsed['data'][0]['addresses'][0] <NEW_LINE> self.id = basic['id'] <NEW_LINE> self.name = basic['name'] <NEW_LINE> self.score = basic['score'] <NEW_LINE> self.access = basic['access'] <NEW_LINE> self.enhanced = basic['enhanced'] <NEW_LINE> self.internet_address = basic['internetAddresses'] <NEW_LINE> self.badges = basic['badges'] <NEW_LINE> self.tags = basic['tags'] <NEW_LINE> self.sources = basic['sources'] <NEW_LINE> self.phone = phone(phone_parsed) <NEW_LINE> self.address = address(address_parsed) <NEW_LINE> self.provider = parsed['provider'] <NEW_LINE> self.trace = parsed['trace'] <NEW_LINE> self.sourcestats = parsed['stats']['sourceStats']
Return a new search instance given a phone number.
62598f9f32920d7e50bc5e59
class Equipable(Base): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> Base.__init__(self, possible_slots=list, wearer=object, in_slot=str) <NEW_LINE> <DEDENT> @property <NEW_LINE> def saveable_fields(self): <NEW_LINE> <INDENT> fields = self.fields.keys() <NEW_LINE> fields.remove("wearer") <NEW_LINE> return fields
Component that stores the data for an entity that can be equipped.
62598f9ff8510a7c17d7e079
class InteractiveGraphicsDevice(GraphicsDevice): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> plt.show(block=False) <NEW_LINE> plt.pause(.001) <NEW_LINE> <DEDENT> def draw_current_axes(self): <NEW_LINE> <INDENT> plt.pause(.001)
A private stack manages the set of active graphics devices.
62598f9ee1aae11d1e7ce726
class NoSuchJobStoreException(Exception): <NEW_LINE> <INDENT> def __init__(self, locator): <NEW_LINE> <INDENT> super().__init__("The job store '%s' does not exist, so there is nothing to restart." % locator)
Indicates that the specified job store does not exist.
62598f9f3539df3088ecc0b8
class CompositeSequenceAccess(CompositeAccess): <NEW_LINE> <INDENT> def __init__(self, segment, compositeQualifier=None, x12type=None): <NEW_LINE> <INDENT> self.segment = segment <NEW_LINE> if isinstance(compositeQualifier, (list, tuple)): <NEW_LINE> <INDENT> self.qualifier = compositeQualifier <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.qualifier = (compositeQualifier, ) <NEW_LINE> <DEDENT> self.x12type = x12type <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> typeName = "None" if self.x12type is None else self.x12type.__name__ <NEW_LINE> return "CompositeSequenceAccess( %r, %r, %r, %s )" % ( self.segment, self.position, self.qualifier, typeName) <NEW_LINE> <DEDENT> def __get__(self, instance, owner): <NEW_LINE> <INDENT> segList = instance.segList(self.segment) <NEW_LINE> compList = [] <NEW_LINE> for seg in segList: <NEW_LINE> <INDENT> compList.extend(seg.compositeList(*self.qualifier)) <NEW_LINE> <DEDENT> data = [] <NEW_LINE> for composite in compList: <NEW_LINE> <INDENT> raw = composite <NEW_LINE> if self.x12type is not None: <NEW_LINE> <INDENT> data.append(self.x12type.x12_to_python(raw)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> data.append(raw) <NEW_LINE> <DEDENT> <DEDENT> return data <NEW_LINE> <DEDENT> def __set__(self, instance, value): <NEW_LINE> <INDENT> raise NotImplementedError()
Map a user-friendly attribute name to a sequence of Composites that occur somewhere in the occurances of a given Segment type. This is used for the various "HI" Segments where a sequence of values is located in a qualified Composites. Each Composite Element has multiple values, the first of which is a qualifier for the Composite. The rest of which is the target values. This is a Descriptor which implements the attributes name using __get__ and __set__ methods.
62598f9fadb09d7d5dc0a38d
class SetKeyOperator(Operator): <NEW_LINE> <INDENT> name = 'set_key' <NEW_LINE> operator_name = 'set_key' <NEW_LINE> operator_constructors = [(str, str)] <NEW_LINE> def __init__(self, inputs, key, value): <NEW_LINE> <INDENT> outputs = copy.deepcopy(inputs) <NEW_LINE> for o in outputs: <NEW_LINE> <INDENT> o[key] = value <NEW_LINE> <DEDENT> Operator.__init__(self, inputs, outputs) <NEW_LINE> <DEDENT> def process(self, inputs): <NEW_LINE> <INDENT> return inputs
Sets a key on all output streams For instance, adding a: set_key("Metadata/Extra/Name", "Foo") To the operator pipeline will set the Metadata/Extra/Name tag to "Foo" on all input streams.
62598f9f21a7993f00c65d87
class UserProfile(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 = UserProfileManager() <NEW_LINE> USERNAME_FIELD = 'email' <NEW_LINE> REQUIRED_FIELDS = ['name'] <NEW_LINE> def get_full_name(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def get_short_name(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.email
database model for users in the system
62598f9f8e7ae83300ee8ea3
class FacadeQueries(AbsResource): <NEW_LINE> <INDENT> def post(self): <NEW_LINE> <INDENT> query_content = request.get_json(force=True) <NEW_LINE> query_id, workflow_id = self.service.query(query_content) <NEW_LINE> result_url = "%s/%s" % (self.generate_host_port_endpoint(endpoint = "/results/<query_id>"), query_id) <NEW_LINE> msg = message.CallbackMessage(request.url, "Finished query. Find the result at the included URL", result_url, workflow_id = workflow_id) <NEW_LINE> return msg.to_dict() , 201
Served by a facade service. It provides the entry point to the system for search clients
62598f9fd53ae8145f918292
class ForceObject(object): <NEW_LINE> <INDENT> def __init__(self, start, end): <NEW_LINE> <INDENT> self.start = start <NEW_LINE> self.end = end <NEW_LINE> self.id = None <NEW_LINE> self._components_map = None <NEW_LINE> self.gpu_idx_buf = None <NEW_LINE> self.gpu_force_buf = None <NEW_LINE> self.force_buf = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def initialized(self): <NEW_LINE> <INDENT> return self._components_map is not None <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return 'ForceObject(id=%s)' % self.id <NEW_LINE> <DEDENT> def force(self): <NEW_LINE> <INDENT> ret = [] <NEW_LINE> for i in range(self._components_map.shape[0]): <NEW_LINE> <INDENT> ret.append(np.sum(self._components_map[i,:] * self.force_buf)) <NEW_LINE> <DEDENT> return ret
Used to track momentum exchange between the fluid and a solid object. The exchanged momentum can be used to compute the value of the force acting on the solid object. See Ladd A. Effects of container walls on the velocity fluctuations of sedimenting spheres. Phys Rev Lett 2002; 88:048301 for more info about this procedure.
62598f9fe5267d203ee6b711
class ReadDeviceInputRegisters(ReadInputRegistersRequest): <NEW_LINE> <INDENT> def __init__(self, unit, address, count): <NEW_LINE> <INDENT> ReadInputRegistersRequest.__init__(self, address, count, unit=unit)
Read device input registers.
62598f9f10dbd63aa1c709ba
class Revert(SetRevertBase): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._revert_stack = deque() <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> self._revert_stack.append([]) <NEW_LINE> for key, value in self._parameters: <NEW_LINE> <INDENT> old_value = self._update_value(key, value) <NEW_LINE> self._debug_print('Set {key} to {value}, was {old_value}.', key=key, value=value, old_value=old_value) <NEW_LINE> if old_value is not None: <NEW_LINE> <INDENT> self._revert_stack[-1].append((key, old_value)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logging.warning((__name__+': Value of {0} was None. This ' + 'parameter will not be reverted.').format(key)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __exit__(self, exc_type, exc_value, traceback): <NEW_LINE> <INDENT> revert_list = self._revert_stack.pop() <NEW_LINE> for key, value in revert_list: <NEW_LINE> <INDENT> old_value = self._update_value(key, value) <NEW_LINE> self._debug_print('Reverted {key} to {value}, was {old_value}.', key=key, value=value, old_value=old_value)
A context manager that sets and reverts parameter values. The manager can handle repeated calls to `__enter__`, with or without intermediate calls to `__exit__` correctly.
62598f9fa17c0f6771d5c03e
class Book(models.Model): <NEW_LINE> <INDENT> zoterokey = models.CharField( verbose_name=ugettext_lazy("Zoterokey"), primary_key=True, max_length=100, blank=True, help_text=ugettext_lazy("Zoterokey des bibliographischen Eintrags aus der Zoterolibrary 'Peter Handke stage texts'")) <NEW_LINE> item_type = models.CharField( max_length=100, blank=True, null=True, verbose_name=ugettext_lazy("Objekttyp")) <NEW_LINE> author = models.CharField( max_length=250, blank=True, null=True, verbose_name=ugettext_lazy("Autor*innenname laut Zotero-Eintrag") ) <NEW_LINE> book_author = models.ManyToManyField( Person, blank=True, verbose_name=ugettext_lazy("Autor*innenname")) <NEW_LINE> title = models.CharField( max_length=500, blank=True, null=True, verbose_name=ugettext_lazy("Titel des Werks")) <NEW_LINE> siglum = models.CharField( verbose_name=ugettext_lazy("Sigle"), max_length=500, blank=True, null=True, help_text=ugettext_lazy("Sigle des publizierten Werks (laut Handkeonline)")) <NEW_LINE> publication_title = models.CharField(max_length=100, blank=True, null=True) <NEW_LINE> short_title = models.CharField(max_length=500, blank=True, null=True) <NEW_LINE> publication_year = models.IntegerField( blank=True, null=True, verbose_name=ugettext_lazy("Jahr der Veröffentlichung")) <NEW_LINE> pub_place = models.ManyToManyField( Place, blank=True, verbose_name=ugettext_lazy("Ort der Veröffentlichung")) <NEW_LINE> book_gnd = models.CharField( max_length=500, blank=True, null=True, verbose_name=ugettext_lazy("GND-ID des Buchs")) <NEW_LINE> item_type = models.CharField( max_length=500, blank=True, null=True, verbose_name=ugettext_lazy("Item type laut Zotero-Eintrag") ) <NEW_LINE> book_type = models.ManyToManyField(SkosConcept, blank=True) <NEW_LINE> @classmethod <NEW_LINE> def get_listview_url(self): <NEW_LINE> <INDENT> return reverse('browsing:browse_books') <NEW_LINE> <DEDENT> def get_absolute_url(self): <NEW_LINE> <INDENT> return reverse('browsing:book_detail', kwargs={'pk': self.zoterokey}) <NEW_LINE> <DEDENT> def get_zotero_url(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> base = "https://www.zotero.org/{}/".format(settings.Z_ID_TYPE) <NEW_LINE> url = "{}{}/peter_handke_stage_texts/items/itemKey/{}".format( base, settings.Z_ID, self.zoterokey ) <NEW_LINE> return url <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> return ugettext_lazy("Bitte Zotero-Einstellungen bereitstellen") <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "{}, {}".format(self.author, self.title) <NEW_LINE> <DEDENT> def get_classname(self): <NEW_LINE> <INDENT> class_name = "{}".format(self.__class__.__name__) <NEW_LINE> return class_name <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_alternative_classname(self): <NEW_LINE> <INDENT> return ugettext_lazy('Bücher')
Bibliographische Informationen zu einem publizierten Buch.
62598f9f3eb6a72ae038a445
class data_show: <NEW_LINE> <INDENT> def __init__(self, vals): <NEW_LINE> <INDENT> self.vals = vals.copy() <NEW_LINE> <DEDENT> def modify(self, vals): <NEW_LINE> <INDENT> raise NotImplementedError("this needs to be implemented to use the data_show class") <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> raise NotImplementedError("this needs to be implemented to use the data_show class")
The data_show class is a base class which describes how to visualize a particular data set. For example, motion capture data can be plotted as a stick figure, or images are shown using imshow. This class enables latent to data visualizations for the GP-LVM.
62598f9fbd1bec0571e14fc5
class SoQtPlaneViewer(SoQtFullViewer): <NEW_LINE> <INDENT> thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> def initClass(): <NEW_LINE> <INDENT> return _soqt.SoQtPlaneViewer_initClass() <NEW_LINE> <DEDENT> initClass = staticmethod(initClass) <NEW_LINE> def getClassTypeId(): <NEW_LINE> <INDENT> return _soqt.SoQtPlaneViewer_getClassTypeId() <NEW_LINE> <DEDENT> getClassTypeId = staticmethod(getClassTypeId) <NEW_LINE> def getTypeId(self): <NEW_LINE> <INDENT> return _soqt.SoQtPlaneViewer_getTypeId(self) <NEW_LINE> <DEDENT> def createInstance(): <NEW_LINE> <INDENT> return _soqt.SoQtPlaneViewer_createInstance() <NEW_LINE> <DEDENT> createInstance = staticmethod(createInstance) <NEW_LINE> def __init__(self, *args): <NEW_LINE> <INDENT> this = _soqt.new_SoQtPlaneViewer(*args) <NEW_LINE> try: self.this.append(this) <NEW_LINE> except: self.this = this <NEW_LINE> <DEDENT> __swig_destroy__ = _soqt.delete_SoQtPlaneViewer <NEW_LINE> __del__ = lambda self : None; <NEW_LINE> def setViewing(self, *args): <NEW_LINE> <INDENT> return _soqt.SoQtPlaneViewer_setViewing(self, *args) <NEW_LINE> <DEDENT> def setCamera(self, *args): <NEW_LINE> <INDENT> return _soqt.SoQtPlaneViewer_setCamera(self, *args) <NEW_LINE> <DEDENT> def setCursorEnabled(self, *args): <NEW_LINE> <INDENT> return _soqt.SoQtPlaneViewer_setCursorEnabled(self, *args)
Proxy of C++ SoQtPlaneViewer class
62598f9f2c8b7c6e89bd35d4
class ShuffledSequentialSubsetIterator(SequentialSubsetIterator): <NEW_LINE> <INDENT> stochastic = True <NEW_LINE> fancy = True <NEW_LINE> def __init__(self, dataset_size, batch_size, num_batches, rng=None): <NEW_LINE> <INDENT> super(ShuffledSequentialSubsetIterator, self).__init__( dataset_size, batch_size, num_batches, None ) <NEW_LINE> self._rng = make_np_rng(rng, which_method=["random_integers", "shuffle"]) <NEW_LINE> self._shuffled = numpy.arange(self._dataset_size) <NEW_LINE> self._rng.shuffle(self._shuffled) <NEW_LINE> <DEDENT> def next(self): <NEW_LINE> <INDENT> if self._batch >= self.num_batches or self._idx >= self._dataset_size: <NEW_LINE> <INDENT> raise StopIteration() <NEW_LINE> <DEDENT> elif (self._idx + self._batch_size) > self._dataset_size: <NEW_LINE> <INDENT> rval = self._shuffled[self._idx: self._dataset_size] <NEW_LINE> self._idx = self._dataset_size <NEW_LINE> return rval <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> rval = self._shuffled[self._idx: self._idx + self._batch_size] <NEW_LINE> self._idx += self._batch_size <NEW_LINE> self._batch += 1 <NEW_LINE> return rval
.. todo:: WRITEME
62598f9ff7d966606f747dec
class LassimContext: <NEW_LINE> <INDENT> def __init__(self, core: CoreSystem, primary_opt: List['OptimizationArgs'], ode_fun: Callable[..., Vector], pert_fun: Callable[..., float], solution_class: Type[BaseSolution], secondary_opt: List['OptimizationArgs'] = None): <NEW_LINE> <INDENT> self.__core_system = core <NEW_LINE> if len(primary_opt) == 0: <NEW_LINE> <INDENT> raise ValueError("Primary optimization list can't be empty") <NEW_LINE> <DEDENT> self.__primary_opt = primary_opt <NEW_LINE> self.__ode_function = ode_fun <NEW_LINE> self.__pert_function = pert_fun <NEW_LINE> self.__solution_class = solution_class <NEW_LINE> self.__secondary_opt = list() <NEW_LINE> if secondary_opt is not None: <NEW_LINE> <INDENT> self.__secondary_opt = secondary_opt <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def core(self) -> CoreSystem: <NEW_LINE> <INDENT> return self.__core_system <NEW_LINE> <DEDENT> @property <NEW_LINE> def primary_opts(self) -> List['OptimizationArgs']: <NEW_LINE> <INDENT> return [val for val in self.__primary_opt] <NEW_LINE> <DEDENT> @property <NEW_LINE> def primary_first(self) -> 'OptimizationArgs': <NEW_LINE> <INDENT> return self.primary_opts[0] <NEW_LINE> <DEDENT> @property <NEW_LINE> def secondary_opts(self) -> List['OptimizationArgs']: <NEW_LINE> <INDENT> return [val for val in self.__secondary_opt] <NEW_LINE> <DEDENT> @property <NEW_LINE> def secondary_first(self) -> Optional['OptimizationArgs']: <NEW_LINE> <INDENT> if len(self.secondary_opts) > 0: <NEW_LINE> <INDENT> return self.secondary_opts[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def ode(self) -> Callable[..., Vector]: <NEW_LINE> <INDENT> return self.__ode_function <NEW_LINE> <DEDENT> @property <NEW_LINE> def perturbation(self) -> Callable[..., float]: <NEW_LINE> <INDENT> return self.__pert_function <NEW_LINE> <DEDENT> @property <NEW_LINE> def SolutionClass(self) -> Type[BaseSolution]: <NEW_LINE> <INDENT> return self.__solution_class <NEW_LINE> <DEDENT> def __str__(self) -> str: <NEW_LINE> <INDENT> return "LassimContext" <NEW_LINE> <DEDENT> __repr__ = __str__
Represents the context of the current optimization. Should allow dependency injection of common parameters, like the class that represents the solutions, the ode function to use, ..
62598f9f67a9b606de545dce
class Grade: <NEW_LINE> <INDENT> def __init__(self, disciplineID, studentID, gradeValue): <NEW_LINE> <INDENT> self.__disciplineID = disciplineID <NEW_LINE> self.__studentID = studentID <NEW_LINE> self.__gradeValue = gradeValue <NEW_LINE> <DEDENT> def getDisciplineID(self): <NEW_LINE> <INDENT> return self.__disciplineID <NEW_LINE> <DEDENT> def getStudentID(self): <NEW_LINE> <INDENT> return self.__studentID <NEW_LINE> <DEDENT> def getGradeValue(self): <NEW_LINE> <INDENT> return self.__gradeValue <NEW_LINE> <DEDENT> def setDisciplineID(self, disciplineID): <NEW_LINE> <INDENT> self.__disciplineID = disciplineID <NEW_LINE> <DEDENT> def setStudentID(self, studentID): <NEW_LINE> <INDENT> self.__studentID = studentID <NEW_LINE> <DEDENT> def setGradeValue(self, gradeValue): <NEW_LINE> <INDENT> self.__gradeValue = gradeValue <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "Discipline ID: " + str(self.__disciplineID) + " Student ID: " + str(self.__studentID) + " Grade value: " + str(self.__gradeValue)
We declare a class of grades where we have the discipline ID, student ID and the value of the grade
62598f9fdd821e528d6d8d38
class ModelContainerTestCase(BaseTest): <NEW_LINE> <INDENT> def test_valid_model(self): <NEW_LINE> <INDENT> model_cls = ModelContainer(APP_LABEL, TestModel2._meta.db_table).model_cls <NEW_LINE> self.assertTrue(model_cls.__class__.__name__ is models.Model.__class__.__name__) <NEW_LINE> <DEDENT> def test_access_denied_model(self): <NEW_LINE> <INDENT> self.assertRaises(ModelAccessDeniedError, lambda: ModelContainer(APP_LABEL, TestModel._meta.db_table).model_cls) <NEW_LINE> <DEDENT> def test_invalid_model(self): <NEW_LINE> <INDENT> self.assertRaises(ModelNotFoundError, lambda: ModelContainer('web', 'model').model_cls)
ModelContainer class tests
62598f9f99cbb53fe6830cd7
class UserUpdateForm(forms.ModelForm): <NEW_LINE> <INDENT> email = forms.EmailField() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = User <NEW_LINE> fields = ['username', 'email']
will update the user model
62598f9f7047854f4633f1e7
class ParentAccessSchema(Schema): <NEW_LINE> <INDENT> grants = fields.List(fields.Nested(Grant)) <NEW_LINE> owned_by = fields.List(fields.Nested(Agent)) <NEW_LINE> links = fields.List(fields.Nested(SecretLink))
Access schema.
62598f9f460517430c431f5d
class FourSiteWaterBox(WaterBox): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(FourSiteWaterBox, self).__init__(model='tip4pew', *args, **kwargs)
Four-site water box (TIP4P-Ew).
62598f9f9b70327d1c57eba3
class CameraError(RuntimeError): <NEW_LINE> <INDENT> pass
Base class of the camera-related error conditions.
62598f9f32920d7e50bc5e5b
class TestCreateNamedRequest(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 testCreateNamedRequest(self): <NEW_LINE> <INDENT> pass
CreateNamedRequest unit test stubs
62598f9fac7a0e7691f72310
class CFM_650: <NEW_LINE> <INDENT> play = Buff(FRIENDLY_HAND + MURLOC, "CFM_650e")
Grimscale Chum
62598f9f76e4537e8c3ef3bc
class AbstractSCE: <NEW_LINE> <INDENT> def __init__(self, model, target_class): <NEW_LINE> <INDENT> self.model = model <NEW_LINE> self.model.eval() <NEW_LINE> self.target_class = target_class <NEW_LINE> <DEDENT> def mask_norm(self, masks): <NEW_LINE> <INDENT> return torch.norm(masks, p=1) / masks.shape[0] <NEW_LINE> <DEDENT> def mask_distance(self, mask1, mask2): <NEW_LINE> <INDENT> return torch.dist(mask1, mask2, p=2) <NEW_LINE> <DEDENT> def mean_distances(self, masks): <NEW_LINE> <INDENT> N = masks.shape[0] <NEW_LINE> if N <= 1: <NEW_LINE> <INDENT> return 0.0 <NEW_LINE> <DEDENT> res = 0.0 <NEW_LINE> for i in range(N): <NEW_LINE> <INDENT> for j in range(i + 1, N): <NEW_LINE> <INDENT> res += self.mask_distance(masks[i], masks[j]) <NEW_LINE> <DEDENT> <DEDENT> return 2 * res / (N * (N - 1)) <NEW_LINE> <DEDENT> def perturbation_operator(self, X, masks): <NEW_LINE> <INDENT> raise NotImplementedError("perturbation_operator should be implemented.") <NEW_LINE> <DEDENT> def init_masks(self, X): <NEW_LINE> <INDENT> raise NotImplementedError("init_masks should be implemented.") <NEW_LINE> <DEDENT> def get_target_class_probabilities(self, X): <NEW_LINE> <INDENT> return self.model(X)[:, self.target_class] <NEW_LINE> <DEDENT> def cost(self, X, lambda_coef, mu_coef, return_all_terms=False): <NEW_LINE> <INDENT> counterfactuals = self.perturbation_operator(X, self.masks) <NEW_LINE> term1 = torch.mean(self.get_target_class_probabilities(counterfactuals)) <NEW_LINE> term2 = torch.mean(self.mask_norm(self.masks)) <NEW_LINE> term3 = self.mean_distances(self.masks) <NEW_LINE> cost_value = term1 + lambda_coef * term2 + mu_coef * term3 <NEW_LINE> return cost_value, term1, lambda_coef * term2, mu_coef * term3 if return_all_terms else cost_value <NEW_LINE> <DEDENT> def fit(self, X, lambda_coef, mu_coef, lr=0.01, n_iter=100, force_masks_init=True, verbose=True, verbose_every_iterations=10): <NEW_LINE> <INDENT> self.X = X <NEW_LINE> if force_masks_init or not hasattr(self, 'masks'): <NEW_LINE> <INDENT> self.masks = self.init_masks(X) <NEW_LINE> <DEDENT> optimizer = optim.SGD([self.masks], lr=lr) <NEW_LINE> for i in range(n_iter): <NEW_LINE> <INDENT> optimizer.zero_grad() <NEW_LINE> cost_value, term1, term2, term3 = self.cost(X, lambda_coef, mu_coef, return_all_terms=True) <NEW_LINE> cost_value.backward() <NEW_LINE> if verbose and i % verbose_every_iterations == 0: <NEW_LINE> <INDENT> print(f"[{i}/{n_iter}] Cost: {cost_value} [{term1}, {term2}, {term3}]") <NEW_LINE> <DEDENT> optimizer.step() <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> def explanation(self): <NEW_LINE> <INDENT> return torch.mean(self.masks, dim=(0, )) <NEW_LINE> <DEDENT> def top_k_features(self, k=10, descending=True): <NEW_LINE> <INDENT> explanation = self.explanation() <NEW_LINE> return torch.argsort(explanation, descending=descending)[:k]
SCE = Sequence of Counterfactuals Explainer. This is an abstract class, which implements framework proposed by the thesis TODO[insert name here].
62598f9fd58c6744b42dc1d5
class Cutout(object): <NEW_LINE> <INDENT> def __init__(self, n_holes, length): <NEW_LINE> <INDENT> self.n_holes = n_holes <NEW_LINE> self.length = length <NEW_LINE> <DEDENT> def __call__(self, img): <NEW_LINE> <INDENT> h = img.size(1) <NEW_LINE> w = img.size(2) <NEW_LINE> mask = np.ones((h, w), np.float32) <NEW_LINE> for n in range(self.n_holes): <NEW_LINE> <INDENT> y = np.random.randint(h) <NEW_LINE> x = np.random.randint(w) <NEW_LINE> y1 = int(np.clip(y - self.length / 2, 0, h)) <NEW_LINE> y2 = int(np.clip(y + self.length / 2, 0, h)) <NEW_LINE> x1 = int(np.clip(x - self.length / 2, 0, w)) <NEW_LINE> x2 = int(np.clip(x + self.length / 2, 0, w)) <NEW_LINE> mask[y1: y2, x1: x2] = 0. <NEW_LINE> <DEDENT> mask = torch.from_numpy(mask) <NEW_LINE> mask = mask.expand_as(img) <NEW_LINE> img = img * mask <NEW_LINE> return img
Randomly mask out one or more patches from an image. Args: n_holes (int): Number of patches to cut out of each image. length (int): The length (in pixels) of each square patch.
62598f9f63d6d428bbee25b7
class UrlManager(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.check_log_file() <NEW_LINE> self.load_progress() <NEW_LINE> <DEDENT> def check_log_file(self): <NEW_LINE> <INDENT> for logfile in ['./log/failed.log', './log/tocrawl.log', './log/crawled.log']: <NEW_LINE> <INDENT> if not os.path.exists(logfile): <NEW_LINE> <INDENT> fp = open(logfile, "w") <NEW_LINE> fp.close() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def load_progress(self): <NEW_LINE> <INDENT> with open("./log/failed.log", "r") as f_failed: <NEW_LINE> <INDENT> self.failed_url = set([url.replace('\n', '') for url in f_failed.readlines()]) <NEW_LINE> <DEDENT> with open("./log/tocrawl.log", "r") as f_tocrawl: <NEW_LINE> <INDENT> self.tocrawl_url = deque([url.replace('\n', '') for url in f_tocrawl.readlines()]) <NEW_LINE> self.tocrawl_url_set = set(self.tocrawl_url) <NEW_LINE> <DEDENT> with open("./log/crawled.log", "r") as f_crawled: <NEW_LINE> <INDENT> self.crawled_url_set = set([url.replace('\n', '') for url in f_crawled.readlines()]) <NEW_LINE> <DEDENT> <DEDENT> def enqueue(self, url): <NEW_LINE> <INDENT> if url not in self.tocrawl_url_set and url not in self.crawled_url_set: <NEW_LINE> <INDENT> self.tocrawl_url.append(url) <NEW_LINE> self.tocrawl_url_set.add(url) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> def store_failed(self, url): <NEW_LINE> <INDENT> if not url in self.failed_url: <NEW_LINE> <INDENT> self.failed_url.add(url) <NEW_LINE> <DEDENT> <DEDENT> def dump(self): <NEW_LINE> <INDENT> with open("./log/failed.log", "w") as f_failed: <NEW_LINE> <INDENT> for url in self.failed_url: <NEW_LINE> <INDENT> f_failed.write(url + '\n') <NEW_LINE> <DEDENT> <DEDENT> with open("./log/tocrawl.log", "w") as f_tocrawl: <NEW_LINE> <INDENT> for url in self.tocrawl_url: <NEW_LINE> <INDENT> f_tocrawl.write(url + '\n') <NEW_LINE> <DEDENT> <DEDENT> with open("./log/crawled.log", "w") as f_crawled: <NEW_LINE> <INDENT> for url in self.crawled_url_set: <NEW_LINE> <INDENT> f_crawled.write(url + '\n') <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def dequeue(self): <NEW_LINE> <INDENT> url = self.tocrawl_url.popleft() <NEW_LINE> self.tocrawl_url_set.remove(url) <NEW_LINE> self.crawled_url_set.add(url) <NEW_LINE> return url <NEW_LINE> <DEDENT> def empty(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.tocrawl_url.appendleft(self.tocrawl_url.popleft()) <NEW_LINE> return False <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> return True
manage the urls
62598f9fcc0a2c111447ae12
class InterpreterWithCustomOps(Interpreter): <NEW_LINE> <INDENT> def __init__(self, custom_op_registerers=None, **kwargs): <NEW_LINE> <INDENT> self._custom_op_registerers = custom_op_registerers or [] <NEW_LINE> super(InterpreterWithCustomOps, self).__init__(**kwargs)
Interpreter interface for TensorFlow Lite Models that accepts custom ops. The interface provided by this class is experimental and therefore not exposed as part of the public API. Wraps the tf.lite.Interpreter class and adds the ability to load custom ops by providing the names of functions that take a pointer to a BuiltinOpResolver and add a custom op.
62598f9f656771135c489489
class IJLogHandler(logging.StreamHandler): <NEW_LINE> <INDENT> def emit(self, record): <NEW_LINE> <INDENT> IJ.log(self.format(record))
A logging handler sending everything to IJ.log().
62598f9f8e7ae83300ee8ea5
class ColorizedTextReporter(TextReporter): <NEW_LINE> <INDENT> COLOR_MAPPING = { "I" : ("green", None), 'C' : (None, "bold"), 'R' : ("magenta", "bold, italic"), 'W' : ("blue", None), 'E' : ("red", "bold"), 'F' : ("red", "bold, underline"), 'S' : ("yellow", "inverse"), } <NEW_LINE> def __init__(self, output=sys.stdout, color_mapping = None): <NEW_LINE> <INDENT> TextReporter.__init__(self, output) <NEW_LINE> self.color_mapping = color_mapping or dict(ColorizedTextReporter.COLOR_MAPPING) <NEW_LINE> <DEDENT> def _get_decoration(self, msg_id): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.color_mapping[msg_id[0]] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return None, None <NEW_LINE> <DEDENT> <DEDENT> def add_message(self, msg_id, location, msg): <NEW_LINE> <INDENT> module, obj, line = location[1:] <NEW_LINE> if module not in self._modules: <NEW_LINE> <INDENT> color, style = self._get_decoration('S') <NEW_LINE> if module: <NEW_LINE> <INDENT> modsep = colorize_ansi('************* Module %s' % module, color, style) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> modsep = colorize_ansi('************* %s' % module, color, style) <NEW_LINE> <DEDENT> self.writeln(modsep) <NEW_LINE> self._modules[module] = 1 <NEW_LINE> <DEDENT> if obj: <NEW_LINE> <INDENT> obj = ':%s' % obj <NEW_LINE> <DEDENT> if self.include_ids: <NEW_LINE> <INDENT> sigle = msg_id <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sigle = msg_id[0] <NEW_LINE> <DEDENT> color, style = self._get_decoration(sigle) <NEW_LINE> msg = colorize_ansi(msg, color, style) <NEW_LINE> sigle = colorize_ansi(sigle, color, style) <NEW_LINE> self.writeln('%s:%3s%s: %s' % (sigle, line, obj, msg))
Simple TextReporter that colorizes text output
62598f9f8e71fb1e983bb8bc
class Newsletters(BaseModel): <NEW_LINE> <INDENT> yearly: List[Newsletter] = Field(default_factory=list) <NEW_LINE> monthly: List[Newsletter] = Field(default_factory=list) <NEW_LINE> weekly: List[Newsletter] = Field(default_factory=list) <NEW_LINE> daily: List[Newsletter] = Field(default_factory=list) <NEW_LINE> def sort(self) -> None: <NEW_LINE> <INDENT> self.yearly = sorted(self.yearly, reverse=True) <NEW_LINE> self.monthly = sorted(self.monthly, reverse=True) <NEW_LINE> self.weekly = sorted(self.weekly, reverse=True) <NEW_LINE> self.daily = sorted(self.daily, reverse=True)
Represents the newsletters for each feed type.
62598f9fa17c0f6771d5c040
class TestConfig(config): <NEW_LINE> <INDENT> ENV = 'test' <NEW_LINE> TESTING = True <NEW_LINE> DEBUG = True
Test configuration
62598f9f851cf427c66b80ce
class MessageDispatcher(object): <NEW_LINE> <INDENT> message_to_method = { 0x0001: 'c_store', 0x0020: 'c_find', 0x0010: 'c_get', 0x0021: 'c_move', 0x0030: 'c_echo', 0x0100: 'n_event_report', 0x0110: 'n_get', 0x0120: 'n_set', 0x0130: 'n_action', 0x0140: 'n_create', 0x0150: 'n_delete', } <NEW_LINE> def get_method(self, msg): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> name = self.message_to_method[msg.command_field] <NEW_LINE> return getattr(self, name) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise exceptions.DIMSEProcessingError('Unknown message type') <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> raise exceptions.DIMSEProcessingError( 'Message type is not supported by service class')
Base class for message dispatcher service. Class provides method for selecting method based on incoming message type.
62598f9f4e4d56256637222a
class FileLock: <NEW_LINE> <INDENT> def __init__(self, file_path, expire=60 * 60 * 2): <NEW_LINE> <INDENT> self.expire = expire <NEW_LINE> self.fpath = file_path <NEW_LINE> self.fd = None <NEW_LINE> <DEDENT> def lock(self): <NEW_LINE> <INDENT> if os.path.exists(self.fpath): <NEW_LINE> <INDENT> if (time.time() - os.stat(self.fpath).st_ctime) > self.expire: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> os.unlink(self.fpath) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> message('FileLock.lock({}) : {}'.format(self.fpath, e)) <NEW_LINE> return False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> try: <NEW_LINE> <INDENT> self.fd = open(self.fpath, 'w') <NEW_LINE> fcntl.flock(self.fd, fcntl.LOCK_EX | fcntl.LOCK_NB) <NEW_LINE> <DEDENT> except IOError as e: <NEW_LINE> <INDENT> message('FileLock.lock({}) : {}'.format(self.fpath, e)) <NEW_LINE> return False <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> def unlock(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> fcntl.flock(self.fd, fcntl.LOCK_UN | fcntl.LOCK_NB) <NEW_LINE> self.fd.close() <NEW_LINE> <DEDENT> except IOError as e: <NEW_LINE> <INDENT> message('FileLock.unlock({}) : {}'.format(self.fpath, e))
Lock/Unlock file
62598f9f92d797404e388a69
class OptimizerWithSparsityGuarantee(object): <NEW_LINE> <INDENT> def __init__(self, optimizer): <NEW_LINE> <INDENT> self._optimizer = optimizer <NEW_LINE> self._learning_rate = optimizer._learning_rate <NEW_LINE> self._learning_rate_map = optimizer._learning_rate_map <NEW_LINE> <DEDENT> def minimize(self, loss, startup_program=None, parameter_list=None, no_grad_set=None): <NEW_LINE> <INDENT> return ASPHelper._minimize( self._optimizer, loss, startup_program=startup_program, parameter_list=parameter_list, no_grad_set=no_grad_set)
OptimizerWithSparsityGuarantee is a wrapper to decorate `minimize` function of given optimizer by `_minimize` of ASPHelper. The decorated `minimize` function would do three things (exactly same as `ASPHelper._minimize`): 1. Call `minimize` function of given optimizer. 2. Call `ASPHelper._create_mask_variables` to create mask Variables. 3. Call `ASPHelper._insert_sparse_mask_ops` to insert weight masking ops in the end of `loss`'s Program.
62598f9f2c8b7c6e89bd35d5