code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class InputHandlerEvent(object): <NEW_LINE> <INDENT> deserialized_types = { 'name': 'str', 'input_events': 'list[ask_sdk_model.services.game_engine.input_event.InputEvent]' } <NEW_LINE> attribute_map = { 'name': 'name', 'input_events': 'inputEvents' } <NEW_LINE> def __init__(self, name=None, input_events=None): <NEW_LINE> <INDENT> self.__discriminator_value = None <NEW_LINE> self.name = name <NEW_LINE> self.input_events = input_events <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.deserialized_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 if isinstance(x, Enum) else x, value )) <NEW_LINE> <DEDENT> elif isinstance(value, Enum): <NEW_LINE> <INDENT> result[attr] = value.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[0], item[1].value) if isinstance(item[1], Enum) 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, InputHandlerEvent): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | :param name: The name of the event as you defined it in your GameEngine.StartInputHandler directive.
:type name: (optional) str
:param input_events: A chronologically ordered report of the raw Button Events that contributed to this Input Handler Event.
:type input_events: (optional) list[ask_sdk_model.services.game_engine.input_event.InputEvent] | 62598fbe7047854f4633f5c5 |
class SSD1351(DisplaySPI): <NEW_LINE> <INDENT> _COLUMN_SET = _SETCOLUMN <NEW_LINE> _PAGE_SET = _SETROW <NEW_LINE> _RAM_WRITE = _WRITERAM <NEW_LINE> _RAM_READ = _READRAM <NEW_LINE> _INIT = ( (_COMMANDLOCK, b"\x12"), (_COMMANDLOCK, b"\xb1"), (_DISPLAYOFF, b""), (_DISPLAYENHANCE, b"\xa4\x00\x00"), (_CLOCKDIV, b"\xf0"), (_MUXRATIO, b"\x7f"), (_SETREMAP, b"\x74"), (_STARTLINE, b"\x00"), (_DISPLAYOFFSET, b"\x00"), (_SETGPIO, b"\x00"), (_FUNCTIONSELECT, b"\x01"), (_PRECHARGE, b"\x32"), (_PRECHARGELEVEL, b"\x1f"), (_VCOMH, b"\x05"), (_NORMALDISPLAY, b""), (_CONTRASTABC, b"\xc8\x80\xc8"), (_CONTRASTMASTER, b"\x0a"), (_SETVSL, b"\xa0\xb5\x55"), (_PRECHARGE2, b"\x01"), (_DISPLAYON, b""), ) <NEW_LINE> _ENCODE_PIXEL = ">H" <NEW_LINE> _ENCODE_POS = ">BB" <NEW_LINE> def __init__( self, spi, dc, cs, rst=None, width=128, height=128, baudrate=16000000, polarity=0, phase=0, *, x_offset=0, y_offset=0, rotation=0 ): <NEW_LINE> <INDENT> baudrate = min(baudrate, 16000000) <NEW_LINE> super().__init__( spi, dc, cs, rst, width, height, baudrate=baudrate, polarity=polarity, phase=phase, x_offset=x_offset, y_offset=y_offset, rotation=rotation, ) | A simple driver for the SSD1351-based displays.
>>> import busio
>>> import digitalio
>>> import board
>>> from adafruit_rgb_display import color565
>>> import adafruit_rgb_display.ssd1351 as ssd1351
>>> spi = busio.SPI(clock=board.SCK, MOSI=board.MOSI, MISO=board.MISO)
>>> display = ssd1351.SSD1351(spi, cs=digitalio.DigitalInOut(board.GPIO0),
... dc=digitalio.DigitalInOut(board.GPIO15), rst=digitalio.DigitalInOut(board.GPIO16))
>>> display.fill(0x7521)
>>> display.pixel(32, 32, 0) | 62598fbee5267d203ee6baf1 |
class BreslowFlemingHarringtonFitter(object): <NEW_LINE> <INDENT> def __init__(self, alpha=0.95): <NEW_LINE> <INDENT> self.alpha = alpha <NEW_LINE> <DEDENT> def fit(self, durations, event_observed=None, timeline=None, entry=None, label='BFH-estimate', alpha=None): <NEW_LINE> <INDENT> naf = NelsonAalenFitter(self.alpha) <NEW_LINE> naf.fit(durations, event_observed=event_observed, timeline=timeline, label=label, entry=entry) <NEW_LINE> self.durations, self.event_observed, self.timeline, self.entry, self.event_table = naf.durations, naf.event_observed, naf.timeline, naf.entry, naf.event_table <NEW_LINE> self.survival_function_ = np.exp(-naf.cumulative_hazard_) <NEW_LINE> self.confidence_interval_ = np.exp(-naf.confidence_interval_) <NEW_LINE> self.median_ = median_survival_times(self.survival_function_) <NEW_LINE> self.predict = _predict(self, "survival_function_", label) <NEW_LINE> self.subtract = _subtract(self, "survival_function_") <NEW_LINE> self.divide = _divide(self, "survival_function_") <NEW_LINE> self.plot = plot_estimate(self, "survival_function_") <NEW_LINE> self.plot_survival_function = self.plot <NEW_LINE> return self <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> s = """<lifelines.BreslowFlemingHarringtonFitter: fitted with %d observations, %d censored>""" % ( self.event_observed.shape[0], (1-self.event_observed).sum()) <NEW_LINE> <DEDENT> except AttributeError as e: <NEW_LINE> <INDENT> s = """<lifelines.BreslowFlemingHarringtonFitter>""" <NEW_LINE> <DEDENT> return s | Class for fitting the Breslow-Fleming-Harrington estimate for the survival function. This estimator
is a biased estimator of the survival function but is more stable when the popualtion is small and
there are too few early truncation times, it may happen that is the number of patients at risk and
the number of deaths is the same.
Mathematically, the NAF estimator is the negative logarithm of the BFH estimator.
BreslowFlemingHarringtonFitter(alpha=0.95)
alpha: The alpha value associated with the confidence intervals. | 62598fbe7d43ff24874274fd |
class FilterQueue(object): <NEW_LINE> <INDENT> def __init__(self, bloomd_client=None, crawler_name=None, capacity=1e8, prob=1e-5): <NEW_LINE> <INDENT> if bloomd_client is None: <NEW_LINE> <INDENT> raise FilterError("bloomd_client cannot be None") <NEW_LINE> <DEDENT> if crawler_name is None: <NEW_LINE> <INDENT> raise FilterError("crawler_name cannot be None") <NEW_LINE> <DEDENT> self.bloomd_client = bloomd_client <NEW_LINE> self.filter = self.bloomd_client.create_filter( crawler_name, capacity=capacity, prob=prob ) <NEW_LINE> <DEDENT> def push(self, url): <NEW_LINE> <INDENT> self.filter.add(url) <NEW_LINE> <DEDENT> def is_member(self, url): <NEW_LINE> <INDENT> if url in self.filter: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False | We use this class to define interface to check where url is
crawled or not. We use bloomd server on backend currently. | 62598fbe60cbc95b0636452f |
class NoSuchDriverError(BaseError): <NEW_LINE> <INDENT> pass | Drastic Base Exception. | 62598fbe56ac1b37e63023e0 |
class Visitor(ast.NodeVisitor): <NEW_LINE> <INDENT> def __init__(self, lines): <NEW_LINE> <INDENT> self.parent = self.top = ModuleDecl('', 0) <NEW_LINE> self.lines = lines <NEW_LINE> self.last_lineno = 1 <NEW_LINE> self.closing_decls = [] <NEW_LINE> <DEDENT> def visitdecl(self, node, cls): <NEW_LINE> <INDENT> decl = cls(node.name, node.lineno - 1) <NEW_LINE> parent = self.parent <NEW_LINE> decl.parent_ref = weakref.ref(parent) <NEW_LINE> parent.children.append(decl) <NEW_LINE> self.last_lineno = node.lineno <NEW_LINE> self.parent = decl <NEW_LINE> self.generic_visit(node) <NEW_LINE> self.parent = parent <NEW_LINE> decl.last_row = self.last_lineno - 1 <NEW_LINE> self.closing_decls.append(decl) <NEW_LINE> <DEDENT> def visit_FunctionDef(self, node): <NEW_LINE> <INDENT> self.close_decls(node.lineno) <NEW_LINE> self.visitdecl(node, FuncDecl) <NEW_LINE> <DEDENT> def visit_ClassDef(self, node): <NEW_LINE> <INDENT> self.close_decls(node.lineno) <NEW_LINE> self.visitdecl(node, ClassDecl) <NEW_LINE> <DEDENT> def generic_visit(self, node): <NEW_LINE> <INDENT> if hasattr(node, 'lineno'): <NEW_LINE> <INDENT> self.close_decls(node.lineno) <NEW_LINE> self.last_lineno = max(self.last_lineno, node.lineno) <NEW_LINE> <DEDENT> super(Visitor, self).generic_visit(node) <NEW_LINE> <DEDENT> def close_decls(self, new_lineno): <NEW_LINE> <INDENT> decls = self.closing_decls <NEW_LINE> if decls: <NEW_LINE> <INDENT> last_row = new_lineno - 2 <NEW_LINE> while last_row > 0 and last_row < len(self.lines): <NEW_LINE> <INDENT> line = self.lines[last_row] <NEW_LINE> if not line or empty_line_re.match(line): <NEW_LINE> <INDENT> last_row -= 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> for decl in decls: <NEW_LINE> <INDENT> decl.last_row = max(last_row, decl.last_row) <NEW_LINE> <DEDENT> del self.closing_decls[:] | Create a Decl tree from a Python abstract syntax tree. | 62598fbe4428ac0f6e658715 |
class Armor(Item): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def Chestplate() -> Armor: <NEW_LINE> <INDENT> return Armor("Chestplate", 5) <NEW_LINE> <DEDENT> def __init__(self, name: str, defense: int) -> None: <NEW_LINE> <INDENT> super().__init__(name) <NEW_LINE> self.defense = defense | Represents an armor item. | 62598fbefff4ab517ebcd9d7 |
class InvalidPaginationToken(Route53ClientError): <NEW_LINE> <INDENT> code = 400 <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> message = ( "Route 53 can't get the next page of query logging configurations " "because the specified value for NextToken is invalid." ) <NEW_LINE> super().__init__("InvalidPaginationToken", message) | Bad NextToken specified when listing query logging configs. | 62598fbecc40096d6161a2d2 |
class MapRelativeVectorSpaceToRelativeNumberField(NumberFieldIsomorphism): <NEW_LINE> <INDENT> def __init__(self, V, K): <NEW_LINE> <INDENT> NumberFieldIsomorphism.__init__(self, Hom(V, K)) <NEW_LINE> <DEDENT> def _call_(self, v): <NEW_LINE> <INDENT> K = self.codomain() <NEW_LINE> B = K.base_field().absolute_field('a') <NEW_LINE> _, to_B = B.structure() <NEW_LINE> h = pari([to_B(a)._pari_('y') for a in v]).Polrev() <NEW_LINE> g = K._pari_rnfeq()._eltreltoabs(h) <NEW_LINE> return K._element_class(K, g) | EXAMPLES::
sage: L.<b> = NumberField(x^4 + 3*x^2 + 1)
sage: K = L.relativize(L.subfields(2)[0][1], 'a'); K
Number Field in a with defining polynomial x^2 - b0*x + 1 over its base field
sage: V, fr, to = K.relative_vector_space()
sage: V
Vector space of dimension 2 over Number Field in b0 with defining polynomial x^2 + 1
sage: fr
Isomorphism map:
From: Vector space of dimension 2 over Number Field in b0 with defining polynomial x^2 + 1
To: Number Field in a with defining polynomial x^2 - b0*x + 1 over its base field
sage: type(fr)
<class 'sage.rings.number_field.maps.MapRelativeVectorSpaceToRelativeNumberField'>
sage: a0 = K.gen(); b0 = K.base_field().gen()
sage: fr(to(a0 + 2*b0)), fr(V([0, 1])), fr(V([b0, 2*b0]))
(a + 2*b0, a, 2*b0*a + b0)
sage: (fr * to)(K.gen()) == K.gen()
True
sage: (to * fr)(V([1, 2])) == V([1, 2])
True | 62598fbedc8b845886d537ad |
class SimpleVirus(object): <NEW_LINE> <INDENT> def __init__(self, maxBirthProb, clearProb): <NEW_LINE> <INDENT> self.maxBirthProb = maxBirthProb <NEW_LINE> self.clearProb = clearProb <NEW_LINE> <DEDENT> def getMaxBirthProb(self): <NEW_LINE> <INDENT> return self.maxBirthProb <NEW_LINE> <DEDENT> def getClearProb(self): <NEW_LINE> <INDENT> return self.clearProb <NEW_LINE> <DEDENT> def doesClear(self): <NEW_LINE> <INDENT> if self.clearProb > random.random(): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def reproduce(self, popDensity): <NEW_LINE> <INDENT> if (self.getMaxBirthProb() * (1 - popDensity)) > random.random(): <NEW_LINE> <INDENT> return SimpleVirus(self.getMaxBirthProb(), self.getClearProb()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise NoChildException | Representation of a simple virus (does not model drug effects/resistance). | 62598fbecc0a2c111447b200 |
class SoundFile: <NEW_LINE> <INDENT> def __init__(self, filepath, volume=1): <NEW_LINE> <INDENT> self.filepath = filepath <NEW_LINE> self.volume = volume <NEW_LINE> <DEDENT> async def play(self, client, channel): <NEW_LINE> <INDENT> voice = await client.join_voice_channel(channel) <NEW_LINE> player = voice.create_ffmpeg_player(self.filepath) <NEW_LINE> player.volume = self.volume <NEW_LINE> player.start() <NEW_LINE> while(not player.is_done()): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> await voice.disconnect() | A class representing a sound file | 62598fbe167d2b6e312b7169 |
class ValueEstimator(): <NEW_LINE> <INDENT> def __init__(self, learning_rate=0.1, scope="value_estimator"): <NEW_LINE> <INDENT> with tf.variable_scope(scope): <NEW_LINE> <INDENT> self.state = tf.placeholder(tf.int32, [], "state") <NEW_LINE> self.target = tf.placeholder(dtype=tf.float32, name="target") <NEW_LINE> state_one_hot = tf.one_hot(self.state, int(env.observation_space.n)) <NEW_LINE> self.output_layer = tf.contrib.layers.fully_connected( inputs=tf.expand_dims(state_one_hot, 0), num_outputs=1, activation_fn=None, weights_initializer=tf.zeros_initializer) <NEW_LINE> self.value_estimate = tf.squeeze(self.output_layer) <NEW_LINE> self.loss = tf.squared_difference(self.value_estimate, self.target) <NEW_LINE> self.optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate) <NEW_LINE> self.train_op = self.optimizer.minimize( self.loss, global_step=tf.contrib.framework.get_global_step()) <NEW_LINE> <DEDENT> <DEDENT> def predict(self, state, sess=None): <NEW_LINE> <INDENT> sess = sess or tf.get_default_session() <NEW_LINE> return sess.run(self.value_estimate, { self.state: state }) <NEW_LINE> <DEDENT> def update(self, state, target, sess=None): <NEW_LINE> <INDENT> sess = sess or tf.get_default_session() <NEW_LINE> feed_dict = { self.state: state, self.target: target } <NEW_LINE> _, loss = sess.run([self.train_op, self.loss], feed_dict) <NEW_LINE> return loss | Value Function approximator. | 62598fbe97e22403b383b0fc |
class DdosProtectionPlan(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'etag': {'readonly': True}, 'resource_guid': {'readonly': True}, 'provisioning_state': {'readonly': True}, 'virtual_networks': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'etag': {'key': 'etag', 'type': 'str'}, 'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'virtual_networks': {'key': 'properties.virtualNetworks', 'type': '[SubResource]'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(DdosProtectionPlan, self).__init__(**kwargs) <NEW_LINE> self.id = None <NEW_LINE> self.name = None <NEW_LINE> self.type = None <NEW_LINE> self.location = kwargs.get('location', None) <NEW_LINE> self.tags = kwargs.get('tags', None) <NEW_LINE> self.etag = None <NEW_LINE> self.resource_guid = None <NEW_LINE> self.provisioning_state = None <NEW_LINE> self.virtual_networks = None | A DDoS protection plan in a resource group.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: Resource ID.
:vartype id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:ivar resource_guid: The resource GUID property of the DDoS protection plan resource. It
uniquely identifies the resource, even if the user changes its name or migrate the resource
across subscriptions or resource groups.
:vartype resource_guid: str
:ivar provisioning_state: The provisioning state of the DDoS protection plan resource. Possible
values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2019_09_01.models.ProvisioningState
:ivar virtual_networks: The list of virtual networks associated with the DDoS protection plan
resource. This list is read-only.
:vartype virtual_networks: list[~azure.mgmt.network.v2019_09_01.models.SubResource] | 62598fbeadb09d7d5dc0a771 |
class zAttr(Attr): <NEW_LINE> <INDENT> ENTRY_ = const.zENTRY_ <NEW_LINE> ENTRY_DATA_ = const.zENTRY_DATA_ <NEW_LINE> SCOPE = const.VARIABLE_SCOPE <NEW_LINE> ENTRY_EXISTENCE_ = const.zENTRY_EXISTENCE_ <NEW_LINE> ATTR_NUMENTRIES_ = const.ATTR_NUMzENTRIES_ <NEW_LINE> ATTR_MAXENTRY_ = const.ATTR_MAXzENTRY_ <NEW_LINE> ENTRY_NUMELEMS_ = const.zENTRY_NUMELEMS_ <NEW_LINE> ENTRY_DATATYPE_ = const.zENTRY_DATATYPE_ <NEW_LINE> ENTRY_DATASPEC_ = const.zENTRY_DATASPEC_ <NEW_LINE> def insert(self, index, data): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def append(self, index, data): <NEW_LINE> <INDENT> raise NotImplementedError | zAttribute for zVariables within a CDF.
.. warning::
Because zAttributes are shared across all variables in a CDF,
directly manipulating them may have unexpected consequences.
It is safest to operate on zEntries via :class:`zAttrList`.
.. note::
When accessing a zAttr, pyCDF exposes only the zEntry corresponding
to the associated zVariable.
See Also
========
:class:`Attr` | 62598fbe66656f66f7d5a5e7 |
class BatchTuner(Tuner): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.count = -1 <NEW_LINE> self.values = [] <NEW_LINE> <DEDENT> def is_valid(self, search_space): <NEW_LINE> <INDENT> if not len(search_space) == 1: <NEW_LINE> <INDENT> raise RuntimeError('BatchTuner only supprt one combined-paramreters key.') <NEW_LINE> <DEDENT> for param in search_space: <NEW_LINE> <INDENT> param_type = search_space[param][TYPE] <NEW_LINE> if not param_type == CHOICE: <NEW_LINE> <INDENT> raise RuntimeError('BatchTuner only supprt one combined-paramreters type is choice.') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if isinstance(search_space[param][VALUE], list): <NEW_LINE> <INDENT> return search_space[param][VALUE] <NEW_LINE> <DEDENT> raise RuntimeError('The combined-paramreters value in BatchTuner is not a list.') <NEW_LINE> <DEDENT> <DEDENT> return None <NEW_LINE> <DEDENT> def update_search_space(self, search_space): <NEW_LINE> <INDENT> self.values = self.is_valid(search_space) <NEW_LINE> <DEDENT> def generate_parameters(self, parameter_id): <NEW_LINE> <INDENT> self.count +=1 <NEW_LINE> if self.count>len(self.values)-1: <NEW_LINE> <INDENT> raise nni.NoMoreTrialError('no more parameters now.') <NEW_LINE> <DEDENT> return self.values[self.count] <NEW_LINE> <DEDENT> def receive_trial_result(self, parameter_id, parameters, value): <NEW_LINE> <INDENT> pass | BatchTuner is tuner will running all the configure that user want to run batchly.
The search space only be accepted like:
{
'combine_params': { '_type': 'choice',
'_value': '[{...}, {...}, {...}]',
}
} | 62598fbe56ac1b37e63023e2 |
class CueSheetTrack(object): <NEW_LINE> <INDENT> def __init__(self, track_number, start_offset, isrc='', type_=0, pre_emphasis=False): <NEW_LINE> <INDENT> self.track_number = track_number <NEW_LINE> self.start_offset = start_offset <NEW_LINE> self.isrc = isrc <NEW_LINE> self.type = type_ <NEW_LINE> self.pre_emphasis = pre_emphasis <NEW_LINE> self.indexes = [] <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return (self.track_number == other.track_number and self.start_offset == other.start_offset and self.isrc == other.isrc and self.type == other.type and self.pre_emphasis == other.pre_emphasis and self.indexes == other.indexes) <NEW_LINE> <DEDENT> except (AttributeError, TypeError): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> __hash__ = object.__hash__ <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return (("<%s number=%r, offset=%d, isrc=%r, type=%r, " "pre_emphasis=%r, indexes=%r)>") % (type(self).__name__, self.track_number, self.start_offset, self.isrc, self.type, self.pre_emphasis, self.indexes)) | CueSheetTrack()
A track in a cuesheet.
For CD-DA, track_numbers must be 1-99, or 170 for the
lead-out. Track_numbers must be unique within a cue sheet. There
must be atleast one index in every track except the lead-out track
which must have none.
Attributes:
track_number (`int`): track number
start_offset (`int`): track offset in samples from start of FLAC stream
isrc (`mutagen.text`): ISRC code, exactly 12 characters
type (`int`): 0 for audio, 1 for digital data
pre_emphasis (`bool`): true if the track is recorded with pre-emphasis
indexes (list[CueSheetTrackIndex]):
list of CueSheetTrackIndex objects | 62598fbe99fddb7c1ca62ee6 |
@python_2_unicode_compatible <NEW_LINE> class Submit(models.Model): <NEW_LINE> <INDENT> receiver = models.ForeignKey(SubmitReceiver) <NEW_LINE> user = models.ForeignKey(django_settings.AUTH_USER_MODEL) <NEW_LINE> time = models.DateTimeField(auto_now_add=True) <NEW_LINE> filename = models.CharField(max_length=128, blank=True) <NEW_LINE> NOT_ACCEPTED = 0 <NEW_LINE> ACCEPTED_WITH_PENALIZATION = 1 <NEW_LINE> ACCEPTED = 2 <NEW_LINE> IS_ACCEPTED_CHOICES = [ (NOT_ACCEPTED, _('no')), (ACCEPTED_WITH_PENALIZATION, _('with penalization')), (ACCEPTED, _('yes')), ] <NEW_LINE> is_accepted = models.IntegerField(default=ACCEPTED, choices=IS_ACCEPTED_CHOICES) <NEW_LINE> objects = models.Manager() <NEW_LINE> with_reviews = SubmitWithReviewManager() <NEW_LINE> def dir_path(self): <NEW_LINE> <INDENT> return os.path.join(submit_settings.SUBMIT_PATH, 'submits', str(self.user.id), str(self.receiver.id), str(self.id)) <NEW_LINE> <DEDENT> def file_path(self): <NEW_LINE> <INDENT> return os.path.join(self.dir_path(), str(self.id) + constants.SUBMITTED_FILE_EXTENSION) <NEW_LINE> <DEDENT> def file_exists(self): <NEW_LINE> <INDENT> return os.path.exists(self.file_path()) <NEW_LINE> <DEDENT> def get_last_review(self): <NEW_LINE> <INDENT> if hasattr(self, 'last_reviews_list'): <NEW_LINE> <INDENT> return self.last_reviews_list[0] if len(self.last_reviews_list) > 0 else None <NEW_LINE> <DEDENT> return self.review_set.order_by('-time', '-pk').first() <NEW_LINE> <DEDENT> last_review = property(get_last_review) <NEW_LINE> def get_absolute_url(self): <NEW_LINE> <INDENT> return reverse('submit.views.view_submit', kwargs=dict(submit_id=self.id)) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = 'submit' <NEW_LINE> verbose_name_plural = 'submits' <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return 'submit %d (%s, %s, %s)' % ( self.id, self.user, self.receiver, self.time.strftime('%H:%M:%S %d.%m.%Y'), ) | Submit holds information about user-submitted data. | 62598fbe21bff66bcd722e5e |
class Contact_info(models.Model): <NEW_LINE> <INDENT> address = models.CharField(verbose_name='地址', max_length=30) <NEW_LINE> phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="号码格式不正确") <NEW_LINE> phone_number = models.CharField('手机号码', max_length=20, validators=[phone_regex], blank=True) <NEW_LINE> customer = models.ForeignKey(Customer, blank=True, null=True, on_delete=models.SET_NULL) <NEW_LINE> default = models.BooleanField(verbose_name='默认方式', default=False) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = '联系方式' <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return '%s-%s' % (self.customer.name, self.phone_number) | 联系方式 | 62598fbe377c676e912f6e6c |
class LDIFDeltaModificationMissingEndDashError(ldifprotocol.LDIFParseError): <NEW_LINE> <INDENT> pass | LDIF delta modification has no ending dash. | 62598fbebf627c535bcb169a |
class LatencyAwareRequestSimulator(object): <NEW_LINE> <INDENT> def __init__( self, worker_desc, load_balancer, latency_fn, number_of_requests, request_per_s): <NEW_LINE> <INDENT> self.worker_desc = worker_desc <NEW_LINE> self.load_balancer = load_balancer <NEW_LINE> self.latency_fn = latency_fn <NEW_LINE> self.number_of_requests = int(number_of_requests) <NEW_LINE> self.request_interval_ms = 1. / (request_per_s / 1000.) <NEW_LINE> self.data = [] <NEW_LINE> self.requests_per_worker = {} <NEW_LINE> <DEDENT> def simulate(self): <NEW_LINE> <INDENT> random.seed(1) <NEW_LINE> np.random.seed(1) <NEW_LINE> self.env = simpy.Environment() <NEW_LINE> self.workers = [] <NEW_LINE> idx = 0 <NEW_LINE> for cap in self.worker_desc: <NEW_LINE> <INDENT> self.workers.append(simpy.Resource(self.env, capacity=cap)) <NEW_LINE> self.requests_per_worker[idx] = 0 <NEW_LINE> idx += 1 <NEW_LINE> <DEDENT> self.env.process(self.generate_requests()) <NEW_LINE> self.env.run() <NEW_LINE> <DEDENT> def generate_requests(self): <NEW_LINE> <INDENT> for i in range(self.number_of_requests): <NEW_LINE> <INDENT> t_processing = self.latency_fn(i) <NEW_LINE> idx = self.load_balancer(i, self.workers, t_processing) <NEW_LINE> self.requests_per_worker[idx] += 1 <NEW_LINE> worker = self.workers[idx] <NEW_LINE> response = self.process_request( i, worker, t_processing ) <NEW_LINE> self.env.process(response) <NEW_LINE> arrival_interval = random.expovariate( 1.0 / self.request_interval_ms ) <NEW_LINE> yield self.env.timeout(arrival_interval) <NEW_LINE> <DEDENT> <DEDENT> def process_request(self, request_id, worker, duration): <NEW_LINE> <INDENT> t_arrive = self.env.now <NEW_LINE> with worker.request() as req: <NEW_LINE> <INDENT> yield req <NEW_LINE> t_start = self.env.now <NEW_LINE> t_queued = t_start - t_arrive <NEW_LINE> yield self.env.timeout(duration) <NEW_LINE> t_done = self.env.now <NEW_LINE> t_processing = t_done - t_start <NEW_LINE> t_total_response = t_done - t_arrive <NEW_LINE> datum = LatencyDatum(t_queued, t_processing, t_total_response) <NEW_LINE> self.data.append(datum) | Simulates a M/G/k process common in request processing (computing)
:param worker_desc: A list of ints of capacities to construct workers with
:param local_balancer: A function which takes the current request number
the list of workers and the request time and returns the index of the
worker to send the next request to
:param latency_fn: A function which takes the curent request number and
returns the number of milliseconds a request took to process
:param number_of_requests: The number of requests to run through the
simulator
:param request_per_s: The rate of requests per second. | 62598fbe76e4537e8c3ef79b |
class AbstractGameUnit(metaclass=ABCMeta): <NEW_LINE> <INDENT> def __init__(self, name=''): <NEW_LINE> <INDENT> self.max_hp = 0 <NEW_LINE> self.health_meter = 0 <NEW_LINE> self.name = name <NEW_LINE> self.enemy = None <NEW_LINE> self.unit_type = None <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def info(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def attack(self, enemy): <NEW_LINE> <INDENT> injured_unit = weighted_random_selection(self, enemy) <NEW_LINE> injury = random.randint(10, 15) <NEW_LINE> injured_unit.health_meter = max(injured_unit.health_meter - injury, 0) <NEW_LINE> print("ATTACK! ", end='') <NEW_LINE> self.show_health(end=' ') <NEW_LINE> enemy.show_health(end=' ') <NEW_LINE> <DEDENT> def heal(self, heal_by=2, full_healing=True): <NEW_LINE> <INDENT> if self.health_meter == self.max_hp: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if full_healing: <NEW_LINE> <INDENT> self.health_meter = self.max_hp <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.health_meter += heal_by <NEW_LINE> <DEDENT> print_bold("You are HEALED!", end=' ') <NEW_LINE> self.show_health(bold=True) <NEW_LINE> <DEDENT> def reset_health_meter(self): <NEW_LINE> <INDENT> self.health_meter = self.max_hp <NEW_LINE> <DEDENT> def show_health(self, bold=False, end='\n'): <NEW_LINE> <INDENT> msg = "Health: %s: %d" % (self.name, self.health_meter) <NEW_LINE> if bold: <NEW_LINE> <INDENT> print_bold(msg, end=end) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print(msg, end=end) | An Abstract base class for creating various game characters | 62598fbe4f6381625f1995bc |
class SmartFormatBaseException(Exception): <NEW_LINE> <INDENT> pass | Base for every SmartFormat template tag exceptions. | 62598fbe283ffb24f3cf3a78 |
class IfNode(Node): <NEW_LINE> <INDENT> def __init__(self, predicate): <NEW_LINE> <INDENT> self.predicate = predicate <NEW_LINE> self.child = None <NEW_LINE> <DEDENT> def set_child(self, child): <NEW_LINE> <INDENT> self.child = child <NEW_LINE> <DEDENT> def evaluate(self, context): <NEW_LINE> <INDENT> if eval(self.predicate, {}, context): <NEW_LINE> <INDENT> return self.child.evaluate(context) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return '' | Renders content if predicate | 62598fbe5fdd1c0f98e5e187 |
class ParseOFX(IPlugin): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.is_activated = False <NEW_LINE> <DEDENT> def build_journal(self, ofx_file, config): <NEW_LINE> <INDENT> tree = OFXTree() <NEW_LINE> tree.parse(ofx_file) <NEW_LINE> ofx_obj = tree.convert() <NEW_LINE> stop_words = config.get('stop_words', []) <NEW_LINE> balance_assertions = [] <NEW_LINE> transactions = [] <NEW_LINE> for statement in ofx_obj.statements: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> routing = statement.account.bankid <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> routing = 'na' <NEW_LINE> <DEDENT> account = statement.account.acctid <NEW_LINE> currency = CURRENCY_LOOKUP[statement.currency] <NEW_LINE> balance = statement.ledgerbal.balamt <NEW_LINE> stmnt_date = strftime(statement.ledgerbal.dtasof, '%Y-%m-%d') <NEW_LINE> a_assert = Posting( account=config['from'], amount=balance, currency=currency, assertion=True ) <NEW_LINE> t_assert = Transaction( date=stmnt_date, payee='Balance for {}-{}'.format(ofx_obj.sonrs.org, account), postings=[a_assert] ) <NEW_LINE> balance_assertions.append(t_assert) <NEW_LINE> for transaction in statement.transactions: <NEW_LINE> <INDENT> meta = [] <NEW_LINE> payee = transaction.name <NEW_LINE> hash_payee = payee <NEW_LINE> for word in stop_words: <NEW_LINE> <INDENT> payee = payee.replace(word, '') <NEW_LINE> <DEDENT> amount = transaction.trnamt <NEW_LINE> trn_date = strftime(transaction.dtposted, '%Y-%m-%d') <NEW_LINE> if transaction.refnum: <NEW_LINE> <INDENT> trn_id = transaction.refnum <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> trn_id = transaction.fitid <NEW_LINE> <DEDENT> check = transaction.checknum <NEW_LINE> if check: <NEW_LINE> <INDENT> meta.append(('check', transaction.checknum)) <NEW_LINE> <DEDENT> check_hash = trn_id + trn_date + hash_payee + str(amount) <NEW_LINE> hash_obj = hashlib.md5(check_hash.encode()) <NEW_LINE> uuid = hash_obj.hexdigest() <NEW_LINE> meta.append(('UUID', uuid)) <NEW_LINE> meta.append(('Imported', strftime(now(), '%Y-%m-%d'))) <NEW_LINE> a_tran = Posting( account=config['from'], amount=amount, currency=currency ) <NEW_LINE> t_tran = Transaction( date=trn_date, payee=payee, postings=[a_tran], metadata=meta, account=account, uuid=uuid ) <NEW_LINE> transactions.append(t_tran) <NEW_LINE> <DEDENT> <DEDENT> return balance_assertions, transactions | OFX file parsing. | 62598fbe2c8b7c6e89bd39b6 |
class SystemDCache(object): <NEW_LINE> <INDENT> _cache = None <NEW_LINE> @staticmethod <NEW_LINE> def get(): <NEW_LINE> <INDENT> if SystemDCache._cache is None: <NEW_LINE> <INDENT> SystemDCache._cache = [] <NEW_LINE> out = check_run_cmd("systemctl", "list-units", "-q", "--full", "--type=service", "--system", "--no-pager", "--no-legend", "--no-block") <NEW_LINE> for line in out.splitlines(): <NEW_LINE> <INDENT> fields = line.split(None, 5) <NEW_LINE> if "ssh" not in fields[0] or "tunnel" not in fields[0]: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> SystemDCache._cache.append(fields[0]) <NEW_LINE> <DEDENT> out = check_run_cmd("systemctl", "list-unit-files", "-q", "--full", "--type=service", "--system", "--no-pager", "--no-legend", "--no-block") <NEW_LINE> for line in out.splitlines(): <NEW_LINE> <INDENT> fields = line.split(None, 5) <NEW_LINE> if "ssh" not in fields[0] or "tunnel" not in fields[0]: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> SystemDCache._cache.append(fields[0]) <NEW_LINE> <DEDENT> <DEDENT> return SystemDCache._cache | Global cache to list SystemD units named ssh tunnel | 62598fbeaad79263cf42e9cb |
class Course(db.Model): <NEW_LINE> <INDENT> __tablename__ = 'courses' <NEW_LINE> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> course_name = db.Column(db.Unicode(32),unique=True,index=True) <NEW_LINE> course_credit = db.Column(db.Integer) <NEW_LINE> course_college = db.Column(db.Unicode(32)) | 课程表,存储所有课程信息 | 62598fbe4527f215b58ea0c4 |
class EventList(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._evtlist = list() <NEW_LINE> <DEDENT> def append(self, object): <NEW_LINE> <INDENT> self._evtlist.append(object) <NEW_LINE> <DEDENT> def getEventListToRawData(self): <NEW_LINE> <INDENT> out = [] <NEW_LINE> for day in self._evtlist: <NEW_LINE> <INDENT> out.append(day.getOutputData()) <NEW_LINE> <DEDENT> return out <NEW_LINE> <DEDENT> def getMonthFirstDay(self): <NEW_LINE> <INDENT> d = self._evtlist[0].getDate() <NEW_LINE> from datetime import datetime <NEW_LINE> return datetime(d.year, d.month, 1) <NEW_LINE> <DEDENT> def insertHolidays(self): <NEW_LINE> <INDENT> from datetime import datetime <NEW_LINE> import calendar <NEW_LINE> d = self.getMonthFirstDay() <NEW_LINE> lastday = calendar.monthrange(d.year, d.month)[1] <NEW_LINE> days = [] <NEW_LINE> for data in self._evtlist: <NEW_LINE> <INDENT> days.append(data.getDate()) <NEW_LINE> <DEDENT> sorted(days) <NEW_LINE> for day in range(1, lastday): <NEW_LINE> <INDENT> dd = datetime(d.year, d.month, day) <NEW_LINE> if dd.weekday() == 3 and not dd.day in days: <NEW_LINE> <INDENT> self.append(Day(dd, True)) <NEW_LINE> <DEDENT> <DEDENT> self._evtlist = sorted(self._evtlist, key=lambda c: c.getDate()) | イベントリストを格納するリストオブジェクト | 62598fbea8370b77170f05d6 |
class HTTPException(DiscodoException): <NEW_LINE> <INDENT> def __init__(self, status: int, data=None) -> None: <NEW_LINE> <INDENT> if not data: <NEW_LINE> <INDENT> data = {} <NEW_LINE> <DEDENT> self.status = data.get("status", status) <NEW_LINE> self.description = data.get( "description", responses.get(status, "Unknown Status Code") ) <NEW_LINE> self.message = data.get("message", "") <NEW_LINE> super().__init__(f"{self.status} {self.description}: {self.message}") | Exception that is thrown when HTTP operation failed.
:var int status: HTTP status code
:var str description: Description of the HTTP status code
:var str message: Server message with this request | 62598fbe5fc7496912d48376 |
class PrivateDnsZoneConfig(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'id': {'readonly': True}, 'type': {'readonly': True}, 'etag': {'readonly': True}, 'provisioning_state': {'readonly': True}, 'record_sets': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'private_dns_zone_id': {'key': 'properties.privateDnsZoneId', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'record_sets': {'key': 'properties.recordSets', 'type': '[RecordSet]'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(PrivateDnsZoneConfig, self).__init__(**kwargs) <NEW_LINE> self.name = kwargs.get('name', None) <NEW_LINE> self.id = None <NEW_LINE> self.type = None <NEW_LINE> self.etag = None <NEW_LINE> self.private_dns_zone_id = kwargs.get('private_dns_zone_id', None) <NEW_LINE> self.provisioning_state = None <NEW_LINE> self.record_sets = None | PrivateDnsZoneConfig resource.
Variables are only populated by the server, and will be ignored when sending a request.
:param name: Name of the resource that is unique within a resource group. This name can be used
to access the resource.
:type name: str
:ivar id: The id of the privateDnsZoneConfig.
:vartype id: str
:ivar type: Type of resource. Will be specified as private dns zone configurations.
:vartype type: str
:ivar etag: A unique read-only string that changes whenever the resource is updated.
:vartype etag: str
:param private_dns_zone_id: The resource id of the private dns zone.
:type private_dns_zone_id: str
:ivar provisioning_state: The provisioning state of the private dns zone group resource.
Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2021_02_01.models.ProvisioningState
:ivar record_sets: A collection of information regarding a recordSet, holding information to
identify private resources.
:vartype record_sets: list[~azure.mgmt.network.v2021_02_01.models.RecordSet] | 62598fbef9cc0f698b1c53ca |
class SupportedRuntimePlatform(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): <NEW_LINE> <INDENT> JAVA = "Java" <NEW_LINE> _NET_CORE = ".NET Core" | The platform of this runtime version (possible values: "Java" or ".NET").
| 62598fbe99fddb7c1ca62ee7 |
class Mailwrapper(Gmail): <NEW_LINE> <INDENT> def __init__(self, gm): <NEW_LINE> <INDENT> self.attachments = gm.attachments <NEW_LINE> self.body = gm.body <NEW_LINE> self.to = gm.to <NEW_LINE> self.cc = gm.cc <NEW_LINE> self.flags = gm.flags <NEW_LINE> self.headers = gm.headers <NEW_LINE> self.message_id = gm.message_id <NEW_LINE> self.sent_at = gm.sent_at <NEW_LINE> self.subject = gm.subject <NEW_LINE> self.thread = gm.thread <NEW_LINE> self.thread_id = gm.thread_id <NEW_LINE> self.to_dict = {'attachments': gm.attachments, 'body': gm.body, 'to': gm.to, 'cc': gm.cc, 'flags': gm.flags, 'headers': gm.headers, 'message_id': gm.message_id, 'sent_at': str(gm.sent_at), 'subject': gm.subject, 'thread': gm.thread, 'thread_id': gm.thread_id} | Wrapper per selezionare i soli campi d'interesse dalle mail e salvarle in
un file json | 62598fbedc8b845886d537b1 |
class AtRule(object): <NEW_LINE> <INDENT> def __init__(self, at_keyword, head, body, line, column): <NEW_LINE> <INDENT> self.at_keyword = at_keyword <NEW_LINE> self.head = TokenList(head) <NEW_LINE> self.body = TokenList(body) if body is not None else body <NEW_LINE> self.line = line <NEW_LINE> self.column = column <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return ('<{0.__class__.__name__} {0.line}:{0.column} {0.at_keyword}>' .format(self)) | An unparsed at-rule.
.. attribute:: at_keyword
The normalized (lower-case) at-keyword as a string. Eg: ``'@page'``
.. attribute:: head
The part of the at-rule between the at-keyword and the ``{``
marking the body, or the ``;`` marking the end of an at-rule without
a body. A :class:`~.token_data.TokenList`.
.. attribute:: body
The content of the body between ``{`` and ``}`` as a
:class:`~.token_data.TokenList`, or ``None`` if there is no body
(ie. if the rule ends with ``;``).
The head was validated against the core grammar but **not** the body,
as the body might contain declarations. In case of an error in a
declaration, parsing should continue from the next declaration.
The whole rule should not be ignored as it would be for an error
in the head.
These at-rules are expected to be parsed further before reaching
the user API. | 62598fbe7c178a314d78d696 |
class ShowHighlight(Mbase_subcmd.DebuggerSubcommand): <NEW_LINE> <INDENT> short_help = 'Show if we use terminal highlight' <NEW_LINE> def run(self, args): <NEW_LINE> <INDENT> val = self.settings['highlight'] <NEW_LINE> if 'plain' == val: <NEW_LINE> <INDENT> mess = 'output set to not use terminal escape sequences' <NEW_LINE> <DEDENT> elif 'light' == val: <NEW_LINE> <INDENT> mess = ('output set for terminal with escape sequences ' 'for a light background') <NEW_LINE> <DEDENT> elif 'dark' == val: <NEW_LINE> <INDENT> mess = ('output set for terminal with escape sequences ' 'for a dark background') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.errmsg('Internal error: incorrect highlight setting %s' % val) <NEW_LINE> return <NEW_LINE> <DEDENT> self.msg(mess) <NEW_LINE> return <NEW_LINE> <DEDENT> pass | **show highlight**
Show whether we use terminal highlighting.
See also:
--------
`set highlight` | 62598fbe63d6d428bbee29a8 |
class MockedUser: <NEW_LINE> <INDENT> def __init__(self, username): <NEW_LINE> <INDENT> self.username = username <NEW_LINE> self.top_artists = [] | mocks query_user reponse | 62598fbe7047854f4633f5cb |
class Transformations(object): <NEW_LINE> <INDENT> def mean_at_zero(self, arr): <NEW_LINE> <INDENT> return np.array([i - np.mean(a) for i in arr]) <NEW_LINE> <DEDENT> def norm_to_min_zero(self, arr): <NEW_LINE> <INDENT> return np.array([i / max(a) for i in arr]) <NEW_LINE> <DEDENT> def norm_to_absolute_min_zero(self, arr): <NEW_LINE> <INDENT> return np.array([(i-min(arr))/(max(arr)-min(arr)) for i in arr]) <NEW_LINE> <DEDENT> def norm_to_neg_pos(self, arr): <NEW_LINE> <INDENT> return np.array([(i-mean(arr))/(max(arr)-mean(arr)) for i in arr]) <NEW_LINE> <DEDENT> def norm_by_std(self, arr): <NEW_LINE> <INDENT> return np.array([(i-mean(arr))/std(arr) for i in arr]) | since these transformations are all related, we'll nest them all under a feature norm class | 62598fbe0fa83653e46f50db |
class AsciiToImage(object): <NEW_LINE> <INDENT> def __init__(self, **kw): <NEW_LINE> <INDENT> self._font = kw.get('font', pkg_resources.resource_filename( 'mediagoblin.media_types.ascii', os.path.join('fonts', 'Inconsolata.otf'))) <NEW_LINE> self._font_size = kw.get('font_size', 11) <NEW_LINE> self._if = ImageFont.truetype( self._font, self._font_size, encoding='unic') <NEW_LINE> _log.info('Font set to {0}, size {1}'.format( self._font, self._font_size)) <NEW_LINE> self._if_dims = self._if.getsize('.') <NEW_LINE> <DEDENT> def convert(self, text, destination): <NEW_LINE> <INDENT> im = self._create_image(text) <NEW_LINE> if im.save(destination): <NEW_LINE> <INDENT> _log.info('Saved image in {0}'.format( destination)) <NEW_LINE> <DEDENT> <DEDENT> def _create_image(self, text): <NEW_LINE> <INDENT> _log.debug('Drawing image') <NEW_LINE> text = text.decode('utf-8') <NEW_LINE> lines = text.split('\n') <NEW_LINE> line_lengths = [len(i) for i in lines] <NEW_LINE> im_dims = ( max(line_lengths) * self._if_dims[0], len(line_lengths) * self._if_dims[1]) <NEW_LINE> _log.info('Destination image dimensions will be {0}'.format( im_dims)) <NEW_LINE> im = Image.new( 'RGBA', im_dims, (255, 255, 255, 0)) <NEW_LINE> draw = ImageDraw.Draw(im) <NEW_LINE> char_pos = [0, 0] <NEW_LINE> for line in lines: <NEW_LINE> <INDENT> line_length = len(line) <NEW_LINE> _log.debug('Writing line at {0}'.format(char_pos)) <NEW_LINE> for _pos in range(0, line_length): <NEW_LINE> <INDENT> char = line[_pos] <NEW_LINE> px_pos = self._px_pos(char_pos) <NEW_LINE> _log.debug('Writing character "{0}" at {1} (px pos {2})'.format( char.encode('ascii', 'replace'), char_pos, px_pos)) <NEW_LINE> draw.text( px_pos, char, font=self._if, fill=(0, 0, 0, 255)) <NEW_LINE> char_pos[0] += 1 <NEW_LINE> <DEDENT> char_pos[0] = 0 <NEW_LINE> char_pos[1] += 1 <NEW_LINE> <DEDENT> return im <NEW_LINE> <DEDENT> def _px_pos(self, char_pos): <NEW_LINE> <INDENT> px_pos = [0, 0] <NEW_LINE> for index, val in zip(range(0, len(char_pos)), char_pos): <NEW_LINE> <INDENT> px_pos[index] = char_pos[index] * self._if_dims[index] <NEW_LINE> <DEDENT> return px_pos | Converter of ASCII art into image files, preserving whitespace
kwargs:
- font: Path to font file
default: fonts/Inconsolata.otf
- font_size: Font size, ``int``
default: 11 | 62598fbe26068e7796d4cb53 |
class Meta2Rebuild(SingleServiceCommandMixin, XcuteRdirCommand): <NEW_LINE> <INDENT> JOB_CLASS = Meta2RebuildJob <NEW_LINE> def get_parser(self, prog_name): <NEW_LINE> <INDENT> parser = super(Meta2Rebuild, self).get_parser(prog_name) <NEW_LINE> SingleServiceCommandMixin.patch_parser(self, parser) <NEW_LINE> parser.add_argument( '--bases-per-second', type=int, help='Max bases per second. ' '(default=%d)' % self.JOB_CLASS.DEFAULT_TASKS_PER_SECOND) <NEW_LINE> return parser <NEW_LINE> <DEDENT> def get_job_config(self, parsed_args): <NEW_LINE> <INDENT> job_params = { 'service_id': parsed_args.service, 'rdir_fetch_limit': parsed_args.rdir_fetch_limit, 'rdir_timeout': parsed_args.rdir_timeout, } <NEW_LINE> return { 'tasks_per_second': parsed_args.bases_per_second, 'params': job_params } | [BETA] Rebuild bases that were on the specified service. | 62598fbe099cdd3c636754de |
@admin.register(models.FBARegion) <NEW_LINE> class FBARegionAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> fields = [ "name", "default_country", "postage_price", "max_weight", "max_size", "fulfillment_unit", "currency", "auto_close", "warehouse_required", ] <NEW_LINE> list_display = [ "name", "default_country", "postage_price", "max_weight", "max_size", "fulfillment_unit", "currency", "auto_close", "warehouse_required", ] <NEW_LINE> list_editable = [ "default_country", "postage_price", "max_weight", "max_size", "fulfillment_unit", "currency", "auto_close", "warehouse_required", ] | Model admin for the FBARegion model. | 62598fbeaad79263cf42e9cc |
class ParserNode: <NEW_LINE> <INDENT> def __init__(self, grammar, begin, prior, visual): <NEW_LINE> <INDENT> self.grammar = grammar <NEW_LINE> self.begin = begin <NEW_LINE> self.prior = prior <NEW_LINE> self.visual = visual <NEW_LINE> <DEDENT> def debug_log(self, out, indent, data): <NEW_LINE> <INDENT> out( "%sParserNode %26s prior %4s, b%4d, v%4d %s" % ( indent, self.grammar.get("name", "None"), self.prior, self.begin, self.visual, repr(data[self.begin : self.begin + 15])[1:-1], ) ) | A parser node represents a span of grammar. i.e. from this point to that
point is HTML. Another parser node would represent the next segment, of
grammar (maybe JavaScript, CSS, comment, or quoted string for example. | 62598fbe796e427e5384e98d |
class WindowState: <NEW_LINE> <INDENT> def __init__(self, window_state): <NEW_LINE> <INDENT> self.x = window_state[3] <NEW_LINE> alerts_data = window_state[1] <NEW_LINE> if alerts_data is not None: <NEW_LINE> <INDENT> alerts = alerts_data[1] <NEW_LINE> self.alerts = [ Alert(alert_data) for alert_data in alerts ] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.alerts = [] <NEW_LINE> <DEDENT> accounts_data = window_state[2] <NEW_LINE> accounts_list = accounts_data[6] <NEW_LINE> self.accounts = {} <NEW_LINE> for account_data in accounts_list: <NEW_LINE> <INDENT> account = Account(account_data) <NEW_LINE> self.accounts[account.email] = account | Represents the window.STATE variable in the Google Alerts page.
This variable is a Javascript array containing all information regarding
every alert, information about the logged in user account and some other
information as well. | 62598fbe7cff6e4e811b5c1a |
class RsaModel(ModelBase): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(RsaModel, self).__init__() <NEW_LINE> self.model_param = RsaParam() <NEW_LINE> <DEDENT> def fit(self, data_inst): <NEW_LINE> <INDENT> LOGGER.info("RsaModel start fit...") <NEW_LINE> LOGGER.debug("data_inst={}, count={}".format(data_inst, data_inst.count())) <NEW_LINE> key_pair = {"d": self.model_param.rsa_key_d, "n": self.model_param.rsa_key_n} <NEW_LINE> data_processed = self.encrypt_data_using_rsa(data_inst, key_pair) <NEW_LINE> return self.save_data(data_processed) <NEW_LINE> <DEDENT> def save_data(self, data_inst): <NEW_LINE> <INDENT> LOGGER.debug("save data: data_inst={}, count={}".format(data_inst, data_inst.count())) <NEW_LINE> persistent_table = data_inst.save_as(namespace=self.model_param.save_out_table_namespace, name=self.model_param.save_out_table_name) <NEW_LINE> LOGGER.info("save data to namespace={}, name={}".format(persistent_table._namespace, persistent_table._name)) <NEW_LINE> session.save_data_table_meta( {'schema': data_inst.schema, 'header': data_inst.schema.get('header', [])}, data_table_namespace=persistent_table._namespace, data_table_name=persistent_table._name) <NEW_LINE> version_log = "[AUTO] save data at %s." % datetime.datetime.now() <NEW_LINE> version_control.save_version(name=persistent_table._name, namespace=persistent_table._namespace, version_log=version_log) <NEW_LINE> return persistent_table <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def hash(value): <NEW_LINE> <INDENT> return hashlib.sha256(bytes(str(value), encoding='utf-8')).hexdigest() <NEW_LINE> <DEDENT> def encrypt_data_using_rsa(self, data_inst, key_pair): <NEW_LINE> <INDENT> LOGGER.info("encrypt data using rsa: {}".format(str(key_pair))) <NEW_LINE> data_processed_pair = data_inst.map( lambda k, v: ( RsaModel.hash(gmpy_math.powmod(int(RsaModel.hash(k), 16), key_pair["d"], key_pair["n"])), k) ) <NEW_LINE> return data_processed_pair | encrypt data using RSA
Parameters
----------
RsaParam : object, self-define id_process parameters,
define in federatedml.param.rsa_param | 62598fbed7e4931a7ef3c28b |
class BatchProcessingCommand(BaseCommand): <NEW_LINE> <INDENT> def add_arguments(self, parser): <NEW_LINE> <INDENT> parser.add_argument('fields', nargs='+', help="A sequence of " "model-field name pairs in the form 'Model.field'") <NEW_LINE> <DEDENT> def precondition_check(self, options, model, field): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def preprocess(self, options): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def process(self, options, instance, model_name, field_name): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def handle(self, *args, **options): <NEW_LINE> <INDENT> self.preprocess(options) <NEW_LINE> for model_field_pair in options['fields']: <NEW_LINE> <INDENT> components = model_field_pair.split('.') <NEW_LINE> if len(components) != 2: <NEW_LINE> <INDENT> message = "failed to parse model-field pair '{0}'" <NEW_LINE> raise CommandError(message.format(model_field_pair)) <NEW_LINE> <DEDENT> model_name, field_name = components <NEW_LINE> try: <NEW_LINE> <INDENT> models = ContentType.objects.filter(app_label='pcari') <NEW_LINE> model = models.get(model=model_name.lower()).model_class() <NEW_LINE> field = model._meta.get_field(field_name) <NEW_LINE> self.precondition_check(options, model, field) <NEW_LINE> <DEDENT> except Exception as exc: <NEW_LINE> <INDENT> message = 'model or field failed precondition check: {0}' <NEW_LINE> raise CommandError(message.format(unicode(exc))) <NEW_LINE> <DEDENT> for instance in model.objects.all(): <NEW_LINE> <INDENT> self.process(options, instance, model_name, field_name) <NEW_LINE> <DEDENT> <DEDENT> self.postprocess(options) <NEW_LINE> <DEDENT> def postprocess(self, options): <NEW_LINE> <INDENT> pass | A ``BatchProcessingCommand`` provides utilities for manipulating a sequence
of fields, which would be useful for cleaning or exporting data. | 62598fbeff9c53063f51a846 |
class Test: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> <DEDENT> def test_func(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def next_test_func(self): <NEW_LINE> <INDENT> pass | class doc string | 62598fbe3317a56b869be64b |
class Operator(object): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def display(cls): <NEW_LINE> <INDENT> game.set_board('lower') <NEW_LINE> game.grid.draw_board() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def spawn(cls): <NEW_LINE> <INDENT> game.set_board('upper') <NEW_LINE> game.grid.draw_board() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def new_line(cls): <NEW_LINE> <INDENT> print <NEW_LINE> <DEDENT> def signal_parser(self, signal): <NEW_LINE> <INDENT> if signal == '?s' or signal == '?n': <NEW_LINE> <INDENT> signals = [signal] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> signals = [s for s in signal if s != ' '] <NEW_LINE> <DEDENT> for sig in signals: <NEW_LINE> <INDENT> commands = {'p' : self.display, 'q' : sys.exit, 'g' : game.grid.given, 'c' : game.grid.clear, '?s': game.grid.show_score, '?n': game.grid.show_clear_lines, 's' : game.grid.step, 't' : game.active_tet.print_tet, ')' : game.active_tet.rotate_clockwise, '(' : game.active_tet.rotate_counter_clockwise, ';' : self.new_line, 'P' : self.spawn, '<' : game.move_tet_west, '>' : game.move_tet_east, 'v' : game.move_tet_south, 'V' : game.hard_drop} <NEW_LINE> if sig.isupper() and not (sig == 'V' or sig == 'P'): <NEW_LINE> <INDENT> game.active_tet = game.set_active_tet(sig) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> commands[sig]() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def receive_signal(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> received = raw_input() <NEW_LINE> self.signal_parser(received) | Handles receiving, parsing, and triaging incoming signals | 62598fbee1aae11d1e7ce921 |
class permutation_dict(dict): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> self._phook_setitem_ = lambda key, val: val <NEW_LINE> self._phook_getitem_ = lambda key, val: val <NEW_LINE> <DEDENT> def __setitem__(self, arg, val): <NEW_LINE> <INDENT> if isinstance(arg, tuple): <NEW_LINE> <INDENT> arg = reprsort(list(arg)) <NEW_LINE> arg = tuple(arg) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> arg = tuple([arg]) <NEW_LINE> <DEDENT> val = self._phook_setitem_(arg, val) <NEW_LINE> return super().__setitem__(arg, val) <NEW_LINE> <DEDENT> def __getitem__(self, arg): <NEW_LINE> <INDENT> if isinstance(arg, tuple): <NEW_LINE> <INDENT> arg = reprsort(list(arg)) <NEW_LINE> arg = tuple(arg) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> arg = tuple([arg]) <NEW_LINE> <DEDENT> return self._phook_getitem_(arg, super().__getitem__(arg)) | A modification of dict.
Tuple keys are considered equal, if the first can be obtained by permuting the second.
For example (1, 3, 2, 0) == (0, 1, 2, 3)
Also, hooks for __getitem__ and __setitem__ are provided. | 62598fbecc40096d6161a2d5 |
class CharacterStatistics(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=255) <NEW_LINE> damage = models.IntegerField() <NEW_LINE> icon = models.CharField(max_length=255) <NEW_LINE> rarity = models.CharField(max_length=20) | To be changed | 62598fbe5166f23b2e2435d7 |
class UNet(nn.Module): <NEW_LINE> <INDENT> def __init__(self, num_classes, num_filters=32, pretrained=True): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.resnet = resnet50(pretrained=pretrained) <NEW_LINE> self.enc0 = nn.Sequential(self.resnet.conv1, self.resnet.bn1, self.resnet.relu, self.resnet.maxpool) <NEW_LINE> self.enc1 = self.resnet.layer1 <NEW_LINE> self.enc2 = self.resnet.layer2 <NEW_LINE> self.enc3 = self.resnet.layer3 <NEW_LINE> self.enc4 = self.resnet.layer4 <NEW_LINE> self.center = DecoderBlock(2048, num_filters * 8) <NEW_LINE> self.dec0 = DecoderBlock(2048 + num_filters * 8, num_filters * 8) <NEW_LINE> self.dec1 = DecoderBlock(1024 + num_filters * 8, num_filters * 8) <NEW_LINE> self.dec2 = DecoderBlock(512 + num_filters * 8, num_filters * 2) <NEW_LINE> self.dec3 = DecoderBlock(256 + num_filters * 2, num_filters * 2 * 2) <NEW_LINE> self.dec4 = DecoderBlock(num_filters * 2 * 2, num_filters) <NEW_LINE> self.dec5 = ConvRelu(num_filters, num_filters) <NEW_LINE> self.final = nn.Conv2d(num_filters, num_classes, kernel_size=1) <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> enc0 = self.enc0(x) <NEW_LINE> enc1 = self.enc1(enc0) <NEW_LINE> enc2 = self.enc2(enc1) <NEW_LINE> enc3 = self.enc3(enc2) <NEW_LINE> enc4 = self.enc4(enc3) <NEW_LINE> center = self.center(nn.functional.max_pool2d(enc4, kernel_size=2, stride=2)) <NEW_LINE> dec0 = self.dec0(torch.cat([enc4, center], dim=1)) <NEW_LINE> dec1 = self.dec1(torch.cat([enc3, dec0], dim=1)) <NEW_LINE> dec2 = self.dec2(torch.cat([enc2, dec1], dim=1)) <NEW_LINE> dec3 = self.dec3(torch.cat([enc1, dec2], dim=1)) <NEW_LINE> dec4 = self.dec4(dec3) <NEW_LINE> dec5 = self.dec5(dec4) <NEW_LINE> return self.final(dec5) | The "U-Net" architecture for semantic segmentation, adapted by changing the encoder to a ResNet feature extractor.
Also known as AlbuNet due to its inventor Alexander Buslaev. | 62598fbea8370b77170f05d9 |
class TaskStatus(object): <NEW_LINE> <INDENT> NONE = SimpleString("None") <NEW_LINE> READY = SimpleString("Ready") <NEW_LINE> QUEUE = SimpleString("Queue") <NEW_LINE> RUNNING = SimpleString("Running") <NEW_LINE> STOPPING = SimpleString("Stopping") <NEW_LINE> STOPPED = SimpleString("Stopped") <NEW_LINE> INVALID = SimpleString("Invalid") <NEW_LINE> FAIL = SimpleString("Fail") <NEW_LINE> ERROR = SimpleString("Fail") <NEW_LINE> SUCCESS = SimpleString("Success") <NEW_LINE> @staticmethod <NEW_LINE> def is_success(status): <NEW_LINE> <INDENT> if status is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return TaskStatus.SUCCESS.lower() == status.lower() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def is_running(status): <NEW_LINE> <INDENT> if status is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return TaskStatus.RUNNING.lower() == status.lower() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def is_fail(status): <NEW_LINE> <INDENT> if status is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return TaskStatus.FAIL.lower() == status.lower() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def is_ready(status): <NEW_LINE> <INDENT> if status is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if status.lower() == TaskStatus.READY.lower(): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def is_none(status): <NEW_LINE> <INDENT> if status is None: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if status.lower() == TaskStatus.NONE.lower(): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def parse(cls, s): <NEW_LINE> <INDENT> if isinstance(s, TaskStatus): <NEW_LINE> <INDENT> return s <NEW_LINE> <DEDENT> if StringTool.is_string(s) is False: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> for key, value in cls.__dict__.items(): <NEW_LINE> <INDENT> if StringTool.is_string(value) is False: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if key.startswith("_") is True: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if isinstance(value, SimpleString) is False: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if value.lower() == s.lower(): <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> <DEDENT> return None <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def compare(cls, s1, s2): <NEW_LINE> <INDENT> con = {0: [cls.NONE], 1: [cls.READY], 2: [cls.QUEUE], 3: [cls.RUNNING], 4: [cls.STOPPING], 5: [cls.STOPPED], 6: [cls.INVALID, cls.FAIL], 7: [cls.SUCCESS]} <NEW_LINE> sk1 = sk2 = -1 <NEW_LINE> for k, ss in con.items(): <NEW_LINE> <INDENT> if sk1 == -1: <NEW_LINE> <INDENT> if s1 in ss: <NEW_LINE> <INDENT> sk1 = k <NEW_LINE> <DEDENT> <DEDENT> if sk2 == -1: <NEW_LINE> <INDENT> if s2 in ss: <NEW_LINE> <INDENT> sk2 = k <NEW_LINE> <DEDENT> <DEDENT> if sk1 != -1 and sk2 != -1: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> if sk1 == -1 or sk2 == -1: <NEW_LINE> <INDENT> return -2 <NEW_LINE> <DEDENT> if sk1 > sk2: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> elif sk2 > sk1: <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> return 0 | add in version 0.1.19 | 62598fbedc8b845886d537b3 |
class Int(SimpleSpace): <NEW_LINE> <INDENT> def __init__(self, lower, upper, default=None): <NEW_LINE> <INDENT> self.lower = lower <NEW_LINE> self.upper = upper <NEW_LINE> self._default = default <NEW_LINE> <DEDENT> def get_hp(self, name): <NEW_LINE> <INDENT> return CSH.UniformIntegerHyperparameter(name=name, lower=self.lower, upper=self.upper, default_value=self._default) | Search space for numeric hyperparameter that takes integer values.
Parameters
----------
lower : int
The lower bound of the search space (minimum possible value of hyperparameter)
upper : int
The upper bound of the search space (maximum possible value of hyperparameter)
default : int (optional)
Default value tried first during hyperparameter optimization
Examples
--------
>>> range = ag.space.Int(0, 100) | 62598fbe4a966d76dd5ef0cc |
class IdentityCache(Cache): <NEW_LINE> <INDENT> def __init__(self, django_session): <NEW_LINE> <INDENT> self._db = DjangoSessionCacheAdapter(django_session, '_identities') <NEW_LINE> self._sync = True <NEW_LINE> <DEDENT> def get(self, name_id, entity_id, *args, **kwargs): <NEW_LINE> <INDENT> info = super(IdentityCache, self).get(name_id, entity_id, *args, **kwargs) <NEW_LINE> try: <NEW_LINE> <INDENT> name_id = info['name_id'] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> info = dict(info) <NEW_LINE> info['name_id'] = decode(name_id) <NEW_LINE> <DEDENT> return info <NEW_LINE> <DEDENT> def set(self, name_id, entity_id, info, *args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> name_id = info['name_id'] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> info = dict(info) <NEW_LINE> info['name_id'] = code(name_id) <NEW_LINE> <DEDENT> return super(IdentityCache, self).set(name_id, entity_id, info, *args, **kwargs) | Handles information about the users that have been succesfully
logged in.
This information is useful because when the user logs out we must
know where does he come from in order to notify such IdP/AA.
The current implementation stores this information in the Django session. | 62598fbe71ff763f4b5e7974 |
class ExecutorDriverThread(ExceptionalThread): <NEW_LINE> <INDENT> def __init__(self, driver): <NEW_LINE> <INDENT> self._driver = driver <NEW_LINE> super(ExecutorDriverThread, self).__init__() <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> self._driver.run() | Start the executor and wait until it is stopped.
This is decoupled from the main thread, because only the main thread can receive signals
and we would miss those when blocking in the driver run method. | 62598fbe63b5f9789fe8536a |
class MiningJob: <NEW_LINE> <INDENT> def __init__(self, previous_block: Block, pending_txs: List[Transaction]): <NEW_LINE> <INDENT> self.previous_block = previous_block <NEW_LINE> self.pending_txs = pending_txs <NEW_LINE> data = { 'txs': [dataclasses.asdict(_) for _ in self.pending_txs], } <NEW_LINE> self.block = Block( index=self.previous_block.index + 1, timestamp=int(time.time()), data=data, previous_hash=self.previous_block.hash, nonce=self.previous_block.nonce + 1, ) <NEW_LINE> self.is_mined = False <NEW_LINE> <DEDENT> def validate_difficulty(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.block.validate_difficulty() <NEW_LINE> return True <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def mine(self): <NEW_LINE> <INDENT> while not self.validate_difficulty(): <NEW_LINE> <INDENT> self.block.nonce += 1 <NEW_LINE> <DEDENT> return self.block | CPU挖矿的一个工作 | 62598fbe0fa83653e46f50de |
class OperationNameNode(Node): <NEW_LINE> <INDENT> def __init__(self, ident): <NEW_LINE> <INDENT> self.ident = ident | A Node which represents the name of an operation in the AST. | 62598fbe50812a4eaa620ce7 |
class TeachingUsePropertyCode(models.Model): <NEW_LINE> <INDENT> code = models.CharField(primary_key=True, max_length=2, verbose_name=u"代码") <NEW_LINE> name = models.CharField(unique=True, max_length=32, verbose_name=u"名称") <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.name | 教学使用性质 | 62598fbe44b2445a339b6a73 |
class LocationComparator: <NEW_LINE> <INDENT> def __init__(self, posting_location, candidate_locations): <NEW_LINE> <INDENT> self.api_key = "AIzaSyDbkAJndXb-HX6cj4LYYaB8Nm98DmI3D7Y" <NEW_LINE> self.posting_location = posting_location <NEW_LINE> self.candidate_locations = [] <NEW_LINE> self.max_distance = 100000 <NEW_LINE> self.min_distance = 0 <NEW_LINE> for item in candidate_locations: <NEW_LINE> <INDENT> self.candidate_locations.append(item) <NEW_LINE> <DEDENT> <DEDENT> def testPrint(self): <NEW_LINE> <INDENT> print("{} | {}".format(self.posting_location, self.candidate_locations)) <NEW_LINE> <DEDENT> def changePostingLocation(self, location): <NEW_LINE> <INDENT> self.posting_location = location <NEW_LINE> <DEDENT> def addCandidateLocation(self, location): <NEW_LINE> <INDENT> if location not in self.candidate_locations: <NEW_LINE> <INDENT> self.candidate_locations.append(location) <NEW_LINE> <DEDENT> <DEDENT> def getShortestDistance(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> gmaps = googlemaps.Client(key=self.api_key) <NEW_LINE> origin = self.posting_location.getLatLon() <NEW_LINE> destinations = [] <NEW_LINE> for loc in self.candidate_locations: <NEW_LINE> <INDENT> destinations.append(loc.getLatLon()) <NEW_LINE> <DEDENT> distmatx = gmaps.distance_matrix( origin, destinations ) <NEW_LINE> rows = distmatx['rows'] <NEW_LINE> shortest_row = rows[0]['elements'][0]['distance']['value'] <NEW_LINE> if len(rows[0]['elements']) > 1: <NEW_LINE> <INDENT> for item in rows: <NEW_LINE> <INDENT> for value in item.values(): <NEW_LINE> <INDENT> for val in value: <NEW_LINE> <INDENT> if val['distance']['value'] < shortest_row: <NEW_LINE> <INDENT> shortest_row = val['distance']['value'] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> if shortest_row > self.max_distance: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> elif type(shortest_row) is None: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if shortest_row is not None: <NEW_LINE> <INDENT> return shortest_row/self.max_distance <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except AssertionError as e: <NEW_LINE> <INDENT> raise AssertionError('Locations need to be location object') <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logger = logging.getLogger(__name__) <NEW_LINE> logger.error(e) | This class uses the google maps api to compare the different locations offered by the user against the location
specified for the posting by the employer | 62598fbed486a94d0ba2c1ca |
class CannotRedefineSnipIDError(SnippetError): <NEW_LINE> <INDENT> def __init__(self, snippet): <NEW_LINE> <INDENT> msg = ('Attempted to overwrite snip_id {} for snippet {} ' '(has this snippet already been committed?)' ).format(snippet.snip_id, str(snippet)) <NEW_LINE> super(CannotRedefineSnipIDError, self).__init__(snippet, msg=msg) <NEW_LINE> self.snip_id = snippet.snip_id <NEW_LINE> self.snippet = snippet | Attempted to redefine snip_id in committed snippet | 62598fbe3346ee7daa337745 |
class MathBlock(Block): <NEW_LINE> <INDENT> def __init__(self, parent, idevice): <NEW_LINE> <INDENT> Block.__init__(self, parent, idevice) <NEW_LINE> self.contentElement = MathElement(idevice.content) <NEW_LINE> self.contentElement.height = 250 <NEW_LINE> <DEDENT> def process(self, request): <NEW_LINE> <INDENT> Block.process(self, request) <NEW_LINE> self.contentElement.process(request) <NEW_LINE> <DEDENT> def renderEdit(self, style): <NEW_LINE> <INDENT> html = u"<div>\n" <NEW_LINE> html += self.contentElement.renderEdit() <NEW_LINE> html += self.renderEditButtons() <NEW_LINE> html += u"</div>\n" <NEW_LINE> return html <NEW_LINE> <DEDENT> def renderPreview(self, style): <NEW_LINE> <INDENT> html = u"<div class=\"iDevice " <NEW_LINE> html += u"emphasis"+unicode(self.idevice.emphasis)+"\" " <NEW_LINE> html += u"ondblclick=\"submitLink('edit',"+self.id+", 0);\">\n" <NEW_LINE> html += self.contentElement.renderPreview() <NEW_LINE> html += self.renderViewButtons() <NEW_LINE> html += "</div>\n" <NEW_LINE> return html <NEW_LINE> <DEDENT> def renderView(self, style): <NEW_LINE> <INDENT> html = u"<div class=\"iDevice " <NEW_LINE> html += u"emphasis"+unicode(self.idevice.emphasis)+"\">\n" <NEW_LINE> html += self.contentElement.renderView() <NEW_LINE> html += u"</div>\n" <NEW_LINE> return html | MathBlock can render and process MathIdevices as XHTML | 62598fbe21bff66bcd722e64 |
class Thing(Response): <NEW_LINE> <INDENT> _validation = { '_type': {'required': True}, 'id': {'readonly': True}, 'web_search_url': {'readonly': True}, 'name': {'readonly': True}, 'url': {'readonly': True}, 'image': {'readonly': True}, 'description': {'readonly': True}, 'bing_id': {'readonly': True}, } <NEW_LINE> _attribute_map = { '_type': {'key': '_type', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'web_search_url': {'key': 'webSearchUrl', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'url': {'key': 'url', 'type': 'str'}, 'image': {'key': 'image', 'type': 'ImageObject'}, 'description': {'key': 'description', 'type': 'str'}, 'bing_id': {'key': 'bingId', 'type': 'str'}, } <NEW_LINE> _subtype_map = { '_type': {'CreativeWork': 'CreativeWork', 'Intangible': 'Intangible'} } <NEW_LINE> def __init__(self, **kwargs) -> None: <NEW_LINE> <INDENT> super(Thing, self).__init__(**kwargs) <NEW_LINE> self.name = None <NEW_LINE> self.url = None <NEW_LINE> self.image = None <NEW_LINE> self.description = None <NEW_LINE> self.bing_id = None <NEW_LINE> self._type = 'Thing' | Thing.
You probably want to use the sub-classes and not this class directly. Known
sub-classes are: CreativeWork, Intangible
Variables are only populated by the server, and will be ignored when
sending a request.
All required parameters must be populated in order to send to Azure.
:param _type: Required. Constant filled by server.
:type _type: str
:ivar id: A String identifier.
:vartype id: str
:ivar web_search_url: The URL To Bing's search result for this item.
:vartype web_search_url: str
:ivar name: The name of the thing represented by this object.
:vartype name: str
:ivar url: The URL to get more information about the thing represented by
this object.
:vartype url: str
:ivar image:
:vartype image:
~azure.cognitiveservices.search.websearch.models.ImageObject
:ivar description: A short description of the item.
:vartype description: str
:ivar bing_id: An ID that uniquely identifies this item.
:vartype bing_id: str | 62598fbebe7bc26dc9251f59 |
class TestOWLUnaryPropertyAxiom(TestCase): <NEW_LINE> <INDENT> pass | OWLUnaryPropertyAxiom test cases | 62598fbed268445f26639c81 |
class XNORGate(Block): <NEW_LINE> <INDENT> def __init__(self,system,numInput,sizeInput): <NEW_LINE> <INDENT> self.numInput = numInput <NEW_LINE> self.name = "XNOR_GATE" <NEW_LINE> self.sizeInput = sizeInput <NEW_LINE> input_vector = [sizeInput]*self.numInput <NEW_LINE> output_vector = [sizeInput] <NEW_LINE> super().__init__(input_vector,output_vector,system,self.name) <NEW_LINE> <DEDENT> def generate(self): <NEW_LINE> <INDENT> filetext = "" <NEW_LINE> if self.getOutputSignalSize(0) == 1: <NEW_LINE> <INDENT> filetext += "%s <= %s"%(self.getOutputSignalName(0),self.getInputSignalName(0)) <NEW_LINE> for i in range(1,self.numInput): <NEW_LINE> <INDENT> filetext += " xnor %s"%(self.getInputSignalName(i)) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> filetext += "%s <= "%self.getOutputSignalName(0) <NEW_LINE> for i in range (self.sizeInput): <NEW_LINE> <INDENT> filetext += "%s[%d]"%(self.getInputSignalName(0),self.sizeInput-i-1) <NEW_LINE> for j in range(1,self.numInput): <NEW_LINE> <INDENT> filetext += " xnor %s[%d]"%(self.getInputSignalName(j),self.sizeInput-i-1) <NEW_LINE> <DEDENT> if i != self.sizeInput - 1: <NEW_LINE> <INDENT> filetext += " & " <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> filetext += ";\n" <NEW_LINE> return filetext | XNOR Gate
PORTS SPECIFICATIONS | 62598fbe4527f215b58ea0c8 |
class JobRepository(JobRepositoryInterface): <NEW_LINE> <INDENT> def find(self, uuid: 'UUID') -> Job: <NEW_LINE> <INDENT> return self._find({'uuid': uuid}) <NEW_LINE> <DEDENT> def create(self, **kwargs) -> Job: <NEW_LINE> <INDENT> return Job.objects.create(**kwargs) <NEW_LINE> <DEDENT> def get_or_create(self, **kwargs) -> Job: <NEW_LINE> <INDENT> return Job.objects.get_or_create(**kwargs) <NEW_LINE> <DEDENT> def factory(self, **kwargs) -> Job: <NEW_LINE> <INDENT> return self._factory(**kwargs) <NEW_LINE> <DEDENT> def save(self, instance: Job) -> Job: <NEW_LINE> <INDENT> return instance.save() <NEW_LINE> <DEDENT> def update_fields(self, instance: Job, fields: dict) -> Job: <NEW_LINE> <INDENT> for attr, val in fields.items(): <NEW_LINE> <INDENT> setattr(instance, attr, val) <NEW_LINE> <DEDENT> return instance.save(update_fields=fields.keys()) <NEW_LINE> <DEDENT> def _factory(self, **kwargs) -> Job: <NEW_LINE> <INDENT> return Job(**kwargs) <NEW_LINE> <DEDENT> def _find(self, params: dict) -> Job: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ret = Job.objects.get(**params) <NEW_LINE> <DEDENT> except ObjectDoesNotExist: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return ret | Implementation of the interface that define operations over the database. | 62598fbe091ae35668704e1f |
class Light: <NEW_LINE> <INDENT> def __init__(self, device, index): <NEW_LINE> <INDENT> self.device = device <NEW_LINE> self.index = index <NEW_LINE> <DEDENT> @property <NEW_LINE> def state(self): <NEW_LINE> <INDENT> return self.raw.get(ATTR_LIGHT_STATE) == 1 <NEW_LINE> <DEDENT> @property <NEW_LINE> def dimmer(self): <NEW_LINE> <INDENT> return self.raw.get(ATTR_LIGHT_DIMMER) <NEW_LINE> <DEDENT> @property <NEW_LINE> def hex_color(self): <NEW_LINE> <INDENT> return self.raw.get(ATTR_LIGHT_COLOR) <NEW_LINE> <DEDENT> @property <NEW_LINE> def xy_color(self): <NEW_LINE> <INDENT> return (self.raw.get(ATTR_LIGHT_COLOR_X), self.raw.get(ATTR_LIGHT_COLOR_Y)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def kelvin_color(self): <NEW_LINE> <INDENT> current_x = self.raw.get(ATTR_LIGHT_COLOR_X) <NEW_LINE> current_y = self.raw.get(ATTR_LIGHT_COLOR_Y) <NEW_LINE> if current_x is not None and current_y is not None: <NEW_LINE> <INDENT> kelvin = xyY_to_kelvin(current_x, current_y) <NEW_LINE> return kelvin if can_kelvin_to_xy(kelvin) else None <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def raw(self): <NEW_LINE> <INDENT> return self.device.raw[ATTR_LIGHT_CONTROL][self.index] <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> state = "on" if self.state else "off" <NEW_LINE> return "<Light #{} - " "name: {}, " "state: {}, " "dimmer: {}, " "hex_color: {}, " "xy_color: {}" ">".format(self.index, self.device.name, state, self.dimmer, self.hex_color, self.xy_color) | Represent a light control.
https://github.com/IPSO-Alliance/pub/blob/master/docs/IPSO-Smart-Objects.pdf | 62598fbe9f28863672818978 |
class AgeInsight(DemographicInsight): <NEW_LINE> <INDENT> def __init__(self, percentage=None, age=None, **kwargs): <NEW_LINE> <INDENT> super(AgeInsight, self).__init__(percentage=percentage, **kwargs) <NEW_LINE> self.age = age | AgeInsight. | 62598fbe3d592f4c4edbb0b9 |
class _TSeenSecondary(typing.NamedTuple): <NEW_LINE> <INDENT> schema_name: str <NEW_LINE> property_name: str | Records information about the secondary that has been seen. | 62598fbe7047854f4633f5cf |
class VirusTotalWhoisDialog(QDialog, Ui_VirusTotalWhoisDialog): <NEW_LINE> <INDENT> def __init__(self, domain, whois, parent=None): <NEW_LINE> <INDENT> super(VirusTotalWhoisDialog, self).__init__(parent) <NEW_LINE> self.setupUi(self) <NEW_LINE> self.headerLabel.setText( self.tr("<b>Whois information for domain {0}</b>").format(domain)) <NEW_LINE> self.headerPixmap.setPixmap( UI.PixmapCache.getPixmap("virustotal.png")) <NEW_LINE> self.whoisEdit.setPlainText(whois) | Class implementing a dialog to show the 'whois' information. | 62598fbeec188e330fdf8a8d |
class DataProject(Base): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def cast(arg): <NEW_LINE> <INDENT> return DataProject() <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return str() <NEW_LINE> <DEDENT> @name.setter <NEW_LINE> def name(self, name): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @property <NEW_LINE> def rootFolder(self): <NEW_LINE> <INDENT> return DataFolder() <NEW_LINE> <DEDENT> @property <NEW_LINE> def id(self): <NEW_LINE> <INDENT> return str() <NEW_LINE> <DEDENT> @property <NEW_LINE> def parentHub(self): <NEW_LINE> <INDENT> return DataHub() | Represents the master branch project within a hub. | 62598fbe55399d3f05626711 |
class GRUCell(RNNCellBase): <NEW_LINE> <INDENT> def __init__(self, input_size: int, hidden_size: int, bias: bool = True): <NEW_LINE> <INDENT> super().__init__(input_size, hidden_size, bias, num_chunks=3) <NEW_LINE> <DEDENT> def construct(self, inputs, hx): <NEW_LINE> <INDENT> return gru_cell(inputs, hx, self.weight_ih, self.weight_hh, self.bias_ih, self.bias_hh) | A GRU(Gated Recurrent Unit) cell.
.. math::
\begin{array}{ll}
r = \sigma(W_{ir} x + b_{ir} + W_{hr} h + b_{hr}) \\
z = \sigma(W_{iz} x + b_{iz} + W_{hz} h + b_{hz}) \\
n = \tanh(W_{in} x + b_{in} + r * (W_{hn} h + b_{hn})) \\
h' = (1 - z) * n + z * h
\end{array}
Here :math:`\sigma` is the sigmoid function, and :math:`*` is the Hadamard product. :math:`W, b`
are learnable weights between the output and the input in the formula. For instance,
:math:`W_{ir}, b_{ir}` are the weight and bias used to transform from input :math:`x` to :math:`r`.
Details can be found in paper
`Learning Phrase Representations using RNN Encoder–Decoder for Statistical Machine Translation
<https://aclanthology.org/D14-1179.pdf>`_.
Args:
input_size (int): Number of features of input.
hidden_size (int): Number of features of hidden layer.
has_bias (bool): Whether the cell has bias `b_ih` and `b_hh`. Default: True.
Inputs:
- **x** (Tensor) - Tensor of shape (batch_size, `input_size`).
- **hx** (Tensor) - Tensor of data type mindspore.float32 and shape (batch_size, `hidden_size`).
Data type of `hx` must be the same as `x`.
Outputs:
- **hx'** (Tensor) - Tensor of shape (batch_size, `hidden_size`).
Raises:
TypeError: If `input_size`, `hidden_size` is not an int.
TypeError: If `has_bias` is not a bool.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> net = nn.GRUCell(10, 16)
>>> x = Tensor(np.ones([5, 3, 10]).astype(np.float32))
>>> hx = Tensor(np.ones([3, 16]).astype(np.float32))
>>> output = []
>>> for i in range(5):
>>> hx = net(x[i], hx)
>>> output.append(hx)
>>> print(output[0].shape)
(3, 16) | 62598fbe5fdd1c0f98e5e18d |
class PredPreyEnv(se.SpatialEnv): <NEW_LINE> <INDENT> repop = True <NEW_LINE> def __init__(self, name, length, height, preact=True, postact=True, model_nm="predprey_model"): <NEW_LINE> <INDENT> super().__init__(name, length, height, preact, postact, model_nm=model_nm) <NEW_LINE> self.agents.set_num_zombies(self.props.get("num_zombies", 0)) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> self.agents.create_zombies() <NEW_LINE> super().run() <NEW_LINE> <DEDENT> def keep_running(self): <NEW_LINE> <INDENT> return len(self.agents) > 0 <NEW_LINE> <DEDENT> def postact_loop(self): <NEW_LINE> <INDENT> for creature in reversed(self.agents): <NEW_LINE> <INDENT> if not creature.is_alive(): <NEW_LINE> <INDENT> self.agents.remove(creature) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def new_name_suffix(self, creature): <NEW_LINE> <INDENT> pop = self.get_my_pop(creature) <NEW_LINE> return "." + str(self.period) + "." + str(pop) | This class creates an environment for predators
to chase and eat prey | 62598fbe7d43ff2487427502 |
class RebootTest(base_test.BaseTestClass): <NEW_LINE> <INDENT> def setUpClass(self): <NEW_LINE> <INDENT> self.dut = self.android_devices[0] <NEW_LINE> <DEDENT> def testReboot(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.dut.reboot() <NEW_LINE> self.dut.waitForBootCompletion() <NEW_LINE> <DEDENT> except utils.TimeoutError: <NEW_LINE> <INDENT> asserts.fail("Reboot failed.") | Tests if device survives reboot.
Attributes:
dut: AndroidDevice, the device under test as config | 62598fbea8370b77170f05dc |
@python_2_unicode_compatible <NEW_LINE> class SurveyForm(TimeStampedModel): <NEW_LINE> <INDENT> name = models.CharField(max_length=255, db_index=True, unique=True) <NEW_LINE> form = models.TextField() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> app_label = 'survey' <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> self.validate_form_html(self.form) <NEW_LINE> super().save(*args, **kwargs) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def validate_form_html(cls, html): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> fields = cls.get_field_names_from_html(html) <NEW_LINE> <DEDENT> except Exception as ex: <NEW_LINE> <INDENT> log.exception(f"Cannot parse SurveyForm html: {ex}") <NEW_LINE> raise ValidationError(f"Cannot parse SurveyForm as HTML: {ex}") <NEW_LINE> <DEDENT> if not len(fields): <NEW_LINE> <INDENT> raise ValidationError("SurveyForms must contain at least one form input field") <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def create(cls, name, form, update_if_exists=False): <NEW_LINE> <INDENT> survey = cls.get(name, throw_if_not_found=False) <NEW_LINE> if not survey: <NEW_LINE> <INDENT> survey = SurveyForm(name=name, form=form) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if update_if_exists: <NEW_LINE> <INDENT> survey.form = form <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise SurveyFormNameAlreadyExists() <NEW_LINE> <DEDENT> <DEDENT> survey.save() <NEW_LINE> return survey <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get(cls, name, throw_if_not_found=True): <NEW_LINE> <INDENT> survey = None <NEW_LINE> exists = SurveyForm.objects.filter(name=name).exists() <NEW_LINE> if exists: <NEW_LINE> <INDENT> survey = SurveyForm.objects.get(name=name) <NEW_LINE> <DEDENT> elif throw_if_not_found: <NEW_LINE> <INDENT> raise SurveyFormNotFound() <NEW_LINE> <DEDENT> return survey <NEW_LINE> <DEDENT> def get_answers(self, user=None, limit_num_users=10000): <NEW_LINE> <INDENT> return SurveyAnswer.get_answers(self, user, limit_num_users=limit_num_users) <NEW_LINE> <DEDENT> def has_user_answered_survey(self, user): <NEW_LINE> <INDENT> return SurveyAnswer.do_survey_answers_exist(self, user) <NEW_LINE> <DEDENT> def save_user_answers(self, user, answers, course_key): <NEW_LINE> <INDENT> self.clear_user_answers(user) <NEW_LINE> SurveyAnswer.save_answers(self, user, answers, course_key) <NEW_LINE> <DEDENT> def clear_user_answers(self, user): <NEW_LINE> <INDENT> SurveyAnswer.objects.filter(form=self, user=user).delete() <NEW_LINE> <DEDENT> def get_field_names(self): <NEW_LINE> <INDENT> return SurveyForm.get_field_names_from_html(self.form) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_field_names_from_html(cls, html): <NEW_LINE> <INDENT> names = [] <NEW_LINE> tree = etree.fromstring(HTML('<div>{}</div>').format(HTML(html))) <NEW_LINE> input_fields = ( tree.findall('.//input') + tree.findall('.//select') + tree.findall('.//textarea') ) <NEW_LINE> for input_field in input_fields: <NEW_LINE> <INDENT> if 'name' in list(input_field.keys()) and input_field.attrib['name'] not in names: <NEW_LINE> <INDENT> names.append(input_field.attrib['name']) <NEW_LINE> <DEDENT> <DEDENT> return names | Model to define a Survey Form that contains the HTML form data
that is presented to the end user. A SurveyForm is not tied to
a particular run of a course, to allow for sharing of Surveys
across courses
.. no_pii: | 62598fbed7e4931a7ef3c290 |
class Session(object): <NEW_LINE> <INDENT> session_re = re.compile( r'^(?P<protocol>https?)://(?P<host>([a-z0-9-_])+(\.[a-z0-9-_]+){0,})(:(?P<port>\d{1,5}))?$' ) <NEW_LINE> def __init__(self, protocol, host, port=None): <NEW_LINE> <INDENT> self.protocol = protocol <NEW_LINE> self.host = host <NEW_LINE> if port is None: <NEW_LINE> <INDENT> port = 9200 <NEW_LINE> <DEDENT> self.port = port <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_string(cls, session_as_string): <NEW_LINE> <INDENT> session_as_string = session_as_string.strip() <NEW_LINE> m = cls.session_re.match(session_as_string) <NEW_LINE> if m is None: <NEW_LINE> <INDENT> raise SessionException("string does not match a session") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> port = None <NEW_LINE> if m.group('port'): <NEW_LINE> <INDENT> port = int(m.group('port')) <NEW_LINE> <DEDENT> return cls(m.group('protocol'), m.group('host'), port) <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "{}://{}:{}".format(self.protocol, self.host, self.port) | Elasticsearch session
| 62598fbe99fddb7c1ca62eea |
class Interface: <NEW_LINE> <INDENT> def __init__(self, game): <NEW_LINE> <INDENT> self.game = game <NEW_LINE> pg.init() <NEW_LINE> self.window = pg.display.set_mode((640, 600)) <NEW_LINE> self.window.fill((230, 230, 230)) <NEW_LINE> pg.display.set_caption("MacGseyver Escape") <NEW_LINE> self.sprites = { FLOOR: pg.image.load('ressources/floor.png').convert_alpha(), WALL: pg.image.load('ressources/wall.png').convert_alpha(), NEEDLE: pg.image.load('ressources/aiguillem.png').convert_alpha(), PIPE: pg.image.load('ressources/pipe.png').convert_alpha(), ETHER: pg.image.load('ressources/ether.png').convert_alpha(), HEROS: pg.image.load('ressources/MacGyver.png').convert_alpha(), GUARDIAN: pg.image.load('ressources/Gardien.png').convert_alpha() } <NEW_LINE> self.movement = { pg.K_UP: 'UP', pg.K_DOWN: 'DOWN', pg.K_RIGHT: 'RIGHT', pg.K_LEFT: 'LEFT' } <NEW_LINE> <DEDENT> def check_final_value(self): <NEW_LINE> <INDENT> if self.game.okay == 1: <NEW_LINE> <INDENT> Message(self.window, "Game Over").draw_message() <NEW_LINE> <DEDENT> elif self.game.okay == 2: <NEW_LINE> <INDENT> Message(self.window, "You win").draw_message() <NEW_LINE> <DEDENT> <DEDENT> def show_find_objects(self): <NEW_LINE> <INDENT> for i, row in enumerate(self.game.list_objects): <NEW_LINE> <INDENT> sprite = self.sprites[row] <NEW_LINE> self.window.blit(sprite, (40*15, 40*(1+i))) <NEW_LINE> <DEDENT> <DEDENT> def show_maze(self): <NEW_LINE> <INDENT> for i, row in enumerate(self.game.maze): <NEW_LINE> <INDENT> for j, cell in enumerate(row): <NEW_LINE> <INDENT> self.show_cell(cell, i, j) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def show_cell(self, cell, i, j): <NEW_LINE> <INDENT> sprite = self.sprites[cell] <NEW_LINE> if cell not in (WALL, FLOOR): <NEW_LINE> <INDENT> self.show_cell(FLOOR, i, j) <NEW_LINE> <DEDENT> self.window.blit(sprite, (40*j, 40*i)) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> runing = self.game.okay <NEW_LINE> while not self.game.okay: <NEW_LINE> <INDENT> self.items = Items(self.window, self.game.counter_items) <NEW_LINE> self.show_maze() <NEW_LINE> self.show_find_objects() <NEW_LINE> self.items.show_number_items() <NEW_LINE> print(self.game.counter_items) <NEW_LINE> for event in pg.event.get(): <NEW_LINE> <INDENT> if event.type == pg.QUIT: <NEW_LINE> <INDENT> exit(0) <NEW_LINE> <DEDENT> elif event.type == pg.KEYDOWN: <NEW_LINE> <INDENT> if event.key in self.movement: <NEW_LINE> <INDENT> self.game.move_hero(self.movement[event.key]) <NEW_LINE> <DEDENT> elif event.key == pg.K_q: <NEW_LINE> <INDENT> exit(0) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> pg.display.flip() <NEW_LINE> <DEDENT> self.check_final_value() <NEW_LINE> pg.display.flip() <NEW_LINE> while True: <NEW_LINE> <INDENT> for event in pg.event.get(): <NEW_LINE> <INDENT> if event.type == pg.QUIT: <NEW_LINE> <INDENT> exit(0) <NEW_LINE> <DEDENT> elif event.type == pg.KEYDOWN: <NEW_LINE> <INDENT> if event.key == pg.K_q: <NEW_LINE> <INDENT> exit(0) | Control the view of the game using pygame | 62598fbe5fdd1c0f98e5e18e |
@ComponentFactory(FACTORY_REQUIRES_BEST) <NEW_LINE> @RequiresBest('service', IEchoService) <NEW_LINE> class RequiresBestComponentFactory(TestComponentFactory): <NEW_LINE> <INDENT> @Bind <NEW_LINE> def bind(self, svc, svc_ref): <NEW_LINE> <INDENT> self.states.append(IPopoEvent.BOUND) <NEW_LINE> <DEDENT> @Unbind <NEW_LINE> def unbind(self, svc, svc_ref): <NEW_LINE> <INDENT> self.states.append(IPopoEvent.UNBOUND) | Component factory with a RequiresBest requirement | 62598fbe4527f215b58ea0ca |
class SuiteEntryUpdateModel(Model): <NEW_LINE> <INDENT> _attribute_map = { 'child_suite_id': {'key': 'childSuiteId', 'type': 'int'}, 'sequence_number': {'key': 'sequenceNumber', 'type': 'int'}, 'test_case_id': {'key': 'testCaseId', 'type': 'int'} } <NEW_LINE> def __init__(self, child_suite_id=None, sequence_number=None, test_case_id=None): <NEW_LINE> <INDENT> super(SuiteEntryUpdateModel, self).__init__() <NEW_LINE> self.child_suite_id = child_suite_id <NEW_LINE> self.sequence_number = sequence_number <NEW_LINE> self.test_case_id = test_case_id | SuiteEntryUpdateModel.
:param child_suite_id: Id of child suite in a suite
:type child_suite_id: int
:param sequence_number: Updated sequence number for the test case or child suite in the suite
:type sequence_number: int
:param test_case_id: Id of a test case in a suite
:type test_case_id: int | 62598fbe091ae35668704e21 |
class NumpyToTensor(object): <NEW_LINE> <INDENT> def __call__(self, img): <NEW_LINE> <INDENT> x = torch.from_numpy(img) <NEW_LINE> return x | Converts numpy array to PyTorch tensor. | 62598fbe442bda511e95c65b |
class ResolutionEmailView(generic.DetailView): <NEW_LINE> <INDENT> model = ResolutionEmail | View to get the details of one resolution email | 62598fbe66673b3332c305cf |
@override_settings(EMAIL_BACKEND="anymail.backends.mailgun.EmailBackend") <NEW_LINE> class MailgunBackendImproperlyConfiguredTests(SimpleTestCase, AnymailTestMixin): <NEW_LINE> <INDENT> def test_missing_api_key(self): <NEW_LINE> <INDENT> with self.assertRaises(ImproperlyConfigured) as cm: <NEW_LINE> <INDENT> mail.send_mail('Subject', 'Message', 'from@example.com', ['to@example.com']) <NEW_LINE> <DEDENT> errmsg = str(cm.exception) <NEW_LINE> self.assertRegex(errmsg, r'\bMAILGUN_API_KEY\b') <NEW_LINE> self.assertRegex(errmsg, r'\bANYMAIL_MAILGUN_API_KEY\b') | Test ESP backend without required settings in place | 62598fbe71ff763f4b5e7978 |
class MessageContactModel(S3Model): <NEW_LINE> <INDENT> names = ("msg_contact", ) <NEW_LINE> def model(self): <NEW_LINE> <INDENT> T = current.T <NEW_LINE> tablename = "msg_contact" <NEW_LINE> self.define_table(tablename, self.super_link("message_id", "msg_message"), self.msg_channel_id(), s3_datetime(default = "now"), Field("subject", length=78, label = T("Subject"), requires = IS_LENGTH(78), ), Field("name", label = T("Name"), ), Field("body", "text", label = T("Message"), ), Field("phone", label = T("Phone"), requires = IS_EMPTY_OR(IS_PHONE_NUMBER_MULTI()), ), Field("from_address", label = T("Email"), requires = IS_EMPTY_OR(IS_EMAIL()), ), Field("inbound", "boolean", default = True, label = T("Direction"), represent = lambda direction: (direction and [T("In")] or [T("Out")])[0], readable = False, writable = False, ), *s3_meta_fields()) <NEW_LINE> self.configure(tablename, orderby = "msg_contact.date desc", super_entity = "msg_message", ) <NEW_LINE> current.response.s3.crud_strings[tablename] = Storage( label_create = T("Contact Form"), title_display = T("Contact Details"), title_list = T("Contacts"), title_update = T("Edit Contact"), label_list_button = T("List Contacts"), label_delete_button = T("Delete Contact"), msg_record_created = T("Contact added"), msg_record_modified = T("Contact updated"), msg_record_deleted = T("Contact deleted"), msg_list_empty = T("No Contacts currently registered")) <NEW_LINE> return None | Contact Form | 62598fbeec188e330fdf8a90 |
class AzureAsyncOperationResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'status': {'key': 'status', 'type': 'str'}, 'error': {'key': 'error', 'type': 'Error'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(AzureAsyncOperationResult, self).__init__(**kwargs) <NEW_LINE> self.status = kwargs.get('status', None) <NEW_LINE> self.error = kwargs.get('error', None) | The response body contains the status of the specified asynchronous operation, indicating whether it has succeeded, is in progress, or has failed. Note that this status is distinct from the HTTP status code returned for the Get Operation Status operation itself. If the asynchronous operation succeeded, the response body includes the HTTP status code for the successful request. If the asynchronous operation failed, the response body includes the HTTP status code for the failed request and error information regarding the failure.
:param status: Status of the Azure async operation. Possible values include: "InProgress",
"Succeeded", "Failed".
:type status: str or ~azure.mgmt.network.v2020_04_01.models.NetworkOperationStatus
:param error: Details of the error occurred during specified asynchronous operation.
:type error: ~azure.mgmt.network.v2020_04_01.models.Error | 62598fbe7b180e01f3e4914e |
class ExtendedQLabel(QtGui.QLabel): <NEW_LINE> <INDENT> zoom = Signal(QtGui.QWheelEvent, name="zoom") <NEW_LINE> pan = Signal(QtGui.QMoveEvent, name="pan") <NEW_LINE> DELTA2 = 100 <NEW_LINE> def __init__(self, parent): <NEW_LINE> <INDENT> QtGui.QLabel.__init__(self, parent) <NEW_LINE> self.old_pos = None <NEW_LINE> <DEDENT> def mouseReleaseEvent(self, ev): <NEW_LINE> <INDENT> logger.debug("Released %s %s", ev, ev) <NEW_LINE> if self.old_pos is not None: <NEW_LINE> <INDENT> lastx, lasty = self.old_pos <NEW_LINE> x = ev.x() <NEW_LINE> y = ev.y() <NEW_LINE> dx = x - lastx <NEW_LINE> dy = y - lasty <NEW_LINE> delta2 = dx * dx + dy * dy <NEW_LINE> if delta2 > self.DELTA2: <NEW_LINE> <INDENT> move_ev = QtGui.QMoveEvent(ev.pos(), QtCore.QPoint(*self.old_pos)) <NEW_LINE> self.pan.emit(move_ev) <NEW_LINE> <DEDENT> self.old_pos = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("last ev is None !!!") <NEW_LINE> <DEDENT> <DEDENT> def mousePressEvent(self, ev): <NEW_LINE> <INDENT> logger.debug("Pressed %s %s %s ", ev, ev.x(), ev.y()) <NEW_LINE> self.old_pos = (ev.x(), ev.y()) <NEW_LINE> <DEDENT> def wheelEvent(self, ev): <NEW_LINE> <INDENT> logger.debug("Scroll %s at %s,%s %s", ev, ev.x(), ev.y(), ev.delta()) <NEW_LINE> self.zoom.emit(ev) | Extenstion for Qlabel with pan and zoom function used to display images
| 62598fbe55399d3f05626713 |
class TradeList(object): <NEW_LINE> <INDENT> def __init__(self, trades: list=None): <NEW_LINE> <INDENT> self.trades = trades or [] <NEW_LINE> <DEDENT> def add_trade(self, trade: Trade): <NEW_LINE> <INDENT> self.trades.append(trade) <NEW_LINE> <DEDENT> def get_trades_in_interval(self) -> list: <NEW_LINE> <INDENT> interval_start = datetime.now() - timedelta(minutes=15) <NEW_LINE> interval_end = datetime.now() <NEW_LINE> trades_in_interval = [] <NEW_LINE> for trade in self.trades: <NEW_LINE> <INDENT> if interval_start <= trade.trade_date <= interval_end: <NEW_LINE> <INDENT> trades_in_interval.append(trade) <NEW_LINE> <DEDENT> <DEDENT> return trades_in_interval <NEW_LINE> <DEDENT> @handle_zero_division <NEW_LINE> def vol_weighted_stock_price(self) -> float: <NEW_LINE> <INDENT> price_quantity_sum = 0 <NEW_LINE> quantity_sum = 0 <NEW_LINE> for trade in self.trades: <NEW_LINE> <INDENT> price_quantity_sum += trade.price * trade.volume <NEW_LINE> quantity_sum += trade.volume <NEW_LINE> <DEDENT> return price_quantity_sum / quantity_sum | Contains a list of trade transactions, along with helper methods
to process the transaction list | 62598fbe656771135c48986c |
class GitNameNotFound(ContinuousIntegrationException): <NEW_LINE> <INDENT> pass | Describes a missing Git Name. | 62598fbe956e5f7376df577d |
class Condition: <NEW_LINE> <INDENT> META_DATA_HEADER = "\t".join(["isTs", "is1stLast", "prevCol", "del.t", "condName"]) + "\n" <NEW_LINE> def __init__(self, condition_name, gene_mapping): <NEW_LINE> <INDENT> self.name = condition_name <NEW_LINE> self.gene_mapping = pd.Series(gene_mapping, name=condition_name) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Condition" + repr((self.name, id(self))) <NEW_LINE> <DEDENT> def response_scalar(self, gene_name): <NEW_LINE> <INDENT> return self.gene_mapping[gene_name] <NEW_LINE> <DEDENT> def design_vector(self, transcription_factors): <NEW_LINE> <INDENT> return self.gene_mapping[transcription_factors] <NEW_LINE> <DEDENT> def meta_data_tsv_line(self, isTs=False, is1stLast="e", prevCol=None, delt=None): <NEW_LINE> <INDENT> def f(s): <NEW_LINE> <INDENT> if s is None: <NEW_LINE> <INDENT> return "NA" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return repr(s).replace("'", '"') <NEW_LINE> <DEDENT> <DEDENT> data = [isTs, is1stLast, prevCol, delt, self.name] <NEW_LINE> return "\t".join(map(f, data)) + "\n" | A condition maps gene names to numbers which often represent expression levels.
Parameters
----------
condition_name: str
A unique name identifying the condition.
gene_mapping: pd.Series
A pandas Series holding the gene to number mapping or an object that
can be converted to a pandas Series. | 62598fbe7cff6e4e811b5c20 |
class ParallelDevice(object): <NEW_LINE> <INDENT> def __init__(self, components): <NEW_LINE> <INDENT> global _next_device_number, _next_device_number_lock <NEW_LINE> self.components = tuple(components) <NEW_LINE> ctx = context.context() <NEW_LINE> with _next_device_number_lock: <NEW_LINE> <INDENT> self.name = "{}/device:CUSTOM:{}".format( ctx.host_address_space(), _next_device_number) <NEW_LINE> _next_device_number += 1 <NEW_LINE> <DEDENT> device, device_info = _pywrap_parallel_device.GetParallelDeviceCapsules( self.name, self.components) <NEW_LINE> context.register_custom_device(device, self.name, device_info) <NEW_LINE> <DEDENT> def pack(self, tensors): <NEW_LINE> <INDENT> with ops.device(self.name): <NEW_LINE> <INDENT> return tpu_ops.tpu_replicated_input(inputs=tensors) <NEW_LINE> <DEDENT> <DEDENT> def unpack(self, parallel_tensor): <NEW_LINE> <INDENT> with ops.device(self.name): <NEW_LINE> <INDENT> return tpu_ops.tpu_replicated_output( parallel_tensor, num_replicas=len(self.components)) <NEW_LINE> <DEDENT> <DEDENT> @contextlib.contextmanager <NEW_LINE> def scope(self): <NEW_LINE> <INDENT> with ops.device(self.name), saving.independent_buffers(self): <NEW_LINE> <INDENT> yield | A device which executes operations in parallel. | 62598fbead47b63b2c5a7a53 |
class _ClippingPlaneRemoveAll(CommandManager): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(_ClippingPlaneRemoveAll, self).__init__() <NEW_LINE> self.resources = { "Pixmap": "fem-clipping-plane-remove-all", "MenuText": QtCore.QT_TRANSLATE_NOOP( "FEM_ClippingPlaneRemoveAll", "Remove all clipping planes" ), "ToolTip": QtCore.QT_TRANSLATE_NOOP( "FEM_ClippingPlaneRemoveAll", "Remove all clipping planes" ) } <NEW_LINE> self.is_active = "with_document" <NEW_LINE> <DEDENT> def Activated(self): <NEW_LINE> <INDENT> line1 = "for node in list(sg.getChildren()):\n" <NEW_LINE> line2 = " if isinstance(node, coin.SoClipPlane):\n" <NEW_LINE> line3 = " sg.removeChild(node)" <NEW_LINE> FreeCADGui.doCommand("from pivy import coin") <NEW_LINE> FreeCADGui.doCommand("sg = Gui.ActiveDocument.ActiveView.getSceneGraph()") <NEW_LINE> FreeCADGui.doCommand("nodes = sg.getChildren()") <NEW_LINE> FreeCADGui.doCommand(line1 + line2 + line3) | The FEM_ClippingPlaneemoveAll command definition | 62598fbe796e427e5384e993 |
class UPCCodeGenerator(CCodeGenerator): <NEW_LINE> <INDENT> pass | A BRAID-style code generator for UPC. | 62598fbe57b8e32f5250821c |
class TestAddressResource(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 testAddressResource(self): <NEW_LINE> <INDENT> pass | AddressResource unit test stubs | 62598fbe7d847024c075c5bb |
class CustomUser(AbstractBaseUser): <NEW_LINE> <INDENT> name = models.CharField(_('name'), max_length=254, blank=True, default="") <NEW_LINE> email = models.EmailField(_('email address'), max_length=254, unique=True) <NEW_LINE> date_of_birth = models.DateField(blank=True, null=True) <NEW_LINE> is_staff = models.BooleanField(_('staff status'), default=False) <NEW_LINE> is_active = models.BooleanField(_('active'), default=False, help_text=_('Designates whether this user should be treated as active. Unselect it instead of deleting accounts.')) <NEW_LINE> USERNAME_FIELD = 'email' <NEW_LINE> objects = manager.CustomUserManager() <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return str(self.email) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = _('user') <NEW_LINE> verbose_name_plural = _('users') <NEW_LINE> <DEDENT> def get_full_name(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def get_short_name(self): <NEW_LINE> <INDENT> return self.name.strip() <NEW_LINE> <DEDENT> def email_user(self, subject, message, from_email=None): <NEW_LINE> <INDENT> send_mail(subject, message, from_email, [self.email]) <NEW_LINE> <DEDENT> def forgot_password(self, *args, **kwargs): <NEW_LINE> <INDENT> User.password_change(self) <NEW_LINE> super(User, self).save(*args, **kwargs) <NEW_LINE> <DEDENT> def password_change(self): <NEW_LINE> <INDENT> password = User.objects.make_random_password() <NEW_LINE> ask_for_password_change(password, self.get_full_name(), self.email) <NEW_LINE> self.set_password(password) <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_superuser(self): <NEW_LINE> <INDENT> return self.is_staff <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_admin(self): <NEW_LINE> <INDENT> return self.is_staff <NEW_LINE> <DEDENT> def has_perm(self, perm, obj=None): <NEW_LINE> <INDENT> return self.is_staff <NEW_LINE> <DEDENT> def has_module_perms(self, app_label): <NEW_LINE> <INDENT> return self.is_staff <NEW_LINE> <DEDENT> def get_perms(self): <NEW_LINE> <INDENT> all_perms = [] <NEW_LINE> for group in self.groups.all(): <NEW_LINE> <INDENT> all_perms += group.permissions.all() <NEW_LINE> <DEDENT> return all_perms <NEW_LINE> <DEDENT> def get_perms_names(self): <NEW_LINE> <INDENT> all_perms = [] <NEW_LINE> for group in self.groups.all(): <NEW_LINE> <INDENT> for perm in group.permissions.all(): <NEW_LINE> <INDENT> all_perms.append(str(perm.codename)) <NEW_LINE> <DEDENT> <DEDENT> return all_perms <NEW_LINE> <DEDENT> def get_all_groups_names(self): <NEW_LINE> <INDENT> all_groups = [] <NEW_LINE> for group in self.groups.all(): <NEW_LINE> <INDENT> all_groups.append(str(group.display_name)) <NEW_LINE> <DEDENT> return all_groups <NEW_LINE> <DEDENT> def get_allowed_categories_as_writer(self): <NEW_LINE> <INDENT> categories = [] <NEW_LINE> for i in self.groups.filter(name__contains="writer"): <NEW_LINE> <INDENT> categories.append(i.name[0:-len('-writer')]) <NEW_LINE> <DEDENT> return categories <NEW_LINE> <DEDENT> def get_allowed_categories_as_editor(self): <NEW_LINE> <INDENT> categories = [] <NEW_LINE> for i in self.groups.filter(name__contains="writer"): <NEW_LINE> <INDENT> categories.append(i.name[0:-len('-writer')]) <NEW_LINE> <DEDENT> return categories | A custom user class that basically mirrors Django's `AbstractUser` class | 62598fbe5166f23b2e2435dd |
class ExactMarginalLogLikelihood(MarginalLogLikelihood): <NEW_LINE> <INDENT> def __init__(self, likelihood, model): <NEW_LINE> <INDENT> if not isinstance(likelihood, _GaussianLikelihoodBase): <NEW_LINE> <INDENT> raise RuntimeError("Likelihood must be Gaussian for exact inference") <NEW_LINE> <DEDENT> super(ExactMarginalLogLikelihood, self).__init__(likelihood, model) <NEW_LINE> <DEDENT> def forward(self, function_dist, target, *params): <NEW_LINE> <INDENT> if not isinstance(function_dist, MultivariateNormal): <NEW_LINE> <INDENT> raise RuntimeError("ExactMarginalLogLikelihood can only operate on Gaussian random variables") <NEW_LINE> <DEDENT> output = self.likelihood(function_dist, *params) <NEW_LINE> res = output.log_prob(target) <NEW_LINE> for added_loss_term in self.model.added_loss_terms(): <NEW_LINE> <INDENT> res = res.add(added_loss_term.loss(*params)) <NEW_LINE> <DEDENT> for _, prior, closure, _ in self.named_priors(): <NEW_LINE> <INDENT> res.add_(prior.log_prob(closure()).sum()) <NEW_LINE> <DEDENT> num_data = target.size(-1) <NEW_LINE> return res.div_(num_data) <NEW_LINE> <DEDENT> def pyro_factor(self, output, target, *params): <NEW_LINE> <INDENT> import pyro <NEW_LINE> mll = self(output, target, *params) <NEW_LINE> pyro.factor("gp_mll", mll) <NEW_LINE> return mll | The exact marginal log likelihood (MLL) for an exact Gaussian process with a
Gaussian likelihood.
.. note::
This module will not work with anything other than a :obj:`~gpytorch.likelihoods.GaussianLikelihood`
and a :obj:`~gpytorch.models.ExactGP`. It also cannot be used in conjunction with
stochastic optimization.
:param ~gpytorch.likelihoods.GaussianLikelihood likelihood: The Gaussian likelihood for the model
:param ~gpytorch.models.ExactGP model: The exact GP model
Example:
>>> # model is a gpytorch.models.ExactGP
>>> # likelihood is a gpytorch.likelihoods.Likelihood
>>> mll = gpytorch.mlls.ExactMarginalLogLikelihood(likelihood, model)
>>>
>>> output = model(train_x)
>>> loss = -mll(output, train_y)
>>> loss.backward() | 62598fbebe7bc26dc9251f5b |
class EchoClient(protocol.Protocol): <NEW_LINE> <INDENT> def connectionMade(self): <NEW_LINE> <INDENT> self.transport.write(b"hello alex!") <NEW_LINE> <DEDENT> def dataReceived(self, data): <NEW_LINE> <INDENT> print("Server said:", data.decode()) <NEW_LINE> self.transport.loseConnection() <NEW_LINE> <DEDENT> def connectionLost(self, reason): <NEW_LINE> <INDENT> print("connection lost") | Once connected, send a message, then print the result. | 62598fbefff4ab517ebcd9e3 |
class UnscentedTransform(object): <NEW_LINE> <INDENT> _sum = functools.partial(np.sum, axis=0) <NEW_LINE> def __init__(self, function): <NEW_LINE> <INDENT> assert isinstance(function, collections.Callable) <NEW_LINE> self._function = function <NEW_LINE> <DEDENT> def __call__(self, mean, covariance, *args, **kwargs): <NEW_LINE> <INDENT> returnSigmas = kwargs.pop('returnSigmas', False) <NEW_LINE> inputSigmaPoints, weights = UnscentedTransform.sigmaPoints(mean, covariance) <NEW_LINE> outputSigmaPoints = [self._function(p, *args, **kwargs) for p in inputSigmaPoints] <NEW_LINE> weightedOutputPoints = zip(weights, outputSigmaPoints) <NEW_LINE> outputMean = self._sum(W*y for W,y in weightedOutputPoints) <NEW_LINE> outputCovariance = self._sum(W*(y-outputMean)*(y-outputMean).T for W,y in weightedOutputPoints) <NEW_LINE> if returnSigmas: <NEW_LINE> <INDENT> return outputMean, outputCovariance, inputSigmaPoints, outputSigmaPoints, weights <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return outputMean, outputCovariance <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def sigmaPoints(mean, covariance): <NEW_LINE> <INDENT> N = len(mean) <NEW_LINE> mean = np.reshape(mean, (N,1)) <NEW_LINE> assert covariance.shape == (N,N) <NEW_LINE> sigmaPoints = [mean] * (2*N + 1) <NEW_LINE> w0 = 1/3 <NEW_LINE> cholesky = linalg.cholesky((N/(1-w0)) * covariance) <NEW_LINE> columns = np.hsplit(cholesky, N) <NEW_LINE> for i, column in enumerate(columns): <NEW_LINE> <INDENT> sigmaPoints[i+1] = mean + column <NEW_LINE> sigmaPoints[i+1+N] = mean - column <NEW_LINE> <DEDENT> weights = [w0] + [(1-w0)/(2*N)] * (2 * N) <NEW_LINE> return sigmaPoints, weights | Implementation of the Unscented Transform of Julier and Uhlmann.
The unscented transform propagates mean and covariance information
through a non-linear function. An instance of this class is callable
to apply the function to a vector of mean values and a covariance
matrix, returning an output mean vector and covariance matrix. | 62598fbea8370b77170f05df |
class MigrateMaterialsView(LoggedInFacultyMixin, AjaxRequiredMixin, JSONResponseMixin, View): <NEW_LINE> <INDENT> def get(self, request, *args, **kwargs): <NEW_LINE> <INDENT> course = get_object_or_404(Course, id=kwargs.pop('course_id', None)) <NEW_LINE> faculty = [user.id for user in course.faculty.all()] <NEW_LINE> faculty_ctx = UserResource().render_list(request, course.faculty.all()) <NEW_LINE> assets = Asset.objects.by_course(course) <NEW_LINE> if settings.SURELINK_URL: <NEW_LINE> <INDENT> assets = assets.exclude( source__url__startswith=settings.SURELINK_URL) <NEW_LINE> <DEDENT> assets = assets.filter( sherdnote_set__author__id__in=faculty ).exclude(source__label='flv_pseudo') <NEW_LINE> notes = SherdNote.objects.get_related_notes( assets, None, faculty, True).exclude_primary_types(['flv_pseudo']) <NEW_LINE> ares = AssetResource(include_annotations=False) <NEW_LINE> asset_ctx = ares.render_list(request, None, None, assets, notes) <NEW_LINE> projects = Project.objects.by_course_and_users(course, faculty) <NEW_LINE> if projects.count() > 0: <NEW_LINE> <INDENT> collabs = Collaboration.objects.get_for_object_list(projects) <NEW_LINE> collabs = collabs.exclude( policy_record__policy_name='PrivateEditorsAreOwners') <NEW_LINE> ids = collabs.values_list('object_pk', flat=True) <NEW_LINE> projects = projects.filter(id__in=ids) <NEW_LINE> <DEDENT> info_ctx = CourseInfoResource().render_one(request, course) <NEW_LINE> ctx = { 'course': {'id': course.id, 'title': course.title, 'faculty': faculty_ctx, 'info': info_ctx}, 'assets': asset_ctx, 'projects': ProjectResource().render_list(request, projects) } <NEW_LINE> return self.render_to_json_response(ctx) | An ajax-only request to retrieve course information & materials
from the perspective of the course faculty members.
Returns:
* Projects authored by faculty
* Assets collected or annotated by faculty
Example:
/api/course/ | 62598fbe1f5feb6acb162e1e |
class GANModule(nn.Module): <NEW_LINE> <INDENT> def __init__(self, generator:nn.Module=None, critic:nn.Module=None, gen_mode:bool=False): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.gen_mode = gen_mode <NEW_LINE> if generator: self.generator,self.critic = generator,critic <NEW_LINE> <DEDENT> def forward(self, *args): <NEW_LINE> <INDENT> return self.generator(*args) if self.gen_mode else self.critic(*args) <NEW_LINE> <DEDENT> def switch(self, gen_mode:bool=None): <NEW_LINE> <INDENT> self.gen_mode = (not self.gen_mode) if gen_mode is None else gen_mode | Wrapper around a `generator` and a `critic` to create a GAN. | 62598fbe3d592f4c4edbb0bd |
class Customer(): <NEW_LINE> <INDENT> def __init__(self, name, level, issue_type, issue): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.level = level <NEW_LINE> self.issue_type = issue_type <NEW_LINE> self.issue = issue <NEW_LINE> self.patience = randint(1, 100) <NEW_LINE> for i in range(0, 5): <NEW_LINE> <INDENT> if LEVEL_BOUNDS[i][0] <= self.level <= LEVEL_BOUNDS[i][1]: <NEW_LINE> <INDENT> low = LEVEL_BOUNDS[i][0] <NEW_LINE> if low <= 0: <NEW_LINE> <INDENT> low = 1 <NEW_LINE> <DEDENT> self.exp = randint(low, LEVEL_BOUNDS[i][1]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.name + " is level " + str(self.level) + "\nIssue type: " + self.issue_type + "\nIssue: " + self.issue + "\nPatience: " + str(self.patience) + "%" + "\nExperience available: " + str(self.exp) + "\n" <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def lose_patience(self): <NEW_LINE> <INDENT> self.patience -= randint(1, 3) | Defines the customer object | 62598fbe71ff763f4b5e797a |
class ViCommandDefBase(object): <NEW_LINE> <INDENT> _serializable = ['_inp',] <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.command = '<unset>' <NEW_LINE> self.input_parser = None <NEW_LINE> self._inp = '' <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> return self.__dict__[key] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '<{0} ({1})>'.format(self.__class__.__qualname__, self.command) <NEW_LINE> <DEDENT> @property <NEW_LINE> def accept_input(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> @property <NEW_LINE> def inp(self): <NEW_LINE> <INDENT> return self._inp <NEW_LINE> <DEDENT> def accept(self, key): <NEW_LINE> <INDENT> _name = self.__class__.__name__ <NEW_LINE> assert self.input_parser, '{0} does not provide an input parser'.format(_name) <NEW_LINE> raise NotImplementedError( '{0} must implement .accept()'.format(_name)) <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self._inp = '' <NEW_LINE> <DEDENT> def translate(self, state): <NEW_LINE> <INDENT> raise NotImplementedError('command {0} must implement .translate()' .format(self.__class__.__name__) ) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_json(cls, data): <NEW_LINE> <INDENT> instance = cls() <NEW_LINE> instance.__dict__.update(data) <NEW_LINE> return instance <NEW_LINE> <DEDENT> def serialize(self): <NEW_LINE> <INDENT> data = {'name': self.__class__.__name__, 'data': {k: v for k, v in self.__dict__.items() if k in self._serializable} } <NEW_LINE> return data | Base class for all Vim commands. | 62598fbe60cbc95b0636453b |
class HostState(BASE, StateMixin): <NEW_LINE> <INDENT> __tablename__ = 'host_state' <NEW_LINE> id = Column( Integer, ForeignKey('host.id', onupdate='CASCADE', ondelete='CASCADE'), primary_key=True ) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return 'HostState[%s state %s percentage %s]' % ( self.id, self.state, self.percentage ) <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> super(HostState, self).update() <NEW_LINE> host = self.host <NEW_LINE> if self.state == 'INSTALLING': <NEW_LINE> <INDENT> host.reinstall_os = False <NEW_LINE> for clusterhost in self.host.clusterhosts: <NEW_LINE> <INDENT> if clusterhost.state in [ 'SUCCESSFUL', 'ERROR' ]: <NEW_LINE> <INDENT> clusterhost.state = 'INSTALLING' <NEW_LINE> clusterhost.state.update() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> elif self.state == 'UNINITIALIZED': <NEW_LINE> <INDENT> for clusterhost in self.host.clusterhosts: <NEW_LINE> <INDENT> if clusterhost.state in [ 'INITIALIZED', 'INSTALLING', 'SUCCESSFUL', 'ERROR' ]: <NEW_LINE> <INDENT> clusterhost.state = 'UNINITIALIZED' <NEW_LINE> clusterhost.state.update() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> elif self.state == 'INITIALIZED': <NEW_LINE> <INDENT> for clusterhost in self.host.clusterhosts: <NEW_LINE> <INDENT> if clusterhost.state in [ 'INSTALLING', 'SUCCESSFUL', 'ERROR' ]: <NEW_LINE> <INDENT> clusterhost.state = 'INITIALIZED' <NEW_LINE> clusterhost.state.update() | Host state table. | 62598fbe55399d3f05626715 |
class OptActionQuiet(ActionExt): <NEW_LINE> <INDENT> def __init__(self, option_strings, dest, nargs=None, **kwargs): <NEW_LINE> <INDENT> super(OptActionQuiet, self).__init__( option_strings, dest, nargs, **kwargs) <NEW_LINE> <DEDENT> def call(self, parser, namespace, values, option_string=None): <NEW_LINE> <INDENT> namespace.quiet = True | Suppress output
--quiet | 62598fbe656771135c48986e |
class RepoReprTests(RepoTests): <NEW_LINE> <INDENT> def test_repr_works_correctly(self): <NEW_LINE> <INDENT> repo = Repo('/path/to/existing/repository') <NEW_LINE> repo_repr = repr(repo) <NEW_LINE> self.assertIsInstance(repo_repr, str) <NEW_LINE> self.assertEqual(eval(repo_repr), repo) | Tests for Repo.__repr__(). | 62598fbe5fdd1c0f98e5e191 |
class Postnet(torch.nn.Module): <NEW_LINE> <INDENT> def __init__( self, idim: int, odim: int, n_layers: int = 5, n_chans: int = 512, n_filts: int = 5, dropout_rate: float = 0.5, use_batch_norm: bool = True, ): <NEW_LINE> <INDENT> super(Postnet, self).__init__() <NEW_LINE> self.postnet = torch.nn.ModuleList() <NEW_LINE> for layer in range(n_layers - 1): <NEW_LINE> <INDENT> ichans = odim if layer == 0 else n_chans <NEW_LINE> ochans = odim if layer == n_layers - 1 else n_chans <NEW_LINE> if use_batch_norm: <NEW_LINE> <INDENT> self.postnet += [ torch.nn.Sequential( torch.nn.Conv1d( ichans, ochans, n_filts, stride=1, padding=(n_filts - 1) // 2, bias=False, ), torch.nn.BatchNorm1d(ochans), torch.nn.Tanh(), torch.nn.Dropout(dropout_rate), ) ] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.postnet += [ torch.nn.Sequential( torch.nn.Conv1d( ichans, ochans, n_filts, stride=1, padding=(n_filts - 1) // 2, bias=False, ), torch.nn.Tanh(), torch.nn.Dropout(dropout_rate), ) ] <NEW_LINE> <DEDENT> <DEDENT> ichans = n_chans if n_layers != 1 else odim <NEW_LINE> if use_batch_norm: <NEW_LINE> <INDENT> self.postnet += [ torch.nn.Sequential( torch.nn.Conv1d( ichans, odim, n_filts, stride=1, padding=(n_filts - 1) // 2, bias=False, ), torch.nn.BatchNorm1d(odim), torch.nn.Dropout(dropout_rate), ) ] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.postnet += [ torch.nn.Sequential( torch.nn.Conv1d( ichans, odim, n_filts, stride=1, padding=(n_filts - 1) // 2, bias=False, ), torch.nn.Dropout(dropout_rate), ) ] <NEW_LINE> <DEDENT> <DEDENT> def forward(self, xs): <NEW_LINE> <INDENT> for postnet in self.postnet: <NEW_LINE> <INDENT> xs = postnet(xs) <NEW_LINE> <DEDENT> return xs | Postnet module for Spectrogram prediction network.
This is a module of Postnet in Spectrogram prediction network,
which described in `Natural TTS Synthesis by
Conditioning WaveNet on Mel Spectrogram Predictions`_.
The Postnet predicts refines the predicted
Mel-filterbank of the decoder,
which helps to compensate the detail sturcture of spectrogram.
.. _`Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions`:
https://arxiv.org/abs/1712.05884 | 62598fbe4f6381625f1995c1 |
class CIFARDataset(Dataset): <NEW_LINE> <INDENT> def __init__(self, x, y, normal_class): <NEW_LINE> <INDENT> self.x = x <NEW_LINE> self.y = (y != normal_class).astype(float) <NEW_LINE> self.transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), ]) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return self.x.shape[0] <NEW_LINE> <DEDENT> def __dim__(self): <NEW_LINE> <INDENT> return self.x.shape[1:] <NEW_LINE> <DEDENT> def __getitem__(self, idx): <NEW_LINE> <INDENT> return ( self.transform(self.x[idx, :, :, :]), torch.from_numpy(np.array(self.y[idx])), torch.from_numpy(np.array(self.y[idx])), ) <NEW_LINE> <DEDENT> def __sample__(self, num): <NEW_LINE> <INDENT> len = self.__len__() <NEW_LINE> index = np.random.choice(len, num, replace=False) <NEW_LINE> return self.__getitem__(index) <NEW_LINE> <DEDENT> def __anomalyratio__(self): <NEW_LINE> <INDENT> return self.y.sum() / self.y.shape[0] | load synthetic time series data | 62598fbe4428ac0f6e658723 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.