code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class MAVLink_battery_status_message(MAVLink_message): <NEW_LINE> <INDENT> def __init__(self, accu_id, voltage_cell_1, voltage_cell_2, voltage_cell_3, voltage_cell_4, voltage_cell_5, voltage_cell_6, current_battery, current_consumed, energy_consumed, battery_remaining): <NEW_LINE> <INDENT> MAVLink_message.__init__(self, MAVLINK_MSG_ID_BATTERY_STATUS, 'BATTERY_STATUS') <NEW_LINE> self._fieldnames = ['accu_id', 'voltage_cell_1', 'voltage_cell_2', 'voltage_cell_3', 'voltage_cell_4', 'voltage_cell_5', 'voltage_cell_6', 'current_battery', 'current_consumed', 'energy_consumed', 'battery_remaining'] <NEW_LINE> self.accu_id = accu_id <NEW_LINE> self.voltage_cell_1 = voltage_cell_1 <NEW_LINE> self.voltage_cell_2 = voltage_cell_2 <NEW_LINE> self.voltage_cell_3 = voltage_cell_3 <NEW_LINE> self.voltage_cell_4 = voltage_cell_4 <NEW_LINE> self.voltage_cell_5 = voltage_cell_5 <NEW_LINE> self.voltage_cell_6 = voltage_cell_6 <NEW_LINE> self.current_battery = current_battery <NEW_LINE> self.current_consumed = current_consumed <NEW_LINE> self.energy_consumed = energy_consumed <NEW_LINE> self.battery_remaining = battery_remaining <NEW_LINE> <DEDENT> def pack(self, mav): <NEW_LINE> <INDENT> return MAVLink_message.pack(self, mav, 177, struct.pack('<iiHHHHHHhBb', self.current_consumed, self.energy_consumed, self.voltage_cell_1, self.voltage_cell_2, self.voltage_cell_3, self.voltage_cell_4, self.voltage_cell_5, self.voltage_cell_6, self.current_battery, self.accu_id, self.battery_remaining))
Transmitte battery informations for a accu pack.
62598fb13539df3088ecc308
class PrivateGeneralTypeSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = PrivateGeneralType <NEW_LINE> fields = ('id', 'active', 'value', 'hour', 'terms',) <NEW_LINE> read_only_fields = ('id',)
Serializer to represent the Private general type classes model
62598fb1fff4ab517ebcd83b
class PerViewThrottling(BaseThrottle): <NEW_LINE> <INDENT> def get_cache_key(self): <NEW_LINE> <INDENT> return 'throttle_view_%s' % self.view.__class__.__name__
Limits the rate of API calls that may be used on a given view. The class name of the view is used as a unique identifier to throttle against.
62598fb14527f215b58e9f2b
class Conv1x1Branch(nn.Module): <NEW_LINE> <INDENT> def __init__(self, in_channels, out_channels): <NEW_LINE> <INDENT> super(Conv1x1Branch, self).__init__() <NEW_LINE> self.conv = incept_conv1x1( in_channels=in_channels, out_channels=out_channels) <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> x = self.conv(x) <NEW_LINE> return x
InceptionV3 specific convolutional 1x1 branch block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels.
62598fb17d43ff248742742d
class InputReadersTest(module_testutil.ModuleInterfaceTest, googletest.TestCase): <NEW_LINE> <INDENT> MODULE = input_readers
Test input_readers module interface.
62598fb1a05bb46b3848a8c2
class Call(BaseMixin, db.Model): <NEW_LINE> <INDENT> __tablename__ = u'telephony_call' <NEW_LINE> call_uuid = db.Column(db.String(100)) <NEW_LINE> start_time = db.Column(db.DateTime) <NEW_LINE> end_time = db.Column(db.DateTime) <NEW_LINE> from_phonenumber_id = db.Column(db.ForeignKey('telephony_phonenumber.id')) <NEW_LINE> to_phonenumber_id = db.Column(db.ForeignKey('telephony_phonenumber.id')) <NEW_LINE> a_leg_uuid = db.Column(db.String(100)) <NEW_LINE> a_leg_request_uuid = db.Column(db.String(100)) <NEW_LINE> onairprogram_id = db.Column(db.ForeignKey('onair_program.id')) <NEW_LINE> from_phonenumber = db.relationship(u'PhoneNumber', primaryjoin='Call.from_phonenumber_id == PhoneNumber.id') <NEW_LINE> to_phonenumber = db.relationship(u'PhoneNumber', primaryjoin='Call.to_phonenumber_id == PhoneNumber.id')
An incoming or outgoing call from the telephony system. Defined here for easy readability by the web server, but should not be written to in this process.
62598fb166673b3332c30422
class FluidSynthPlayer(Player): <NEW_LINE> <INDENT> def __init__(self, config, section, main_loop): <NEW_LINE> <INDENT> self._encoding = locale.getpreferredencoding(False) <NEW_LINE> self._subprocess = None <NEW_LINE> self._supervisor = None <NEW_LINE> super().__init__(config, section, main_loop) <NEW_LINE> self._command = config[section].get("command", "fluidsynth") <NEW_LINE> self._audio_driver = config[section].get("audio_driver", None) <NEW_LINE> self._extra_options = config[section].get("extra_options", None) <NEW_LINE> try: <NEW_LINE> <INDENT> self._soundfont = config[section]["soundfont"] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise PlayerLoadError("SoundFont not provided") <NEW_LINE> <DEDENT> if not os.path.exists(self._soundfont): <NEW_LINE> <INDENT> raise PlayerLoadError("SoundFont file %r does not exist", self._soundfont) <NEW_LINE> <DEDENT> command = self._command.split() <NEW_LINE> command.append("-n") <NEW_LINE> if self._audio_driver: <NEW_LINE> <INDENT> command += ["-a", self._audio_driver] <NEW_LINE> <DEDENT> if self._extra_options: <NEW_LINE> <INDENT> command += self._extra_options.split(" ") <NEW_LINE> <DEDENT> command.append(self._soundfont) <NEW_LINE> logger.debug("Starting %r", " ".join(command)) <NEW_LINE> create = asyncio.subprocess.create_subprocess_exec( *command, stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.PIPE, loop=self.main_loop) <NEW_LINE> task = self.main_loop.create_task(create) <NEW_LINE> self._subprocess = self.main_loop.run_until_complete(task) <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> if self._subprocess or self._supervisor: <NEW_LINE> <INDENT> self.stop() <NEW_LINE> <DEDENT> <DEDENT> async def _supervise(self): <NEW_LINE> <INDENT> if self._subprocess is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> line = await self._subprocess.stderr.readline() <NEW_LINE> if not line: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> fs_logger.debug(line.rstrip().decode(self._encoding, "replace")) <NEW_LINE> <DEDENT> rc = await self._subprocess.wait() <NEW_LINE> if rc > 0: <NEW_LINE> <INDENT> logger.warning("%r exitted with status %r", self._command, rc) <NEW_LINE> <DEDENT> elif rc < 0 and rc not in (-signal.SIGTERM, -signal.SIGINT): <NEW_LINE> <INDENT> logger.warning("%r killed by signal %r", self._command, -rc) <NEW_LINE> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> self._subprocess = None <NEW_LINE> <DEDENT> <DEDENT> def start(self): <NEW_LINE> <INDENT> self._supervisor = self.main_loop.create_task(self._supervise()) <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> if self._subprocess: <NEW_LINE> <INDENT> self._subprocess.terminate() <NEW_LINE> <DEDENT> self._supervisor = None <NEW_LINE> self._subprocess = None <NEW_LINE> <DEDENT> def _send(self, command): <NEW_LINE> <INDENT> if not self._subprocess: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> command = command.encode(self._encoding, "replace") <NEW_LINE> self._subprocess.stdin.write(command) <NEW_LINE> <DEDENT> def handle_message(self, msg): <NEW_LINE> <INDENT> if isinstance(msg, midi.NoteOn): <NEW_LINE> <INDENT> self._send("noteon {} {} {}\n" .format(msg.channel - 1, msg.note, msg.velocity)) <NEW_LINE> <DEDENT> elif isinstance(msg, midi.NoteOff): <NEW_LINE> <INDENT> self._send("noteoff {} {} {}\n" .format(msg.channel - 1, msg.note, msg.velocity)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logger.debug("Unsupported message: %r", msg)
FluidSynt MIDI player. Sends MIDI notes to a FluidSynth process.
62598fb130dc7b766599f8a3
@parser(Specs.docker_info) <NEW_LINE> class DockerInfo(Parser): <NEW_LINE> <INDENT> def parse_content(self, content): <NEW_LINE> <INDENT> self.data = {} <NEW_LINE> if len(content) >= 10: <NEW_LINE> <INDENT> for line in content: <NEW_LINE> <INDENT> if ":" in line: <NEW_LINE> <INDENT> key, value = line.strip().split(":", 1) <NEW_LINE> value = value.strip() <NEW_LINE> value = value if value else None <NEW_LINE> self.data[key.strip()] = value
Represents the output of the ``/usr/bin/docker info`` command. The resulting output of the command is essentially key/value pairs.
62598fb15fcc89381b266177
class InlineForm(LayoutObject): <NEW_LINE> <INDENT> template = 'trionyx/forms/inlineform.html' <NEW_LINE> def __init__(self, form_name, template=None): <NEW_LINE> <INDENT> self.form_name = form_name <NEW_LINE> if template: <NEW_LINE> <INDENT> self.template = template <NEW_LINE> <DEDENT> <DEDENT> def render(self, form, form_style, context, template_pack=TEMPLATE_PACK): <NEW_LINE> <INDENT> inline_form = form.get_inline_forms()[self.form_name] <NEW_LINE> if hasattr(inline_form, 'forms'): <NEW_LINE> <INDENT> config = models_config.get_config(inline_form.form._meta.model) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> config = models_config.get_config(inline_form._meta.model) <NEW_LINE> <DEDENT> return render_to_string(self.template, { 'inline_form_prefix': self.form_name, 'inline_form_verbose_name': config.get_verbose_name(), 'inline_form': inline_form, }, utils.get_current_request())
Layout renderer for inline forms
62598fb1cc40096d6161a204
class TaskLogicVocabularyFactory(object): <NEW_LINE> <INDENT> provides_interface = None <NEW_LINE> def __call__(self, context): <NEW_LINE> <INDENT> gsm = getGlobalSiteManager() <NEW_LINE> scheduled_interfaces = context.get_scheduled_interfaces() <NEW_LINE> terms = [] <NEW_LINE> for scheduled_interface in scheduled_interfaces: <NEW_LINE> <INDENT> for adapter in gsm.registeredAdapters(): <NEW_LINE> <INDENT> implements_interface = issubclass(adapter.provided, ITaskLogic) and issubclass(self.provides_interface, adapter.provided) <NEW_LINE> specific_enough = adapter.required[0].implementedBy(scheduled_interface) or issubclass(scheduled_interface, adapter.required[0]) <NEW_LINE> if implements_interface and specific_enough: <NEW_LINE> <INDENT> terms.append( SimpleTerm(adapter.name, adapter.name, _(adapter.name)) ) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> vocabulary = SimpleVocabulary(terms) <NEW_LINE> return vocabulary
Base class for vocabulary factories listing adapters providing some ITaskLogic (sub)interface and adapting a task container content type.
62598fb191f36d47f2230ed2
@with_slots <NEW_LINE> class EvenlyDiscretizedMFD(BaseMFD): <NEW_LINE> <INDENT> MODIFICATIONS = set() <NEW_LINE> __slots__ = 'min_mag bin_width occurrence_rates'.split() <NEW_LINE> def __init__(self, min_mag, bin_width, occurrence_rates): <NEW_LINE> <INDENT> self.min_mag = min_mag <NEW_LINE> self.bin_width = bin_width <NEW_LINE> self.occurrence_rates = occurrence_rates <NEW_LINE> self.check_constraints() <NEW_LINE> <DEDENT> def check_constraints(self): <NEW_LINE> <INDENT> if not self.bin_width > 0: <NEW_LINE> <INDENT> raise ValueError('bin width must be positive') <NEW_LINE> <DEDENT> if not self.occurrence_rates: <NEW_LINE> <INDENT> raise ValueError('at least one bin must be specified') <NEW_LINE> <DEDENT> if not all(value >= 0 for value in self.occurrence_rates): <NEW_LINE> <INDENT> raise ValueError('all occurrence rates must not be negative') <NEW_LINE> <DEDENT> if not any(value > 0 for value in self.occurrence_rates): <NEW_LINE> <INDENT> raise ValueError('at least one occurrence rate must be positive') <NEW_LINE> <DEDENT> if not self.min_mag >= 0: <NEW_LINE> <INDENT> raise ValueError('minimum magnitude must be non-negative') <NEW_LINE> <DEDENT> <DEDENT> def get_annual_occurrence_rates(self): <NEW_LINE> <INDENT> return [(self.min_mag + i * self.bin_width, occurrence_rate) for i, occurrence_rate in enumerate(self.occurrence_rates)] <NEW_LINE> <DEDENT> def get_min_mag(self): <NEW_LINE> <INDENT> return self.min_mag
Evenly discretized MFD is defined as a precalculated histogram. :param min_mag: Positive float value representing the middle point of the first bin in the histogram. :param bin_width: A positive float value -- the width of a single histogram bin. :param occurrence_rates: The list of non-negative float values representing the actual annual occurrence rates. The resulting histogram has as many bins as this list length.
62598fb1442bda511e95c4ae
class Locacao(object): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def validar(cls): <NEW_LINE> <INDENT> return {}
Classe de negocio responsavel pelos dados da locacao.
62598fb1379a373c97d9906b
class IntegerToolParameter(TextToolParameter): <NEW_LINE> <INDENT> dict_collection_visible_keys = ToolParameter.dict_collection_visible_keys + ['min', 'max'] <NEW_LINE> def __init__(self, tool, input_source): <NEW_LINE> <INDENT> input_source = ensure_input_source(input_source) <NEW_LINE> TextToolParameter.__init__(self, tool, input_source) <NEW_LINE> if self.value: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> int(self.value) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise ValueError("An integer is required") <NEW_LINE> <DEDENT> <DEDENT> elif self.value is None and not self.optional: <NEW_LINE> <INDENT> raise ValueError("The settings for the field named '%s' require a 'value' setting and optionally a default value which must be an integer" % self.name) <NEW_LINE> <DEDENT> self.min = input_source.get('min') <NEW_LINE> self.max = input_source.get('max') <NEW_LINE> if self.min: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.min = int(self.min) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise ValueError("An integer is required") <NEW_LINE> <DEDENT> <DEDENT> if self.max: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.max = int(self.max) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise ValueError("An integer is required") <NEW_LINE> <DEDENT> <DEDENT> if self.min is not None or self.max is not None: <NEW_LINE> <INDENT> self.validators.append(validation.InRangeValidator(None, self.min, self.max)) <NEW_LINE> <DEDENT> <DEDENT> def from_json(self, value, trans, other_values={}): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return int(value) <NEW_LINE> <DEDENT> except (TypeError, ValueError): <NEW_LINE> <INDENT> if contains_workflow_parameter(value) and trans.workflow_building_mode is workflow_building_modes.ENABLED: <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> if not value and self.optional: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> if trans.workflow_building_mode is workflow_building_modes.ENABLED: <NEW_LINE> <INDENT> raise ValueError("An integer or workflow parameter e.g. ${name} is required") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("An integer is required") <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def to_python(self, value, app): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return int(value) <NEW_LINE> <DEDENT> except (TypeError, ValueError) as err: <NEW_LINE> <INDENT> if contains_workflow_parameter(value): <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> if not value and self.optional: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> raise err <NEW_LINE> <DEDENT> <DEDENT> def get_initial_value(self, trans, other_values): <NEW_LINE> <INDENT> if self.value: <NEW_LINE> <INDENT> return int(self.value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None
Parameter that takes an integer value. >>> from galaxy.util.bunch import Bunch >>> trans = Bunch(app=None, history=Bunch(), workflow_building_mode=True) >>> p = IntegerToolParameter(None, XML('<param name="_name" type="integer" value="10" />')) >>> print(p.name) _name >>> sorted(p.to_dict(trans).items()) [('area', False), ('argument', None), ('datalist', []), ('help', ''), ('hidden', False), ('is_dynamic', False), ('label', ''), ('max', None), ('min', None), ('model_class', 'IntegerToolParameter'), ('name', '_name'), ('optional', False), ('refresh_on_change', False), ('type', 'integer'), ('value', '10')] >>> type(p.from_json("10", trans)) <type 'int'> >>> type(p.from_json("_string", trans)) Traceback (most recent call last): ... ValueError: An integer or workflow parameter e.g. ${name} is required
62598fb1f548e778e596b5fa
class TMAClassifier(BaseTMA): <NEW_LINE> <INDENT> def __init__(self, pom_treat: ClassifierMixin, pom_control: ClassifierMixin, name: Optional[str]=None) -> None: <NEW_LINE> <INDENT> if not isinstance(pom_treat, ClassifierMixin): <NEW_LINE> <INDENT> raise TypeError("set Classifier as pom_treat.") <NEW_LINE> <DEDENT> if not isinstance(pom_control, ClassifierMixin): <NEW_LINE> <INDENT> raise TypeError("set Classifier as pom_control.") <NEW_LINE> <DEDENT> super().__init__(pom_treat, pom_control, name) <NEW_LINE> <DEDENT> def predict(self, X: np.ndarray) -> np.ndarray: <NEW_LINE> <INDENT> X = check_array(X, accept_sparse=('csr', 'csc'), dtype=[int, float]) <NEW_LINE> self.pred_treat, self.pred_control = self.pom_treat.predict_proba(X)[:, 1], self.pom_control.predict_proba(X)[:, 1] <NEW_LINE> ite_pred = self.pred_treat - self.pred_control <NEW_LINE> return ite_pred
Two-Model Approach for Classification.
62598fb1aad79263cf42e829
class StochasticEncoderLayer(nn.Module): <NEW_LINE> <INDENT> def __init__(self, size, self_attn, feed_forward, dropout_rate, death_rate=0.0, normalize_before=True, concat_after=False): <NEW_LINE> <INDENT> super(StochasticEncoderLayer, self).__init__() <NEW_LINE> self.self_attn = self_attn <NEW_LINE> self.feed_forward = feed_forward <NEW_LINE> self.norm1 = LayerNorm(size) <NEW_LINE> self.norm2 = LayerNorm(size) <NEW_LINE> self.dropout = nn.Dropout(dropout_rate) <NEW_LINE> self.death_rate = death_rate <NEW_LINE> self.size = size <NEW_LINE> self.normalize_before = normalize_before <NEW_LINE> self.concat_after = concat_after <NEW_LINE> if self.concat_after: <NEW_LINE> <INDENT> self.concat_linear = nn.Linear(size + size, size) <NEW_LINE> <DEDENT> <DEDENT> def forward(self, x, mask): <NEW_LINE> <INDENT> coin = True <NEW_LINE> if self.training: <NEW_LINE> <INDENT> coin = (torch.rand(1)[0].item() >= self.death_rate) <NEW_LINE> <DEDENT> residual = x <NEW_LINE> if self.normalize_before: <NEW_LINE> <INDENT> x = self.norm1(x) <NEW_LINE> <DEDENT> if self.concat_after: <NEW_LINE> <INDENT> x_concat = torch.cat((x, self.self_attn(x, x, x, mask)), dim=-1) <NEW_LINE> if not coin: <NEW_LINE> <INDENT> x = residual + self.concat_linear(x_concat) * 0.0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self.training: <NEW_LINE> <INDENT> x = residual + self.concat_linear(x_concat) / (1 - self.death_rate) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> x = residual + self.concat_linear(x_concat) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if not coin: <NEW_LINE> <INDENT> x = residual + self.dropout(self.self_attn(x, x, x, mask)) * 0.0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self.training: <NEW_LINE> <INDENT> x = residual + self.dropout(self.self_attn(x, x, x, mask)) / (1 - self.death_rate) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> x = residual + self.dropout(self.self_attn(x, x, x, mask)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if not self.normalize_before: <NEW_LINE> <INDENT> x = self.norm1(x) <NEW_LINE> <DEDENT> residual = x <NEW_LINE> if self.normalize_before: <NEW_LINE> <INDENT> x = self.norm2(x) <NEW_LINE> <DEDENT> if not coin: <NEW_LINE> <INDENT> x = residual + self.dropout(self.feed_forward(x)) * 0.0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self.training: <NEW_LINE> <INDENT> x = residual + self.dropout(self.feed_forward(x)) / (1 - self.death_rate) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> x = residual + self.dropout(self.feed_forward(x)) <NEW_LINE> <DEDENT> <DEDENT> if not self.normalize_before: <NEW_LINE> <INDENT> x = self.norm2(x) <NEW_LINE> <DEDENT> return x, mask
Encoder layer module. :param int size: input dim :param espnet.nets.pytorch_backend.transformer.attention.MultiHeadedAttention self_attn: self attention module :param espnet.nets.pytorch_backend.transformer.positionwise_feed_forward.PositionwiseFeedForward feed_forward: feed forward module :param float dropout_rate: dropout rate :param bool normalize_before: whether to use layer_norm before the first block :param bool concat_after: whether to concat attention layer's input and output if True, additional linear will be applied. i.e. x -> x + linear(concat(x, att(x))) if False, no additional linear will be applied. i.e. x -> x + att(x)
62598fb15166f23b2e243430
class TableSelectMultiple(forms.widgets.SelectMultiple): <NEW_LINE> <INDENT> def __init__(self, item_attrs, grouper, *args, **kwargs): <NEW_LINE> <INDENT> super(TableSelectMultiple, self).__init__(*args, **kwargs) <NEW_LINE> self.item_attrs = item_attrs <NEW_LINE> if grouper is None: <NEW_LINE> <INDENT> self.grouper = None <NEW_LINE> self.group_label = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.grouper, self.group_label = grouper <NEW_LINE> <DEDENT> <DEDENT> def render(self, name, value, attrs=None, choices=()): <NEW_LINE> <INDENT> if value is None: <NEW_LINE> <INDENT> value = [] <NEW_LINE> <DEDENT> id = attrs['id'] <NEW_LINE> final_attrs = self.build_attrs(attrs, name=name) <NEW_LINE> output = ['<table id="%s">' % id] <NEW_LINE> str_values = set([force_unicode(v) for v in value]) <NEW_LINE> parent = None <NEW_LINE> parent_id = '%s-p-%%d' % id <NEW_LINE> colspan = len(self.item_attrs) + 1 <NEW_LINE> for i, (option_value, item) in enumerate(self.choices): <NEW_LINE> <INDENT> if self.grouper: <NEW_LINE> <INDENT> grouper = getattr(item, self.grouper, None) <NEW_LINE> if grouper: <NEW_LINE> <INDENT> if grouper.id != parent: <NEW_LINE> <INDENT> parent = grouper.id <NEW_LINE> label = getattr(grouper, self.group_label) <NEW_LINE> child = ' class="child-of-%s"' % (parent_id % parent) <NEW_LINE> output.append(u'<tr id="%s"><td colspan="%d">%s</td></tr>' % (parent_id % parent, colspan, label)) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> parent = None <NEW_LINE> child = '' <NEW_LINE> <DEDENT> <DEDENT> final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i)) <NEW_LINE> cb = forms.widgets.CheckboxInput(final_attrs, check_test=lambda value: value in str_values) <NEW_LINE> option_value = force_unicode(option_value) <NEW_LINE> rendered_cb = cb.render(name, option_value) <NEW_LINE> output.append(u'<tr%s><td>%s</td>' % (child, rendered_cb)) <NEW_LINE> for attr in self.item_attrs: <NEW_LINE> <INDENT> if callable(getattr(item, attr)): <NEW_LINE> <INDENT> content = getattr(item, attr)() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> content = getattr(item, attr) <NEW_LINE> <DEDENT> output.append(u'<td>%s</td>' % escape(content)) <NEW_LINE> <DEDENT> output.append(u'</tr>') <NEW_LINE> <DEDENT> output.append('</table>') <NEW_LINE> return mark_safe(u'\n'.join(output))
Provides selection of items via checkboxes, with a table row being rendered for each item, the first cell in which contains the checkbox. When providing choices for this field, give the item as the second item in all choice tuples. For example, where you might have previously used:: field.choices = [(item.id, item.name) for item in item_list] ...you should use:: field.choices = [(item.id, item) for item in item_list]
62598fb1a219f33f346c686c
class Visitor(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._travelled = set() <NEW_LINE> <DEDENT> def travel(self, src, dst): <NEW_LINE> <INDENT> src_path = src.path if src else '' <NEW_LINE> edge = src_path + ',' + dst.path <NEW_LINE> if edge in self._travelled: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._travelled.add(edge) <NEW_LINE> self._travel(src, dst) <NEW_LINE> return True
Base class for visitors used to traverse the dependency graph.
62598fb1283ffb24f3cf38e3
class Test_strS(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> Base._Base__nb_objects = 0 <NEW_LINE> <DEDENT> def test_str1S(self): <NEW_LINE> <INDENT> s1 = Square(2) <NEW_LINE> st = "[Square] (1) 0/0 - 2" <NEW_LINE> strP = str(s1) <NEW_LINE> self.assertEqual(st, strP) <NEW_LINE> with patch('sys.stdout', new=io.StringIO()) as p: <NEW_LINE> <INDENT> print(s1, end='') <NEW_LINE> pr = p.getvalue() <NEW_LINE> <DEDENT> self.assertEqual(st, pr) <NEW_LINE> <DEDENT> def test_str2S(self): <NEW_LINE> <INDENT> s1 = Square(3, 5) <NEW_LINE> st = "[Square] (1) 5/0 - 3" <NEW_LINE> strP = str(s1) <NEW_LINE> self.assertEqual(st, strP) <NEW_LINE> with patch('sys.stdout', new=io.StringIO()) as p: <NEW_LINE> <INDENT> print(s1, end='') <NEW_LINE> pr = p.getvalue() <NEW_LINE> <DEDENT> self.assertEqual(st, pr) <NEW_LINE> <DEDENT> def test_str3S(self): <NEW_LINE> <INDENT> s1 = Square(2, 5, 6) <NEW_LINE> st = "[Square] (1) 5/6 - 2" <NEW_LINE> strP = str(s1) <NEW_LINE> self.assertEqual(st, strP) <NEW_LINE> with patch('sys.stdout', new=io.StringIO()) as p: <NEW_LINE> <INDENT> print(s1, end='') <NEW_LINE> pr = p.getvalue() <NEW_LINE> <DEDENT> self.assertEqual(st, pr) <NEW_LINE> <DEDENT> def test_str4S(self): <NEW_LINE> <INDENT> s1 = Square(3, 5, 6, 85) <NEW_LINE> st = "[Square] (85) 5/6 - 3" <NEW_LINE> strP = str(s1) <NEW_LINE> self.assertEqual(st, strP) <NEW_LINE> with patch('sys.stdout', new=io.StringIO()) as p: <NEW_LINE> <INDENT> print(s1, end='') <NEW_LINE> pr = p.getvalue() <NEW_LINE> <DEDENT> self.assertEqual(st, pr) <NEW_LINE> <DEDENT> def test_str5S(self): <NEW_LINE> <INDENT> s1 = Square(3, 5, 6, 85) <NEW_LINE> s1.id = 9 <NEW_LINE> s1.x = 8 <NEW_LINE> s1.y = 7 <NEW_LINE> s1.size = 6 <NEW_LINE> st = "[Square] (9) 8/7 - 6" <NEW_LINE> strP = str(s1) <NEW_LINE> self.assertEqual(st, strP) <NEW_LINE> with patch('sys.stdout', new=io.StringIO()) as p: <NEW_LINE> <INDENT> print(s1, end='') <NEW_LINE> pr = p.getvalue() <NEW_LINE> <DEDENT> self.assertEqual(st, pr)
Class for unittest of __str__ method
62598fb1a8370b77170f0432
class Error(Exception): <NEW_LINE> <INDENT> def __init__(self, message): <NEW_LINE> <INDENT> Exception.__init__(self, message) <NEW_LINE> self.message = message
Used to catch parser.error.
62598fb17d847024c075c418
class ProxyInputSource(InputSource): <NEW_LINE> <INDENT> def __init__(self, input): <NEW_LINE> <INDENT> assert isinstance(input, InputSource), input <NEW_LINE> self._input = input <NEW_LINE> <DEDENT> def _get_input_tensors(self): <NEW_LINE> <INDENT> return self._input.get_input_tensors() <NEW_LINE> <DEDENT> def _setup(self, inputs_desc): <NEW_LINE> <INDENT> self._input.setup(inputs_desc) <NEW_LINE> <DEDENT> def _get_callbacks(self): <NEW_LINE> <INDENT> return self._input.get_callbacks() <NEW_LINE> <DEDENT> def _size(self): <NEW_LINE> <INDENT> return self._input.size() <NEW_LINE> <DEDENT> def _reset_state(self): <NEW_LINE> <INDENT> self._input.reset_state()
An InputSource which proxy every method to ``self._input``.
62598fb1e5267d203ee6b95f
class KMtronicSwitch(CoordinatorEntity, SwitchEntity): <NEW_LINE> <INDENT> def __init__(self, coordinator, relay, reverse, config_entry_id): <NEW_LINE> <INDENT> super().__init__(coordinator) <NEW_LINE> self._relay = relay <NEW_LINE> self._config_entry_id = config_entry_id <NEW_LINE> self._reverse = reverse <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self) -> str: <NEW_LINE> <INDENT> return f"Relay{self._relay.id}" <NEW_LINE> <DEDENT> @property <NEW_LINE> def unique_id(self) -> str: <NEW_LINE> <INDENT> return f"{self._config_entry_id}_relay{self._relay.id}" <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_on(self): <NEW_LINE> <INDENT> if self._reverse: <NEW_LINE> <INDENT> return not self._relay.is_energised <NEW_LINE> <DEDENT> return self._relay.is_energised <NEW_LINE> <DEDENT> async def async_turn_on(self, **kwargs) -> None: <NEW_LINE> <INDENT> if self._reverse: <NEW_LINE> <INDENT> await self._relay.de_energise() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> await self._relay.energise() <NEW_LINE> <DEDENT> self.async_write_ha_state() <NEW_LINE> <DEDENT> async def async_turn_off(self, **kwargs) -> None: <NEW_LINE> <INDENT> if self._reverse: <NEW_LINE> <INDENT> await self._relay.energise() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> await self._relay.de_energise() <NEW_LINE> <DEDENT> self.async_write_ha_state() <NEW_LINE> <DEDENT> async def async_toggle(self, **kwargs) -> None: <NEW_LINE> <INDENT> await self._relay.toggle() <NEW_LINE> self.async_write_ha_state()
KMtronic Switch Entity.
62598fb12c8b7c6e89bd381c
class OperationExtendedInfo(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'object_type': {'required': True}, } <NEW_LINE> _attribute_map = { 'object_type': {'key': 'objectType', 'type': 'str'}, } <NEW_LINE> _subtype_map = { 'object_type': {'OperationJobExtendedInfo': 'OperationJobExtendedInfo'} } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(OperationExtendedInfo, self).__init__(**kwargs) <NEW_LINE> self.object_type = None
Operation Extended Info. You probably want to use the sub-classes and not this class directly. Known sub-classes are: OperationJobExtendedInfo. All required parameters must be populated in order to send to Azure. :param object_type: Required. This property will be used as the discriminator for deciding the specific types in the polymorphic chain of types.Constant filled by server. :type object_type: str
62598fb1a8370b77170f0433
class Tile(BaseTile, AttrToggles): <NEW_LINE> <INDENT> ship = blank = is_hit = revealed = False <NEW_LINE> hidden = True <NEW_LINE> attribute_toggles = [("hidden", "revealed")] <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return blank if self.hidden else self.char <NEW_LINE> <DEDENT> def hit(self): <NEW_LINE> <INDENT> self.is_hit = True <NEW_LINE> self.revealed = True <NEW_LINE> self.char = sunkship if self.ship else hitchar
Tile that may be a ship or blank space (water).
62598fb1d486a94d0ba2c027
class Dialect(models.Model): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> ordering = ['signlanguage', 'name'] <NEW_LINE> <DEDENT> signlanguage = models.ForeignKey(SignLanguage) <NEW_LINE> name = models.CharField(max_length=20) <NEW_LINE> description = models.TextField() <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.signlanguage.name + "/" + self.name
A dialect name - a regional dialect of a given Language
62598fb1d486a94d0ba2c026
class UpdateExpressionDeleteAction(UpdateExpressionClause): <NEW_LINE> <INDENT> pass
DeleteAction => Path Value
62598fb1a17c0f6771d5c28c
class SubmissionList_NoHTML5Iframe_IntegrationTests(NoHTML5SeleniumTestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(SubmissionList_NoHTML5Iframe_IntegrationTests, self).setUp() <NEW_LINE> self.exhibition = Exhibition.objects.create(title='New Exhibition', description='goes here', author=self.staff_user) <NEW_LINE> self.artwork = Artwork.objects.create(title='Title bar', code='// code goes here', author=self.user) <NEW_LINE> self.exhibition_path = reverse('exhibition-view', kwargs={'pk': self.exhibition.id}) <NEW_LINE> self.exhibition_url = '%s%s' % (self.live_server_url, self.exhibition_path) <NEW_LINE> <DEDENT> def test_artwork_compile_error(self): <NEW_LINE> <INDENT> bad_artwork1 = Artwork.objects.create(title='Bad test code1', code='bad code! bad!;', author=self.user) <NEW_LINE> good_artwork = Artwork.objects.create(title='Good test code1', code='// good code!', author=self.user) <NEW_LINE> bad_artwork2 = Artwork.objects.create(title='Bad test code2', code='still bad code!', author=self.user) <NEW_LINE> submission1 = Submission.objects.create(artwork=bad_artwork1, exhibition=self.exhibition, submitted_by=self.user) <NEW_LINE> submission2 = Submission.objects.create(artwork=good_artwork, exhibition=self.exhibition, submitted_by=self.user) <NEW_LINE> submission2 = Submission.objects.create(artwork=bad_artwork2, exhibition=self.exhibition, submitted_by=self.user) <NEW_LINE> with wait_for_page_load(self.selenium): <NEW_LINE> <INDENT> self.selenium.get(self.exhibition_url) <NEW_LINE> <DEDENT> self.assertEqual( len(self.selenium.find_elements_by_css_selector('.artwork')), 3 ) <NEW_LINE> self.assertFalse(self.selenium.find_element_by_id('paused-%s' % bad_artwork1.id).is_displayed()) <NEW_LINE> self.assertFalse(self.selenium.find_element_by_id('paused-%s' % good_artwork.id).is_displayed()) <NEW_LINE> self.assertFalse(self.selenium.find_element_by_id('paused-%s' % bad_artwork2.id).is_displayed()) <NEW_LINE> self.assertRaises( NoSuchElementException, self.selenium.find_element_by_tag_name, ('iframe') ) <NEW_LINE> errors = self.get_browser_log(level=u'SEVERE') <NEW_LINE> self.assertEqual(len(errors), 0) <NEW_LINE> upgradeBrowser = self.selenium.find_elements_by_css_selector('.artwork h4') <NEW_LINE> self.assertEqual(len(upgradeBrowser), 3); <NEW_LINE> self.assertEqual( upgradeBrowser[0].text, 'Please upgrade your browser' )
Tests the artwork rendering in a browser that does not support HTML5 iframe srcdoc/sandbox
62598fb130bbd722464699a4
class BertIndex2Text(BaseRecorderInterface): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(self.__class__,self).__init__() <NEW_LINE> from transformers import PreTrainedTokenizerFast <NEW_LINE> self.tokenizer = PreTrainedTokenizerFast() <NEW_LINE> <DEDENT> def forward(self, x : torch.Tensor ) -> str: <NEW_LINE> <INDENT> return self.tokenizer.convert_ids_to_tokens( x )
[summary] :param BaseRecorderInterface: [description] :type BaseRecorderInterface: [type]
62598fb1bd1bec0571e150ee
@factory_config(IAlchemyEngineUtility) <NEW_LINE> class PersistentAlchemyEngineUtility(Persistent, AlchemyEngineUtility, Contained): <NEW_LINE> <INDENT> pass
Persistent implementation of SQLAlchemy engine utility
62598fb18e7ae83300ee90fa
class PeriodicTaskAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> form = PeriodicTaskForm <NEW_LINE> model = PeriodicTask <NEW_LINE> celery_app = current_app <NEW_LINE> list_display = ('__str__', 'enabled') <NEW_LINE> actions = ('enable_tasks', 'disable_tasks', 'run_tasks') <NEW_LINE> fieldsets = ( (None, { 'fields': ('name', 'regtask', 'task', 'enabled', 'description',), 'classes': ('extrapretty', 'wide'), }), ('Schedule', { 'fields': ('interval', 'crontab', 'solar'), 'classes': ('extrapretty', 'wide', ), }), ('Arguments', { 'fields': ('args', 'kwargs'), 'classes': ('extrapretty', 'wide', 'collapse', 'in'), }), ('Execution Options', { 'fields': ('expires', 'queue', 'exchange', 'routing_key'), 'classes': ('extrapretty', 'wide', 'collapse', 'in'), }), ) <NEW_LINE> def changelist_view(self, request, extra_context=None): <NEW_LINE> <INDENT> extra_context = extra_context or {} <NEW_LINE> scheduler = getattr(settings, 'CELERY_BEAT_SCHEDULER', None) <NEW_LINE> extra_context['wrong_scheduler'] = not is_database_scheduler(scheduler) <NEW_LINE> return super(PeriodicTaskAdmin, self).changelist_view( request, extra_context) <NEW_LINE> <DEDENT> def get_queryset(self, request): <NEW_LINE> <INDENT> qs = super(PeriodicTaskAdmin, self).get_queryset(request) <NEW_LINE> return qs.select_related('interval', 'crontab', 'solar') <NEW_LINE> <DEDENT> def enable_tasks(self, request, queryset): <NEW_LINE> <INDENT> rows_updated = queryset.update(enabled=True) <NEW_LINE> PeriodicTasks.update_changed() <NEW_LINE> self.message_user( request, _('{0} task{1} {2} successfully enabled').format( rows_updated, pluralize(rows_updated), pluralize(rows_updated, _('was,were')), ), ) <NEW_LINE> <DEDENT> enable_tasks.short_description = _('Enable selected tasks') <NEW_LINE> def disable_tasks(self, request, queryset): <NEW_LINE> <INDENT> rows_updated = queryset.update(enabled=False) <NEW_LINE> PeriodicTasks.update_changed() <NEW_LINE> self.message_user( request, _('{0} task{1} {2} successfully disabled').format( rows_updated, pluralize(rows_updated), pluralize(rows_updated, _('was,were')), ), ) <NEW_LINE> <DEDENT> disable_tasks.short_description = _('Disable selected tasks') <NEW_LINE> def run_tasks(self, request, queryset): <NEW_LINE> <INDENT> self.celery_app.loader.import_default_modules() <NEW_LINE> tasks = [(self.celery_app.tasks.get(task.task), loads(task.args), loads(task.kwargs), task.queue) for task in queryset] <NEW_LINE> task_ids = [task.apply_async(args=args, kwargs=kwargs, queue=queue) if queue and len(queue) else task.apply_async(args=args, kwargs=kwargs) for task, args, kwargs, queue in tasks] <NEW_LINE> tasks_run = len(task_ids) <NEW_LINE> self.message_user( request, _('{0} task{1} {2} successfully run').format( tasks_run, pluralize(tasks_run), pluralize(tasks_run, _('was,were')), ), ) <NEW_LINE> <DEDENT> run_tasks.short_description = _('Run selected tasks')
Admin-interface for periodic tasks.
62598fb185dfad0860cbfa9f
class VipPermRelation(models.Model): <NEW_LINE> <INDENT> vip_id = models.IntegerField() <NEW_LINE> perm_id = models.IntegerField()
会员-权限 关系表 会员套餐 1 会员身份标识 超级喜欢 会员套餐 2 会员身份标识 反悔功能 无限喜欢次数 会员套餐 3 会员身份标识 超级喜欢 反悔功能 任意更改定位 无限喜欢次数
62598fb13317a56b869be577
class FrozenDict(dict): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.update(*args, **kwargs) <NEW_LINE> <DEDENT> def __setitem__(self, key, val): <NEW_LINE> <INDENT> if key in self: <NEW_LINE> <INDENT> raise Exception("Cannot overwrite existent key: %s" % str(key)) <NEW_LINE> <DEDENT> dict.__setitem__(self, key, val) <NEW_LINE> <DEDENT> def update(self, *args, **kwargs): <NEW_LINE> <INDENT> for (k, v) in dict(*args, **kwargs).iteritems(): <NEW_LINE> <INDENT> self[k] = v
A dictionary that does not permit to redefine its keys
62598fb17d43ff248742742e
class Embeddings(torch.nn.Module, Generic[DT]): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> if not hasattr(self, "name"): <NEW_LINE> <INDENT> self.name: str = "unnamed_embedding" <NEW_LINE> <DEDENT> if not hasattr(self, "static_embeddings"): <NEW_LINE> <INDENT> self.static_embeddings = False <NEW_LINE> <DEDENT> super().__init__() <NEW_LINE> <DEDENT> @property <NEW_LINE> @abstractmethod <NEW_LINE> def embedding_length(self) -> int: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @property <NEW_LINE> @abstractmethod <NEW_LINE> def embedding_type(self) -> str: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def embed(self, data_points: Union[DT, List[DT]]) -> List[DT]: <NEW_LINE> <INDENT> if not isinstance(data_points, list): <NEW_LINE> <INDENT> data_points = [data_points] <NEW_LINE> <DEDENT> if not self._everything_embedded(data_points) or not self.static_embeddings: <NEW_LINE> <INDENT> self._add_embeddings_internal(data_points) <NEW_LINE> <DEDENT> return data_points <NEW_LINE> <DEDENT> def _everything_embedded(self, data_points: Sequence[DT]) -> bool: <NEW_LINE> <INDENT> for data_point in data_points: <NEW_LINE> <INDENT> if self.name not in data_point._embeddings.keys(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def _add_embeddings_internal(self, sentences: List[DT]): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_names(self) -> List[str]: <NEW_LINE> <INDENT> return [self.name] <NEW_LINE> <DEDENT> def get_named_embeddings_dict(self) -> Dict: <NEW_LINE> <INDENT> return {self.name: self} <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_instance_parameters(locals: dict) -> dict: <NEW_LINE> <INDENT> class_definition = locals.get("__class__") <NEW_LINE> instance_parameter_names = set(inspect.signature(class_definition.__init__).parameters) <NEW_LINE> instance_parameter_names.remove("self") <NEW_LINE> instance_parameter_names.add("__class__") <NEW_LINE> instance_parameters = { class_attribute: attribute_value for class_attribute, attribute_value in locals.items() if class_attribute in instance_parameter_names } <NEW_LINE> return instance_parameters
Abstract base class for all embeddings. Every new type of embedding must implement these methods.
62598fb1fff4ab517ebcd83e
class ProcessIOWriter(ProcessIOBase): <NEW_LINE> <INDENT> def __init__(self, args, file, mode, encoding=None, errors=None, newline=None): <NEW_LINE> <INDENT> raise NotImplementedError()
Writable file-like object that wraps an external process.
62598fb101c39578d7f12dd7
class CategoryViewset(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): <NEW_LINE> <INDENT> queryset = GoodsCategory.objects.filter(category_type=1) <NEW_LINE> serializer_class = CategorySerializer
list: 商品分类列表数据 retrieve: 获取商品分类详情
62598fb17047854f4633f433
class Set(_Sequence[S]): <NEW_LINE> <INDENT> def validate(self, value: S) -> None: <NEW_LINE> <INDENT> super().validate(value) <NEW_LINE> cast_value = typing.cast(typing.Sequence, value) <NEW_LINE> if utils.has_duplicates(cast_value): <NEW_LINE> <INDENT> raise exceptions.InvalidArgumentValueError("Value '{value}' {for_name}has duplicate elements.".format(value=value, for_name=self._for_name())) <NEW_LINE> <DEDENT> <DEDENT> def sample(self, random_state: RandomState = None) -> S: <NEW_LINE> <INDENT> elements_max_samples = self.elements.get_max_samples() <NEW_LINE> if elements_max_samples is not None and elements_max_samples < self.min_size: <NEW_LINE> <INDENT> utils.log_once( logger, logging.WARNING, "Elements hyper-parameter for hyper-parameter '%(name)s' cannot provide enough samples " "(maximum %(elements_max_samples)s) to sample a set of at least %(min_size)s elements. Using a default value.", {'name': self.name, 'elements_max_samples': elements_max_samples, 'min_size': self.min_size}, stack_info=True, ) <NEW_LINE> return self.get_default() <NEW_LINE> <DEDENT> return self.elements.sample_multiple(min_samples=self.min_size, max_samples=self.max_size, random_state=random_state, with_replacement=False) <NEW_LINE> <DEDENT> @functools.lru_cache() <NEW_LINE> def get_max_samples(self) -> typing.Optional[int]: <NEW_LINE> <INDENT> max_samples = self.elements.get_max_samples() <NEW_LINE> if max_samples is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> elif max_samples < self.min_size: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> elif self.max_size is None: <NEW_LINE> <INDENT> return 2 ** max_samples - sum(scipy_special.comb(max_samples, j, exact=True) for j in range(self.min_size)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return sum(scipy_special.comb(max_samples, k, exact=True) for k in range(self.min_size, self.max_size + 1)) <NEW_LINE> <DEDENT> <DEDENT> def sample_multiple(self, min_samples: int = 0, max_samples: int = None, random_state: RandomState = None, *, with_replacement: bool = False) -> typing.Sequence[S]: <NEW_LINE> <INDENT> min_samples, max_samples = self._check_sample_size(min_samples, max_samples, with_replacement) <NEW_LINE> random_state = sklearn_validation.check_random_state(random_state) <NEW_LINE> size = random_state.randint(min_samples, max_samples + 1) <NEW_LINE> if with_replacement: <NEW_LINE> <INDENT> sample_list: list = [self.sample(random_state) for i in range(size)] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sample_set: set = set() <NEW_LINE> sample_list = [] <NEW_LINE> while len(sample_list) != size: <NEW_LINE> <INDENT> value = self.sample(random_state) <NEW_LINE> value_set: frozenset = frozenset(value) <NEW_LINE> if value_set not in sample_set: <NEW_LINE> <INDENT> sample_set.add(value_set) <NEW_LINE> sample_list.append(value) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return tuple(sample_list)
A set hyper-parameter which samples without replacement multiple times another hyper-parameter or hyper-parameters configuration. This is useful when a primitive is interested in more than one value of a hyper-parameter or hyper-parameters configuration. Values are represented as tuples of unique elements. The order of elements does not matter (two different orders of same elements represent the same value), but order is meaningful and preserved to assure reproducibility. Type variable ``S`` does not have to be specified because the structural type is a set from provided elements.
62598fb156ac1b37e6302243
class LectureAuthenticationForm(AuthenticationForm): <NEW_LINE> <INDENT> username = forms.EmailField(label=_("Email"), max_length=254) <NEW_LINE> error_messages = { 'invalid_login': _("Please enter a correct %(username)s and password. " "Note that both fields may be case-sensitive."), 'inactive': _("This account is inactive."), } <NEW_LINE> def clean(self): <NEW_LINE> <INDENT> username = self.cleaned_data.get('username') <NEW_LINE> password = self.cleaned_data.get('password') <NEW_LINE> if username and password: <NEW_LINE> <INDENT> self.user_cache = authenticate(username=username, password=password) <NEW_LINE> if self.user_cache is None: <NEW_LINE> <INDENT> raise forms.ValidationError( self.error_messages['invalid_login'], code='invalid_login', params={'username': self.username_field.verbose_name}, ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.confirm_login_allowed(self.user_cache) <NEW_LINE> <DEDENT> <DEDENT> return self.cleaned_data <NEW_LINE> <DEDENT> def clean_username(self): <NEW_LINE> <INDENT> username = self.data['username'] <NEW_LINE> if '@' in username: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> UserModel = get_user_model() <NEW_LINE> username = UserModel.objects.get(email=username).username <NEW_LINE> <DEDENT> except ObjectDoesNotExist: <NEW_LINE> <INDENT> raise ValidationError( self.error_messages['invalid_login'], code='invalid_login', params={'username': self.username_field.verbose_name}, ) <NEW_LINE> <DEDENT> <DEDENT> return username
Base class for authenticating users. Extend this to get a form that accepts username/password logins.
62598fb199cbb53fe6830f32
class Settings(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.screen_width = 1200 <NEW_LINE> self.screen_height = 800 <NEW_LINE> self.bg_color = (230, 230, 230)
A class that stores all settings.
62598fb199fddb7c1ca62e16
class BaseModel(object): <NEW_LINE> <INDENT> def override_values(self, **kwargs): <NEW_LINE> <INDENT> for attr_name, attr_value in kwargs.items(): <NEW_LINE> <INDENT> if hasattr(self, attr_name): <NEW_LINE> <INDENT> setattr(self, attr_name, attr_value) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def obj_to_json(self): <NEW_LINE> <INDENT> return jsonutils.dump_as_bytes(self.obj_to_dict()) <NEW_LINE> <DEDENT> def obj_to_dict(self): <NEW_LINE> <INDENT> the_dict = self.__dict__ <NEW_LINE> retval = self._remove_empty_fields_from_dict(the_dict) <NEW_LINE> return retval <NEW_LINE> <DEDENT> def _remove_empty_fields_from_dict(self, dictionary): <NEW_LINE> <INDENT> resulting_dict = dictionary.copy() <NEW_LINE> empty_keys = [k for k, v in dictionary.items() if v is None] <NEW_LINE> for k in empty_keys: <NEW_LINE> <INDENT> del resulting_dict[k] <NEW_LINE> <DEDENT> return resulting_dict <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def json_to_obj(cls, serialized_str): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> json_dict = jsonutils.loads(serialized_str) <NEW_LINE> return cls.dict_to_obj(json_dict) <NEW_LINE> <DEDENT> except TypeError as e: <NEW_LINE> <INDENT> LOG.error('Couldn\'t deserialize input: %s\n Because: %s', serialized_str, e) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def dict_to_obj(cls, input_dict): <NEW_LINE> <INDENT> return cls(**input_dict)
Base class for models. To allow simple (de)serialization we will use __dict__ to create
62598fb130bbd722464699a5
class HelloViewSet(viewsets.ViewSet): <NEW_LINE> <INDENT> serializer_class = serializer.HelloSerializer <NEW_LINE> def list(self, request): <NEW_LINE> <INDENT> a_viewset = [ 'Uses actions (list,create,retrieve,update,partial_update) ', 'Automatically maps to URLS using Routers', 'Provides more fuctionality with less code', ] <NEW_LINE> return Response({'message': 'Hello!', 'a_viewset': a_viewset}) <NEW_LINE> <DEDENT> def create(self, request): <NEW_LINE> <INDENT> serializer = self.serializer_class(data=request.data) <NEW_LINE> if serializer.is_valid(): <NEW_LINE> <INDENT> name = serializer.validated_data.get('name') <NEW_LINE> message = f'Hello {name}' <NEW_LINE> return Response({'message': message}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Response( serializer.errors, status = status.HTTP_400_BAD_REQUEST ) <NEW_LINE> <DEDENT> <DEDENT> def retrieve(self, request, pk=None): <NEW_LINE> <INDENT> return Response({'http_method': 'GET'}) <NEW_LINE> <DEDENT> def update(self, request, pk=None): <NEW_LINE> <INDENT> return Response({'http_method': 'PUT'}) <NEW_LINE> <DEDENT> def partial_update(self, request, pk=None): <NEW_LINE> <INDENT> return Response({'http_method': 'PATCH'}) <NEW_LINE> <DEDENT> def destroy(self, request, pk=None): <NEW_LINE> <INDENT> return Response({'http_method': 'DELETE'})
Test API ViewSet
62598fb167a9b606de546027
class BeginEnvironment(Command): <NEW_LINE> <INDENT> is_abstract = True <NEW_LINE> endmacro = EndEnvironment <NEW_LINE> @classmethod <NEW_LINE> def invoke(cls, job, tokens, *, invoke_macro=False): <NEW_LINE> <INDENT> if invoke_macro: <NEW_LINE> <INDENT> return super(BeginEnvironment, cls).invoke(job, tokens) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return cls.environment.invoke(job, tokens)
Base command that defines the beginning of an environment
62598fb1be8e80087fbbf0bf
class ConsoleLogger(Logger): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super().__init__(**kwargs) <NEW_LINE> <DEDENT> def _log(self): <NEW_LINE> <INDENT> print(self._buffer, end='')
logs to wherever print() goes
62598fb1f548e778e596b5fd
class DescribeAddressTemplatesResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.TotalCount = None <NEW_LINE> self.AddressTemplateSet = None <NEW_LINE> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.TotalCount = params.get("TotalCount") <NEW_LINE> if params.get("AddressTemplateSet") is not None: <NEW_LINE> <INDENT> self.AddressTemplateSet = [] <NEW_LINE> for item in params.get("AddressTemplateSet"): <NEW_LINE> <INDENT> obj = AddressTemplate() <NEW_LINE> obj._deserialize(item) <NEW_LINE> self.AddressTemplateSet.append(obj) <NEW_LINE> <DEDENT> <DEDENT> self.RequestId = params.get("RequestId")
DescribeAddressTemplates response structure.
62598fb160cbc95b063643aa
class ArchiveCreationError(Exception): <NEW_LINE> <INDENT> pass
Raised when an archive fails during creation
62598fb14428ac0f6e658580
class LivingSocialSpider(BaseSpider): <NEW_LINE> <INDENT> name = "livingsocial" <NEW_LINE> allowed_domains = ['livingsocial.com']
Spider for regularly updated livingsocial.com site, San Francisco Page
62598fb1cc0a2c111447b06c
class Actor(Greenlet): <NEW_LINE> <INDENT> def __init__(self, name, out, socket, context): <NEW_LINE> <INDENT> Greenlet.__init__(self) <NEW_LINE> self.name=name <NEW_LINE> self.out=out <NEW_LINE> self.counter=0 <NEW_LINE> self.context=context <NEW_LINE> self.inbox=self.context.socket(zmq.SUB) <NEW_LINE> self.inbox.connect("inproc://test") <NEW_LINE> self.inbox.setsockopt(zmq.SUBSCRIBE, name) <NEW_LINE> self.outbox=socket <NEW_LINE> <DEDENT> def _run(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> (topic, data)=self.inbox.recv().split() <NEW_LINE> self.counter+=1 <NEW_LINE> self.outbox.send("%s %s"%(self.out, data))
Context is created inside class
62598fb17d43ff248742742f
class TrackedRepository(models.Model): <NEW_LINE> <INDENT> id = models.UUIDField(primary_key=True, default=uuid4, editable=False) <NEW_LINE> user = models.ForeignKey(User, on_delete=models.CASCADE) <NEW_LINE> repo_name = models.TextField() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> app_label = 'flowie' <NEW_LINE> default_related_name = 'tracked_repositories' <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.repo_name
Tracked Repository model
62598fb1fff4ab517ebcd840
class conj(reex.connective): <NEW_LINE> <INDENT> def __str__(self): <NEW_LINE> <INDENT> return "{0:s} & {1:s}".format(self.arg1._strP(), self.arg2._strP()) <NEW_LINE> <DEDENT> def _strP(self): <NEW_LINE> <INDENT> return "({0:s} & {1:s})".format(self.arg1._strP(), self.arg2._strP())
FAdo regexp class that represents the conjunction operation.
62598fb138b623060ffa90f6
class FilterNotValidException(CmisException): <NEW_LINE> <INDENT> pass
FilterNotValidException
62598fb1f548e778e596b5fe
class UWBNetworkCommand: <NEW_LINE> <INDENT> def __init__(self, destination_group=0, type=0, length=0, data=0): <NEW_LINE> <INDENT> self.destination_group = CiholasSerialNumber(destination_group) <NEW_LINE> self.type = type <NEW_LINE> self.length = length <NEW_LINE> self.data = data <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "{}, 0x{:02X}, {}, {}".format(self.destination_group, self.type, self.length, self.data.hex())
UWB Network Command Class Definition
62598fb16e29344779b006b6
class TSVOL(PoundSeparatedCommand): <NEW_LINE> <INDENT> pass
tone classes volume.
62598fb1167d2b6e312b6fcc
class DomPerf(test.Test): <NEW_LINE> <INDENT> test = _DomPerfMeasurement <NEW_LINE> enabled = not sys.platform.startswith('linux') <NEW_LINE> def CreatePageSet(self, options): <NEW_LINE> <INDENT> dom_perf_dir = os.path.join(util.GetChromiumSrcDir(), 'data', 'dom_perf') <NEW_LINE> base_page = 'file://run.html?reportInJS=1&run=' <NEW_LINE> return page_set.PageSet.FromDict({ 'pages': [ { 'url': base_page + 'Accessors' }, { 'url': base_page + 'CloneNodes' }, { 'url': base_page + 'CreateNodes' }, { 'url': base_page + 'DOMDivWalk' }, { 'url': base_page + 'DOMTable' }, { 'url': base_page + 'DOMWalk' }, { 'url': base_page + 'Events' }, { 'url': base_page + 'Get+Elements' }, { 'url': base_page + 'GridSort' }, { 'url': base_page + 'Template' } ] }, dom_perf_dir)
A suite of JavaScript benchmarks for exercising the browser's DOM. The final score is computed as the geometric mean of the individual results. Scores are not comparable across benchmark suite versions and higher scores means better performance: Bigger is better!
62598fb1851cf427c66b8316
class IndexView(HTTPMethodView): <NEW_LINE> <INDENT> decorators = [] <NEW_LINE> async def get(self, req): <NEW_LINE> <INDENT> return text('Hello world!')
This is the class that responds for requests for: /
62598fb126068e7796d4c9b0
class VSEQF_PT_QuickTagsPanel(bpy.types.Panel): <NEW_LINE> <INDENT> bl_label = "Quick Tags" <NEW_LINE> bl_space_type = 'SEQUENCE_EDITOR' <NEW_LINE> bl_region_type = 'UI' <NEW_LINE> bl_category = "Strip" <NEW_LINE> @classmethod <NEW_LINE> def poll(cls, context): <NEW_LINE> <INDENT> prefs = vseqf.get_prefs() <NEW_LINE> if not context.sequences or not context.scene.sequence_editor: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if len(context.sequences) > 0 and context.scene.sequence_editor.active_strip: <NEW_LINE> <INDENT> return prefs.tags <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def draw(self, context): <NEW_LINE> <INDENT> scene = context.scene <NEW_LINE> sequence = timeline.current_active(context) <NEW_LINE> selected = timeline.current_selected(context) <NEW_LINE> layout = self.layout <NEW_LINE> row = layout.row() <NEW_LINE> row.label(text='All Tags:') <NEW_LINE> row = layout.row() <NEW_LINE> row.template_list("VSEQF_UL_QuickTagListAll", "", scene.vseqf, 'tags', scene.vseqf, 'tag_index', rows=3) <NEW_LINE> row = layout.row() <NEW_LINE> tag_index = scene.vseqf.tag_index <NEW_LINE> if len(scene.vseqf.tags) > 0: <NEW_LINE> <INDENT> if tag_index >= len(scene.vseqf.tags): <NEW_LINE> <INDENT> tag_index = len(scene.vseqf.tags) - 1 <NEW_LINE> <DEDENT> text = scene.vseqf.tags[tag_index].name <NEW_LINE> row.operator('vseqf.quicktags_select', text='Select With Tag').text = text <NEW_LINE> row = layout.row() <NEW_LINE> if len(selected) > 0: <NEW_LINE> <INDENT> row.enabled = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> row.enabled = False <NEW_LINE> <DEDENT> row.operator('vseqf.quicktags_add', text='Add Tag To Selected Strips').text = text <NEW_LINE> <DEDENT> row = layout.row() <NEW_LINE> row.separator() <NEW_LINE> tag_index = context.scene.vseqf.strip_tag_index <NEW_LINE> if len(sequence.tags) > 0: <NEW_LINE> <INDENT> if tag_index >= len(sequence.tags): <NEW_LINE> <INDENT> tag_index = len(sequence.tags) - 1 <NEW_LINE> <DEDENT> current_tag = sequence.tags[tag_index] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> current_tag = None <NEW_LINE> <DEDENT> row = layout.row() <NEW_LINE> row.label(text='Active Tags:') <NEW_LINE> row.operator('vseqf.quicktags_clear', text='Clear All Tags').mode = 'active' <NEW_LINE> split = layout.split(factor=.9) <NEW_LINE> split.template_list("VSEQF_UL_QuickTagList", "", sequence, 'tags', scene.vseqf, 'strip_tag_index', rows=3) <NEW_LINE> col = split.column() <NEW_LINE> col.operator('vseqf.quicktags_add_active', text='+').text = 'Tag' <NEW_LINE> if current_tag is not None: <NEW_LINE> <INDENT> col.operator('vseqf.quicktags_remove', text='-').text = current_tag.text <NEW_LINE> <DEDENT> if current_tag is not None: <NEW_LINE> <INDENT> row = layout.row() <NEW_LINE> row.prop(current_tag, 'use_offset', text='Marker Tag') <NEW_LINE> if current_tag.use_offset: <NEW_LINE> <INDENT> row = layout.row() <NEW_LINE> row.label(text=current_tag.text) <NEW_LINE> row.prop(current_tag, 'color', text='') <NEW_LINE> row = layout.row(align=True) <NEW_LINE> row.prop(current_tag, 'offset', text='Tag Offset') <NEW_LINE> row.prop(current_tag, 'length', text='Tag Length')
Panel for displaying, removing and adding tags
62598fb1a79ad1619776a0c3
class ClusterSet(object): <NEW_LINE> <INDENT> def __init__(self, pointType): <NEW_LINE> <INDENT> self.members = [] <NEW_LINE> <DEDENT> def add(self, c): <NEW_LINE> <INDENT> if c in self.members: <NEW_LINE> <INDENT> raise ValueError <NEW_LINE> <DEDENT> self.members.append(c) <NEW_LINE> <DEDENT> def remove(self, c): <NEW_LINE> <INDENT> if c not in self.members: <NEW_LINE> <INDENT> raise ValueError <NEW_LINE> <DEDENT> self.members.remove(c) <NEW_LINE> <DEDENT> def getClusters(self): <NEW_LINE> <INDENT> return self.members[:] <NEW_LINE> <DEDENT> def mergeClusters(self, c1, c2): <NEW_LINE> <INDENT> jointPoints = [] <NEW_LINE> for point in c1.points: <NEW_LINE> <INDENT> jointPoints.append(point) <NEW_LINE> <DEDENT> for point in c2.points: <NEW_LINE> <INDENT> jointPoints.append(point) <NEW_LINE> <DEDENT> c3 = Cluster(jointPoints, c1.pointType) <NEW_LINE> self.remove(c1) <NEW_LINE> self.remove(c2) <NEW_LINE> self.add(c3) <NEW_LINE> <DEDENT> def findClosest(self, linkage): <NEW_LINE> <INDENT> space = len(self.members) <NEW_LINE> closestDistance = linkage(self.members[0], self.members[1]) <NEW_LINE> closestPair = (self.members[0], self.members[1]) <NEW_LINE> for i in range(space - 1): <NEW_LINE> <INDENT> for j in range(i + 1, space): <NEW_LINE> <INDENT> thisDistance = linkage(self.members[i], self.members[j]) <NEW_LINE> if thisDistance < closestDistance: <NEW_LINE> <INDENT> closestDistance = thisDistance <NEW_LINE> closestPair = (self.members[i], self.members[j]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return closestPair <NEW_LINE> <DEDENT> def mergeOne(self, linkage): <NEW_LINE> <INDENT> (c1, c2) = self.findClosest(linkage) <NEW_LINE> self.mergeClusters(c1, c2) <NEW_LINE> return (c1, c2) <NEW_LINE> <DEDENT> def numClusters(self): <NEW_LINE> <INDENT> return len(self.members) <NEW_LINE> <DEDENT> def toStr(self): <NEW_LINE> <INDENT> cNames = [] <NEW_LINE> for c in self.members: <NEW_LINE> <INDENT> cNames.append(c.getNames()) <NEW_LINE> <DEDENT> cNames.sort() <NEW_LINE> result = '' <NEW_LINE> for i in range(len(cNames)): <NEW_LINE> <INDENT> names = '' <NEW_LINE> for n in cNames[i]: <NEW_LINE> <INDENT> names += n + ', ' <NEW_LINE> <DEDENT> names = names[:-2] <NEW_LINE> result += ' C' + str(i) + ':' + names + '\n' <NEW_LINE> <DEDENT> return result
A ClusterSet is defined as a list of clusters
62598fb18da39b475be03241
class EnterNexellFastbootAction(DeployAction): <NEW_LINE> <INDENT> def __init__(self,parameters, key1, key2, key3): <NEW_LINE> <INDENT> super(EnterNexellFastbootAction, self).__init__() <NEW_LINE> self.name = "enter_nexell_fastboot_action" <NEW_LINE> self.description = "enter fastboot bootloader" <NEW_LINE> self.summary = "enter fastboot" <NEW_LINE> self.retries = 10 <NEW_LINE> self.sleep = 10 <NEW_LINE> self.cmd = parameters['images']['nexell_ext'][key1] <NEW_LINE> self.param1 = parameters['images']['nexell_ext'][key2] <NEW_LINE> self.param2 = parameters['images']['nexell_ext'][key3] <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> super(EnterNexellFastbootAction, self).validate() <NEW_LINE> <DEDENT> def run(self, connection, args=None): <NEW_LINE> <INDENT> connection = super(EnterNexellFastbootAction, self).run(connection, args) <NEW_LINE> test_path = self.job.device['device_path'] <NEW_LINE> self.logger.debug("test_path:%s",test_path[0]) <NEW_LINE> telnet_cmd = [self.cmd, self.param1, self.param2, test_path[0]] <NEW_LINE> self.logger.debug("SUKER: telnet_cmd " + str(telnet_cmd)) <NEW_LINE> command_output = self.run_command(telnet_cmd) <NEW_LINE> self.logger.debug("SUKER: self.errors " + str(self.errors)) <NEW_LINE> self.results = {'status': 'finished'} <NEW_LINE> return connection
Enters fastboot bootloader.
62598fb1d486a94d0ba2c02a
@total_ordering <NEW_LINE> class Elem: <NEW_LINE> <INDENT> def __init__(self, metric_value, father_id, graph): <NEW_LINE> <INDENT> self.father_id = father_id <NEW_LINE> self.graph = graph <NEW_LINE> self.metric_value = metric_value <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.metric_value == other.metric_value <NEW_LINE> <DEDENT> def __lt__(self, other): <NEW_LINE> <INDENT> return self.metric_value < other.metric_value
Elements to be sorted according to metric value.
62598fb130bbd722464699a6
class Texture1D(Texture): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> Texture.__init__(self, gl.GL_TEXTURE_1D) <NEW_LINE> self.shape = self._check_shape(self.shape, 1) <NEW_LINE> self._cpu_format = Texture._cpu_formats[self.shape[-1]] <NEW_LINE> self._gpu_format = Texture._gpu_formats[self.shape[-1]] <NEW_LINE> <DEDENT> @property <NEW_LINE> def width(self): <NEW_LINE> <INDENT> return self.shape[0] <NEW_LINE> <DEDENT> def _setup(self): <NEW_LINE> <INDENT> Texture._setup(self) <NEW_LINE> gl.glBindTexture(self.target, self._handle) <NEW_LINE> gl.glTexImage1D(self.target, 0, self._gpu_format, self.width, 0, self._cpu_format, self.gtype, None) <NEW_LINE> self._need_setup = False <NEW_LINE> <DEDENT> def _update(self): <NEW_LINE> <INDENT> log.debug("GPU: Updating texture") <NEW_LINE> if self.pending_data: <NEW_LINE> <INDENT> start, stop = self.pending_data <NEW_LINE> offset, nbytes = start, stop-start <NEW_LINE> itemsize = self.strides[0] <NEW_LINE> x = offset // itemsize <NEW_LINE> width = nbytes//itemsize <NEW_LINE> gl.glTexSubImage1D(self.target, 0, x, width, self._cpu_format, self.gtype, self) <NEW_LINE> <DEDENT> self._pending_data = None <NEW_LINE> self._need_update = False
1D Texture
62598fb155399d3f0562657b
@dataclass <NEW_LINE> class Tick(object): <NEW_LINE> <INDENT> Time: int = 0 <NEW_LINE> Open: float = 0 <NEW_LINE> Close: float = 0 <NEW_LINE> High: float = 0 <NEW_LINE> Low: float = 0 <NEW_LINE> Volume: float = 0 <NEW_LINE> OpenTime: int = 0 <NEW_LINE> CloseTime: int = 0 <NEW_LINE> def is_valid(self): <NEW_LINE> <INDENT> return self.Time != 0
Candlestick/Tick data
62598fb156b00c62f0fb2911
class CachedList(ndb.Model): <NEW_LINE> <INDENT> list_data = ndb.JsonProperty(repeated=True) <NEW_LINE> is_processing = ndb.BooleanProperty() <NEW_LINE> valid_through = ndb.DateTimeProperty()
The CachedList model, represents a list cached as a ndb entity.
62598fb14f6381625f1994ed
class DnsManagementClientConfiguration(AzureConfiguration): <NEW_LINE> <INDENT> def __init__( self, credentials, subscription_id, base_url=None): <NEW_LINE> <INDENT> if credentials is None: <NEW_LINE> <INDENT> raise ValueError("Parameter 'credentials' must not be None.") <NEW_LINE> <DEDENT> if subscription_id is None: <NEW_LINE> <INDENT> raise ValueError("Parameter 'subscription_id' must not be None.") <NEW_LINE> <DEDENT> if not base_url: <NEW_LINE> <INDENT> base_url = 'https://management.azure.com' <NEW_LINE> <DEDENT> super(DnsManagementClientConfiguration, self).__init__(base_url) <NEW_LINE> self.add_user_agent('dnsmanagementclient/{}'.format(VERSION)) <NEW_LINE> self.add_user_agent('Azure-SDK-For-Python') <NEW_LINE> self.credentials = credentials <NEW_LINE> self.subscription_id = subscription_id
Configuration for DnsManagementClient Note that all parameters used to create this instance are saved as instance attributes. :param credentials: Credentials needed for the client to connect to Azure. :type credentials: :mod:`A msrestazure Credentials object<msrestazure.azure_active_directory>` :param subscription_id: Specifies the Azure subscription ID, which uniquely identifies the Microsoft Azure subscription. :type subscription_id: str :param str base_url: Service URL
62598fb18e7ae83300ee90fe
class ApigwPath(object): <NEW_LINE> <INDENT> def __init__(self, event: Dict): <NEW_LINE> <INDENT> self.version = event.get("version") <NEW_LINE> self.apigw_stage = _get_apigw_stage(event) <NEW_LINE> self.path = _get_request_path(event) <NEW_LINE> self.api_prefix = proxy_pattern.sub("", event.get("resource", "")).rstrip("/") <NEW_LINE> if not self.apigw_stage and self.path: <NEW_LINE> <INDENT> path = event.get("path", "") <NEW_LINE> suffix = self.api_prefix + self.path <NEW_LINE> self.path_mapping = path.replace(suffix, "") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.path_mapping = "" <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def prefix(self): <NEW_LINE> <INDENT> if self.apigw_stage and not self.apigw_stage == "$default": <NEW_LINE> <INDENT> return f"/{self.apigw_stage}" + self.api_prefix <NEW_LINE> <DEDENT> elif self.path_mapping: <NEW_LINE> <INDENT> return self.path_mapping + self.api_prefix <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.api_prefix
Parse path of API Call.
62598fb157b8e32f52508149
class ConservativeSourceTerm(ConservativeTracerTerm): <NEW_LINE> <INDENT> def residual(self, solution, solution_old, fields, fields_old, bnd_conditions=None): <NEW_LINE> <INDENT> f = 0 <NEW_LINE> source = fields_old.get('source') <NEW_LINE> if source is not None: <NEW_LINE> <INDENT> H = self.depth.get_total_depth(fields_old['elev_2d']) <NEW_LINE> f += -inner(H*source, self.test)*self.dx <NEW_LINE> <DEDENT> return -f
Generic source term The weak form reads .. math:: F_s = \int_\Omega \sigma \phi dx where :math:`\sigma` is a user defined scalar :class:`Function`.
62598fb13346ee7daa337675
class NodesCommand(RootCommand): <NEW_LINE> <INDENT> name = 'nodes' <NEW_LINE> help = 'Tortuga nodes API' <NEW_LINE> sub_commands = [ ListCommand(), GetCommand(), UpdateCommand(), NodeStatusCommand(), ]
This is a command for interacting with WS API endpoints.
62598fb1b7558d5895463686
class CreateOpenBankOrderPaymentResult(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.ChannelOrderId = None <NEW_LINE> self.ThirdPayOrderId = None <NEW_LINE> self.RedirectInfo = None <NEW_LINE> self.OutOrderId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.ChannelOrderId = params.get("ChannelOrderId") <NEW_LINE> self.ThirdPayOrderId = params.get("ThirdPayOrderId") <NEW_LINE> if params.get("RedirectInfo") is not None: <NEW_LINE> <INDENT> self.RedirectInfo = OpenBankRedirectInfo() <NEW_LINE> self.RedirectInfo._deserialize(params.get("RedirectInfo")) <NEW_LINE> <DEDENT> self.OutOrderId = params.get("OutOrderId") <NEW_LINE> memeber_set = set(params.keys()) <NEW_LINE> for name, value in vars(self).items(): <NEW_LINE> <INDENT> if name in memeber_set: <NEW_LINE> <INDENT> memeber_set.remove(name) <NEW_LINE> <DEDENT> <DEDENT> if len(memeber_set) > 0: <NEW_LINE> <INDENT> warnings.warn("%s fileds are useless." % ",".join(memeber_set))
云企付-支付下单返回响应
62598fb1d7e4931a7ef3c0f0
class DemoBatchSystem(GenericBatchSystem): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def get_mnemonic(): <NEW_LINE> <INDENT> return "demo" <NEW_LINE> <DEDENT> def __init__(self, scheduler_output_filenames, config, options): <NEW_LINE> <INDENT> self.scheduler_output_filenames = scheduler_output_filenames <NEW_LINE> self.config = config <NEW_LINE> self.sim = LittleGridSimulator() <NEW_LINE> <DEDENT> def get_worker_nodes(self, job_ids, job_queues, options): <NEW_LINE> <INDENT> worker_nodes = [] <NEW_LINE> for node in range(WORKER_NODES): <NEW_LINE> <INDENT> core_job_map = {} <NEW_LINE> for core, job_id in enumerate(self.sim.core_job_map[node]): <NEW_LINE> <INDENT> if job_id: <NEW_LINE> <INDENT> core_job_map[core] = job_id <NEW_LINE> <DEDENT> <DEDENT> worker_node = { "domainname": self.sim.domain_names[node], "state": self.sim.node_state[node], "np": self.sim.nps[node], "core_job_map": core_job_map } <NEW_LINE> worker_nodes.append(worker_node) <NEW_LINE> <DEDENT> worker_nodes = self.ensure_worker_nodes_have_qnames(worker_nodes, job_ids, job_queues) <NEW_LINE> return worker_nodes <NEW_LINE> <DEDENT> def get_jobs_info(self): <NEW_LINE> <INDENT> job_ids = [] <NEW_LINE> usernames = [] <NEW_LINE> job_states = [] <NEW_LINE> queue_names = [] <NEW_LINE> for node in range(WORKER_NODES): <NEW_LINE> <INDENT> for core, job_id in enumerate(self.sim.core_job_map[node]): <NEW_LINE> <INDENT> if job_id: <NEW_LINE> <INDENT> job_ids.append(job_id) <NEW_LINE> queue_name, username = self.sim.job_meta[job_id] <NEW_LINE> usernames.append(username) <NEW_LINE> queue_names.append(queue_name) <NEW_LINE> job_states.append(self.sim.job_state[job_id]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return job_ids, usernames, job_states, queue_names <NEW_LINE> <DEDENT> def get_queues_info(self): <NEW_LINE> <INDENT> total_running_jobs = 0 <NEW_LINE> run_for_queue = defaultdict(int) <NEW_LINE> for node in range(WORKER_NODES): <NEW_LINE> <INDENT> for core, job_id in enumerate(self.sim.core_job_map[node]): <NEW_LINE> <INDENT> if job_id: <NEW_LINE> <INDENT> total_running_jobs += 1 <NEW_LINE> queue_name, _ = self.sim.job_meta[job_id] <NEW_LINE> run_for_queue[queue_name] += 1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> total_queued_jobs = self.sim.get_total_queued() <NEW_LINE> qstatq_list = list() <NEW_LINE> for queue_name in QUEUES: <NEW_LINE> <INDENT> qstatq = { 'queue_name': queue_name, 'run': run_for_queue[queue_name], 'queued': str(len(self.sim.queue_jobs[queue_name])), 'state': self.sim.queue_state[queue_name], 'lm': random.randint(0, 100), } <NEW_LINE> qstatq_list.append(qstatq) <NEW_LINE> <DEDENT> return total_running_jobs, total_queued_jobs, qstatq_list
This is an example implementation of how a batch system is "read" and what is expected of it by qtop in order to run.
62598fb1baa26c4b54d4f311
class IntegerArgument(AbstractArgument): <NEW_LINE> <INDENT> def _parse_one(self, arg): <NEW_LINE> <INDENT> return int(arg)
An argument that captures integers.
62598fb1d58c6744b42dc306
class Typed(): <NEW_LINE> <INDENT> def __init__(self, name, expected_type, mutable=True): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.expected_type = expected_type <NEW_LINE> self.mutable = mutable <NEW_LINE> <DEDENT> def __get__(self, instance, cls): <NEW_LINE> <INDENT> if instance is None: <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return instance.__dict__[self.name] <NEW_LINE> <DEDENT> <DEDENT> def __set__(self, instance, val): <NEW_LINE> <INDENT> if self.name in instance.__dict__.keys(): <NEW_LINE> <INDENT> if not self.mutable: <NEW_LINE> <INDENT> print('Warning: Attempting to change Immutable Attribute') <NEW_LINE> return None <NEW_LINE> <DEDENT> <DEDENT> if not isinstance(val, self.expected_type): <NEW_LINE> <INDENT> raise TypeError('Expecting argument of type {}'.format(self.expected_type)) <NEW_LINE> <DEDENT> instance.__dict__[self.name] = val
Descriptor class used for a type assertion decorator used to type-check specified attributes Parameters ---------- name: str name of attribute expected_type: type object type associated with attribute mutable: boolean attribute if mutable if set to True and Immutable otherwise
62598fb160cbc95b063643ac
class DeleteVPNBindGroupToLocalSite(CommandResource): <NEW_LINE> <INDENT> resource = 'vpnbindgrouptolocalsites' <NEW_LINE> @staticmethod <NEW_LINE> def add_known_arguments(parser): <NEW_LINE> <INDENT> parser.add_argument( 'id', metavar='VPNBINDGROUPTOLOCALSITE', help="ID or Name of VPNBindGroupToLocalSite to delete\n\n") <NEW_LINE> return parser
Delete a given VPNBindGroupToLocalSite
62598fb13317a56b869be579
class DiffXDOMReader(object): <NEW_LINE> <INDENT> reader_cls = DiffXReader <NEW_LINE> def __init__(self, diffx_cls): <NEW_LINE> <INDENT> self.diffx_cls = diffx_cls <NEW_LINE> <DEDENT> def parse(self, stream): <NEW_LINE> <INDENT> with stream: <NEW_LINE> <INDENT> reader = self.reader_cls(stream) <NEW_LINE> diffx = self.diffx_cls() <NEW_LINE> section_handlers = { Section.MAIN: self._read_main_section, Section.MAIN_META: self._read_meta_section, Section.MAIN_PREAMBLE: self._read_preamble_section, Section.CHANGE: self._read_change_section, Section.CHANGE_PREAMBLE: self._read_preamble_section, Section.CHANGE_META: self._read_meta_section, Section.FILE: self._read_file_section, Section.FILE_META: self._read_meta_section, Section.FILE_DIFF: self._read_diff_section, } <NEW_LINE> cur_section = diffx <NEW_LINE> for section_info in reader: <NEW_LINE> <INDENT> section_id = section_info['section'] <NEW_LINE> section_handler = section_handlers[section_id] <NEW_LINE> cur_section = ( section_handler(diffx, cur_section, section_info) or cur_section ) <NEW_LINE> <DEDENT> <DEDENT> return diffx <NEW_LINE> <DEDENT> def _read_meta_section(self, diffx, section, section_info): <NEW_LINE> <INDENT> section.meta = section_info['metadata'] <NEW_LINE> self._set_content_options(section.meta_section, section_info['options']) <NEW_LINE> <DEDENT> def _read_preamble_section(self, diffx, section, section_info): <NEW_LINE> <INDENT> section.preamble = section_info['text'] <NEW_LINE> self._set_content_options(section.preamble_section, section_info['options']) <NEW_LINE> <DEDENT> def _read_diff_section(self, diffx, section, section_info): <NEW_LINE> <INDENT> section.diff = section_info['diff'] <NEW_LINE> self._set_content_options(section.diff_section, section_info['options']) <NEW_LINE> <DEDENT> def _read_main_section(self, diffx, section, section_info): <NEW_LINE> <INDENT> diffx.options.clear() <NEW_LINE> diffx.options.update(section_info['options']) <NEW_LINE> <DEDENT> def _read_change_section(self, diffx, section, section_info): <NEW_LINE> <INDENT> return diffx.add_change(**section_info['options']) <NEW_LINE> <DEDENT> def _read_file_section(self, diffx, section, section_info): <NEW_LINE> <INDENT> return diffx.changes[-1].add_file(**section_info['options']) <NEW_LINE> <DEDENT> def _set_content_options(self, section, options): <NEW_LINE> <INDENT> options.pop('length', None) <NEW_LINE> section.options.clear() <NEW_LINE> section.options.update(options)
A reader for parsing a DiffX file into DOM objects. This will construct a :py:class:`~pydiffx.dom.objects.DiffX` from an input byte stream, such as a file, HTTP response, or memory-backed stream. Often, you won't use this directly. Instead, you'll call :py:meth:`DiffXFile.from_stream() <pydiffx.dom.objects.DiffX.from_stream>` or :py:meth:`DiffXFile.from_bytes() <pydiffx.dom.objects.DiffX.from_bytes>`. If constructing manually, one instance can be reused for multiple streams. Attributes: diffx_cls (type): The :py:class:`~pydiffx.dom.objects.DiffX` class or subclass to create when parsing.
62598fb14428ac0f6e658582
class Album: <NEW_LINE> <INDENT> def __init__(self, name, year, artist=None): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.year = year <NEW_LINE> if artist is None: <NEW_LINE> <INDENT> self.artist = Artist("Various Artists") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.artist = artist <NEW_LINE> <DEDENT> self.tracks = [] <NEW_LINE> <DEDENT> def add_song(self, song, position=None): <NEW_LINE> <INDENT> if position is None: <NEW_LINE> <INDENT> self.tracks.append(song) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.tracks.insert(position, song)
Class to represent a Album, using it's track list Attributes: album name (str): The name of the album year (int): The year of the album artist: (Artist): The artist responsible for the album. If not specified will default to "Various Artists" tracks (List(Songs)): A list of songs on the album Methods: addSong: Used to add a new song to an album track list
62598fb1236d856c2adc946c
@implementer(IMessage) <NEW_LINE> class Message(Container): <NEW_LINE> <INDENT> pass
Archive Simple Message Item
62598fb17d43ff2487427430
class StateProcessor(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> with tf.variable_scope("state_processor"): <NEW_LINE> <INDENT> self.input_state = tf.placeholder(shape=[observation_space_size], dtype=tf.float32) <NEW_LINE> self.output = self.input_state <NEW_LINE> <DEDENT> <DEDENT> def process(self, sess, state): <NEW_LINE> <INDENT> return sess.run(self.output, {self.input_state:state})
Processes the input state for use with the network
62598fb18e7ae83300ee90ff
class Word(gym.spaces.MultiDiscrete): <NEW_LINE> <INDENT> def __init__(self, max_length, vocab): <NEW_LINE> <INDENT> if len(vocab) != len(set(vocab)): <NEW_LINE> <INDENT> raise VocabularyHasDuplicateTokens() <NEW_LINE> <DEDENT> self.max_length = max_length <NEW_LINE> self.PAD = "<PAD>" <NEW_LINE> self.UNK = "<UNK>" <NEW_LINE> self.BOS = "<S>" <NEW_LINE> self.EOS = "</S>" <NEW_LINE> self.SEP = "<|>" <NEW_LINE> special_tokens = [self.PAD, self.UNK, self.EOS, self.BOS, self.SEP] <NEW_LINE> self.vocab = [w for w in special_tokens if w not in vocab] <NEW_LINE> self.vocab += list(vocab) <NEW_LINE> self.vocab_set = set(self.vocab) <NEW_LINE> self.vocab_size = len(self.vocab) <NEW_LINE> self.id2w = {i: w for i, w in enumerate(self.vocab)} <NEW_LINE> self.w2id = {w: i for i, w in self.id2w.items()} <NEW_LINE> self.PAD_id = self.w2id[self.PAD] <NEW_LINE> self.UNK_id = self.w2id[self.UNK] <NEW_LINE> self.BOS_id = self.w2id[self.BOS] <NEW_LINE> self.EOS_id = self.w2id[self.EOS] <NEW_LINE> self.SEP_id = self.w2id[self.SEP] <NEW_LINE> super().__init__([len(self.vocab) - 1] * self.max_length) <NEW_LINE> self.dtype = np.int64 <NEW_LINE> <DEDENT> def tokenize(self, text, padding=False): <NEW_LINE> <INDENT> text = text.lower() <NEW_LINE> text = re.sub(".", " </S> <S> ", text) <NEW_LINE> text = "<S> " + text + " </S>" <NEW_LINE> text = re.sub("'", "", text) <NEW_LINE> text = re.sub("[^a-z0-9 ]", " ", text) <NEW_LINE> words = text.split() <NEW_LINE> ids = [self.w2id.get(w, self.UNK_id) for w in words] <NEW_LINE> if padding: <NEW_LINE> <INDENT> nb_pads = self.max_length - len(ids) <NEW_LINE> msg = "Provided `max_length` was not large enough ({} words).".format(len(ids)) <NEW_LINE> assert nb_pads >= 0, msg <NEW_LINE> ids += [self.PAD_id] * nb_pads <NEW_LINE> <DEDENT> return np.array(ids) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Word(L={}, V={})".format(self.max_length, self.vocab_size)
Word observation/action space This space consists of a series of `gym.spaces.Discrete` objects all with the same parameters. Each `gym.spaces.Discrete` can take integer values between 0 and `len(self.vocab)`. Notes ----- The following special tokens will be prepended (if needed) to the vocabulary: <PAD> : Padding <UNK> : Unknown word <S> : Beginning of sentence </S> : End of sentence
62598fb138b623060ffa90f8
class OutputFilterDatabase(LazyDatabase): <NEW_LINE> <INDENT> def initialize(self): <NEW_LINE> <INDENT> from spira.yevon import filters <NEW_LINE> f = filters.ToggledCompositeFilter(filters=[]) <NEW_LINE> f += filters.PortCellFilter(name='cell_ports') <NEW_LINE> f += filters.PortPolygonEdgeFilter(name='edge_ports') <NEW_LINE> f += filters.PortPolygonContactFilter(name='contact_ports') <NEW_LINE> f['cell_ports'] = True <NEW_LINE> f['edge_ports'] = False <NEW_LINE> f['contat_ports'] = False <NEW_LINE> self.PORTS = f
Define the filters that will be used when creating a spira.PCell object.
62598fb11b99ca400228f55e
class ActiveUserView(View): <NEW_LINE> <INDENT> def get(self, request, active_code): <NEW_LINE> <INDENT> all_records = EmailVerifyRecord.objects.filter(code=active_code) <NEW_LINE> if all_records: <NEW_LINE> <INDENT> for record in all_records: <NEW_LINE> <INDENT> email = record.email <NEW_LINE> user = UserProfile.objects.get(email=email) <NEW_LINE> user.is_active = True <NEW_LINE> user.save() <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return render(request, "active_fail.html") <NEW_LINE> <DEDENT> return render(request, "active_success.html")
用户激活
62598fb1fff4ab517ebcd842
class ErrorResponse(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'error': {'key': 'error', 'type': 'ErrorDetails'}, } <NEW_LINE> def __init__( self, *, error: Optional["ErrorDetails"] = None, **kwargs ): <NEW_LINE> <INDENT> super(ErrorResponse, self).__init__(**kwargs) <NEW_LINE> self.error = error
The error object. :param error: The error details object. :type error: ~azure.mgmt.network.v2020_03_01.models.ErrorDetails
62598fb1442bda511e95c4b4
class AdminLoginForm(AdminAuthenticationForm): <NEW_LINE> <INDENT> error_messages = { "invalid_login": _("Please enter the correct %(username)s and password " "for your account. Note that both fields are " "case-sensitive") } <NEW_LINE> def confirm_login_allowed(self, user): <NEW_LINE> <INDENT> if not user.is_active: <NEW_LINE> <INDENT> raise django.forms.ValidationError( self.error_messages["invalid_login"], code="invalid_login", params={"username": self.username_field.verbose_name} )
Provides a login form for the admin UI This removes the requirement for the user to have the `is_staff` attribute set to True. We use the admin UI for all users so this check and flag is redundant in this app.
62598fb1be383301e0253856
class Pbit_Conversion(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.pbit_check = Pbit.pbit_conversion_check.Pbit_Conversion_check() <NEW_LINE> <DEDENT> def convert_decimal(self,value): <NEW_LINE> <INDENT> Negative_counter = 0 <NEW_LINE> value = str(value) <NEW_LINE> if value[0] is "-": <NEW_LINE> <INDENT> value = value[1:] <NEW_LINE> Negative_counter = 1 <NEW_LINE> <DEDENT> head_type = self.pbit_check.type_decimal_number(value) <NEW_LINE> value = value[2:] <NEW_LINE> if head_type is 'two': <NEW_LINE> <INDENT> values = int(value,2) <NEW_LINE> ten_number = self.pbit_check.check_negative(Negative_counter,values) <NEW_LINE> return int(ten_number) <NEW_LINE> <DEDENT> elif head_type is 'sixteen': <NEW_LINE> <INDENT> values = int(value,16) <NEW_LINE> ten_number = self.pbit_check.check_negative(Negative_counter,values) <NEW_LINE> return int(ten_number) <NEW_LINE> <DEDENT> elif head_type is "ten": <NEW_LINE> <INDENT> sys.exit('This is value is not Binary number or Hexdecimal') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sys.exit('Argument is not a numeric string ') <NEW_LINE> <DEDENT> <DEDENT> def convert_binary(self,value): <NEW_LINE> <INDENT> Negative_counter = 0 <NEW_LINE> value = str(value) <NEW_LINE> if value[0] is "-": <NEW_LINE> <INDENT> value = value[1:] <NEW_LINE> Negative_counter = 1 <NEW_LINE> <DEDENT> head_type = self.pbit_check.type_decimal_number(value) <NEW_LINE> if head_type is not "ten": <NEW_LINE> <INDENT> value = value[2:] <NEW_LINE> <DEDENT> if head_type is 'ten': <NEW_LINE> <INDENT> values = bin(int(value)) <NEW_LINE> two_number = self.pbit_check.check_negative(Negative_counter,values) <NEW_LINE> return two_number <NEW_LINE> <DEDENT> elif head_type is 'sixteen': <NEW_LINE> <INDENT> values = bin(int(value,16)) <NEW_LINE> two_number = self.pbit_check.check_negative(Negative_counter,values) <NEW_LINE> return two_number <NEW_LINE> <DEDENT> elif head_type is 'two': <NEW_LINE> <INDENT> sys.exit('This is value is not Decimal number or Hexdecimal ') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sys.exit("Argument is not a numeric string") <NEW_LINE> <DEDENT> <DEDENT> def convert_hex(self,value): <NEW_LINE> <INDENT> Negative_counter = 0 <NEW_LINE> value = str(value) <NEW_LINE> if value[0] is "-": <NEW_LINE> <INDENT> value = value[1:] <NEW_LINE> Negative_counter = 1 <NEW_LINE> <DEDENT> head_type = self.pbit_check.type_decimal_number(value) <NEW_LINE> if head_type is not "ten": <NEW_LINE> <INDENT> value = value[2:] <NEW_LINE> <DEDENT> if head_type is 'ten': <NEW_LINE> <INDENT> values = hex(int(value)) <NEW_LINE> hex_number = self.pbit_check.check_negative(Negative_counter,values) <NEW_LINE> return hex_number <NEW_LINE> <DEDENT> elif head_type is 'two': <NEW_LINE> <INDENT> values = hex(int(value,2)) <NEW_LINE> hex_number = self.pbit_check.check_negative(Negative_counter,values) <NEW_LINE> return hex_number <NEW_LINE> <DEDENT> elif head_type is 'sixteen': <NEW_LINE> <INDENT> sys.exit('This is value is not Decimal number or Binary number') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sys.exit("Argument is not a numeric string")
変換系の関数を集めたモジュール
62598fb16e29344779b006b8
class BatchTextRequest(object): <NEW_LINE> <INDENT> openapi_types = { 'text': 'str', 'id': 'str' } <NEW_LINE> attribute_map = { 'text': 'text', 'id': 'id' } <NEW_LINE> def __init__(self, text=None, id=None, local_vars_configuration=None): <NEW_LINE> <INDENT> if local_vars_configuration is None: <NEW_LINE> <INDENT> local_vars_configuration = Configuration() <NEW_LINE> <DEDENT> self.local_vars_configuration = local_vars_configuration <NEW_LINE> self._text = None <NEW_LINE> self._id = None <NEW_LINE> self.discriminator = None <NEW_LINE> if text is not None: <NEW_LINE> <INDENT> self.text = text <NEW_LINE> <DEDENT> if id is not None: <NEW_LINE> <INDENT> self.id = id <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def text(self): <NEW_LINE> <INDENT> return self._text <NEW_LINE> <DEDENT> @text.setter <NEW_LINE> def text(self, text): <NEW_LINE> <INDENT> self._text = text <NEW_LINE> <DEDENT> @property <NEW_LINE> def id(self): <NEW_LINE> <INDENT> return self._id <NEW_LINE> <DEDENT> @id.setter <NEW_LINE> def id(self, id): <NEW_LINE> <INDENT> self._id = id <NEW_LINE> <DEDENT> def to_dict(self, serialize=False): <NEW_LINE> <INDENT> result = {} <NEW_LINE> def convert(x): <NEW_LINE> <INDENT> if hasattr(x, "to_dict"): <NEW_LINE> <INDENT> args = inspect.getargspec(x.to_dict).args <NEW_LINE> if len(args) == 1: <NEW_LINE> <INDENT> return x.to_dict() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return x.to_dict(serialize) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return x <NEW_LINE> <DEDENT> <DEDENT> for attr, _ in six.iteritems(self.openapi_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> attr = self.attribute_map.get(attr, attr) if serialize else attr <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: convert(x), value )) <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], convert(item[1])), value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = convert(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, BatchTextRequest): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.to_dict() == other.to_dict() <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, BatchTextRequest): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.to_dict() != other.to_dict()
NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually.
62598fb1aad79263cf42e82f
class TokenAuthView(APIView): <NEW_LINE> <INDENT> def post(self, request): <NEW_LINE> <INDENT> token = request.data['token'] <NEW_LINE> userName = request.data['userName'] <NEW_LINE> decodeToken = jwt.decode(token, SECRET_KEY, JWT_ALGORITHM) <NEW_LINE> AuthUserName = User.objects.get(email=decodeToken['user_email']).name <NEW_LINE> if userName == AuthUserName: <NEW_LINE> <INDENT> content = {"auth_result": "grant", "user_email": decodeToken['user_email'], "message": "유저 인증 성공"} <NEW_LINE> return Response(content, status=status.HTTP_200_OK) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> content = {"auth_result": "revoke", "message": "(!) 다시 로그인해주세요."} <NEW_LINE> return Response(content, status=status.HTTP_200_OK)
POST /api/token/auth
62598fb166656f66f7d5a44c
class OpenedheaterDw0: <NEW_LINE> <INDENT> energy = 'internel' <NEW_LINE> devtype = "FWH-OPEN-DW0" <NEW_LINE> def __init__(self, dictDev): <NEW_LINE> <INDENT> self.name = dictDev['name'] <NEW_LINE> self.iPort = Port(dictDev['iPort']) <NEW_LINE> self.iPort_fw = Port(dictDev['iPort_fw']) <NEW_LINE> self.oPort_fw = Port(dictDev['oPort_fw']) <NEW_LINE> self.heatAdded = 0 <NEW_LINE> self.heatExtracted = 0 <NEW_LINE> self.QExtracted = 0 <NEW_LINE> <DEDENT> def state(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def balance(self): <NEW_LINE> <INDENT> qes1 = self.iPort.h - self.oPort_fw.h <NEW_LINE> qfw1 = self.oPort_fw.h - self.iPort_fw.h <NEW_LINE> self.iPort.fdot = self.oPort_fw.fdot * qfw1/(qes1 + qfw1) <NEW_LINE> self.iPort_fw.fdot = self.oPort_fw.fdot - self.iPort.fdot <NEW_LINE> self.heatAdded = self.iPort_fw.fdot * qfw1 <NEW_LINE> self.heatExtracted = self.iPort.fdot * qes1 <NEW_LINE> <DEDENT> def equation_rows(self): <NEW_LINE> <INDENT> colidm = [(self.iPort.id, 1), (self.iPort_fw.id, 1), (self.oPort_fw.id, -1)] <NEW_LINE> rowm = {"a": colidm, "b": 0} <NEW_LINE> colide = [(self.iPort.id, self.iPort.h), (self.iPort_fw.id, self.iPort_fw.h), (self.oPort_fw.id, -self.oPort_fw.h)] <NEW_LINE> rowe = {"a": colide, "b": 0} <NEW_LINE> self.rows = [rowm, rowe] <NEW_LINE> <DEDENT> def energy_fdot(self): <NEW_LINE> <INDENT> qes1 = self.iPort.h - self.oPort_fw.h <NEW_LINE> qfw1 = self.oPort_fw.h - self.iPort_fw.h <NEW_LINE> self.heatAdded = self.iPort_fw.fdot * qfw1 <NEW_LINE> self.heatExtracted = self.iPort.fdot * qes1 <NEW_LINE> <DEDENT> def calmdot(self, totalmass): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def sm_energy(self): <NEW_LINE> <INDENT> ucovt = 3600.0 * 1000.0 <NEW_LINE> self.QExtracted = self.iPort.mdot * (self.iPort.h - self.oPort_fw.h)/ucovt <NEW_LINE> self.QAdded = self.iPort_fw.mdot * (self.oPort_fw.h - self.iPort_fw.h)/ucovt <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> result = '\n' + self.name <NEW_LINE> result += '\n' + " PORT " + Port.title <NEW_LINE> result += '\n'+" iPort " + self.iPort.__str__() <NEW_LINE> result += '\n'+" iPort_fw " + self.iPort_fw.__str__() <NEW_LINE> result += '\n' + " oPort_fw " + self.oPort_fw.__str__() <NEW_LINE> result += '\nheatAdded(kJ) \t{:>.2f}'.format(self.heatAdded) <NEW_LINE> result += '\nheatExtracted(kJ) \t{:>.2f}'.format(self.heatExtracted) <NEW_LINE> try: <NEW_LINE> <INDENT> result += '\nQAdded(MW) \t{:>.2f}'.format(self.QAdded) <NEW_LINE> result += '\nQExtracted(MW) \t{:>.2f}'.format(self.QExtracted) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return result
so and sm
62598fb1090684286d59370b
class Blog(models.Model): <NEW_LINE> <INDENT> caption = models.CharField(max_length=50) <NEW_LINE> author = models.ForeignKey(Author) <NEW_LINE> tags = models.ManyToManyField(Tag, blank=True) <NEW_LINE> content = models.TextField() <NEW_LINE> publish_time = models.DateTimeField(auto_now_add=True) <NEW_LINE> update_time = models.DateTimeField(auto_now=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> ordering = ['-publish_time'] <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return u'%s %s %s' % (self.caption, self.author, self.publish_time)
docstring for Blogs
62598fb121bff66bcd722cc4
class MlpPolicy(FeedForwardPolicy): <NEW_LINE> <INDENT> def __init__(self, sess, ob_space, ac_space, n_env, n_steps, n_batch, reuse=False, obs_phs=None, dueling=True, **_kwargs): <NEW_LINE> <INDENT> super(MlpPolicy, self).__init__(sess, ob_space, ac_space, n_env, n_steps, n_batch, reuse, feature_extraction="mlp", obs_phs=obs_phs, dueling=dueling, layer_norm=False, **_kwargs)
Policy object that implements DQN policy, using a MLP (2 layers of 64) :param sess: (TensorFlow session) The current TensorFlow session :param ob_space: (Gym Space) The observation space of the environment :param ac_space: (Gym Space) The action space of the environment :param n_env: (int) The number of environments to run :param n_steps: (int) The number of steps to run for each environment :param n_batch: (int) The number of batch to run (n_envs * n_steps) :param reuse: (bool) If the policy is reusable or not :param obs_phs: (TensorFlow Tensor, TensorFlow Tensor) a tuple containing an override for observation placeholder and the processed observation placeholder respectively :param dueling: (bool) if true double the output MLP to compute a baseline for action scores :param _kwargs: (dict) Extra keyword arguments for the nature CNN feature extraction
62598fb18da39b475be03243
class WaterCost(BSElement): <NEW_LINE> <INDENT> element_type = "xs:decimal"
Annual cost of water. ($)
62598fb14527f215b58e9f31
class Section(unittest.TestCase): <NEW_LINE> <INDENT> def test_level6(self): <NEW_LINE> <INDENT> s = wtp.Section('====== == ======\n') <NEW_LINE> self.assertEqual(6, s.level) <NEW_LINE> self.assertEqual(' == ', s.title) <NEW_LINE> <DEDENT> def test_nolevel7(self): <NEW_LINE> <INDENT> s = wtp.Section('======= h6 =======\n') <NEW_LINE> self.assertEqual(6, s.level) <NEW_LINE> self.assertEqual('= h6 =', s.title) <NEW_LINE> <DEDENT> def test_unbalanced_equalsigns_in_title(self): <NEW_LINE> <INDENT> s = wtp.Section('====== == \n') <NEW_LINE> self.assertEqual(2, s.level) <NEW_LINE> self.assertEqual('==== ', s.title) <NEW_LINE> s = wtp.Section('== ====== \n') <NEW_LINE> self.assertEqual(2, s.level) <NEW_LINE> self.assertEqual(' ====', s.title) <NEW_LINE> s = wtp.Section('======== \n') <NEW_LINE> self.assertEqual(3, s.level) <NEW_LINE> self.assertEqual('==', s.title) <NEW_LINE> <DEDENT> def test_leadsection(self): <NEW_LINE> <INDENT> s = wtp.Section('lead text. \n== section ==\ntext.') <NEW_LINE> self.assertEqual(0, s.level) <NEW_LINE> self.assertEqual('', s.title) <NEW_LINE> <DEDENT> def test_set_title(self): <NEW_LINE> <INDENT> s = wtp.Section('== section ==\ntext.') <NEW_LINE> s.title = ' newtitle ' <NEW_LINE> self.assertEqual(' newtitle ', s.title) <NEW_LINE> <DEDENT> @unittest.expectedFailure <NEW_LINE> def test_lead_set_title(self): <NEW_LINE> <INDENT> s = wtp.Section('lead text') <NEW_LINE> s.title = ' newtitle ' <NEW_LINE> <DEDENT> def test_set_contents(self): <NEW_LINE> <INDENT> s = wtp.Section('== title ==\ntext.') <NEW_LINE> s.contents = ' newcontents ' <NEW_LINE> self.assertEqual(' newcontents ', s.contents) <NEW_LINE> <DEDENT> def test_set_lead_contents(self): <NEW_LINE> <INDENT> s = wtp.Section('lead') <NEW_LINE> s.contents = 'newlead' <NEW_LINE> self.assertEqual('newlead', s.string) <NEW_LINE> <DEDENT> def test_set_level(self): <NEW_LINE> <INDENT> s = wtp.Section('=== t ===\ntext') <NEW_LINE> s.level = 2 <NEW_LINE> self.assertEqual('== t ==\ntext', s.string)
Test the Section class.
62598fb1a17c0f6771d5c292
class CheckResultNotice(Event): <NEW_LINE> <INDENT> def __init__(self, player_id, side): <NEW_LINE> <INDENT> self.player_id = player_id <NEW_LINE> self.side = side
Special Notice for Sheriff, results of night check
62598fb167a9b606de54602b
class ParametricConcurrent(nn.Sequential): <NEW_LINE> <INDENT> def __init__(self, axis=1): <NEW_LINE> <INDENT> super(ParametricConcurrent, self).__init__() <NEW_LINE> self.axis = axis <NEW_LINE> <DEDENT> def forward(self, x, **kwargs): <NEW_LINE> <INDENT> out = [] <NEW_LINE> for module in self._modules.values(): <NEW_LINE> <INDENT> out.append(module(x, **kwargs)) <NEW_LINE> <DEDENT> out = torch.cat(tuple(out), dim=self.axis) <NEW_LINE> return out
A container for concatenation of modules with parameters. Parameters: ---------- axis : int, default 1 The axis on which to concatenate the outputs.
62598fb171ff763f4b5e77cf
class ChoiceOfMovementError(GameError): <NEW_LINE> <INDENT> pass
コマの移動が適切でない時のエラー
62598fb14428ac0f6e658583
class Noun: <NEW_LINE> <INDENT> def __init__(self, noun, article): <NEW_LINE> <INDENT> self.noun = noun <NEW_LINE> self.article = article
Represents a noun with its respective article.
62598fb14f6381625f1994ee
class BusinessMonthBegin(CacheableOffset, DateOffset): <NEW_LINE> <INDENT> def apply(self, other): <NEW_LINE> <INDENT> n = self.n <NEW_LINE> wkday, _ = tslib.monthrange(other.year, other.month) <NEW_LINE> first = _get_firstbday(wkday) <NEW_LINE> if other.day > first and n <= 0: <NEW_LINE> <INDENT> n += 1 <NEW_LINE> <DEDENT> elif other.day < first and n > 0: <NEW_LINE> <INDENT> other = other + timedelta(days=first - other.day) <NEW_LINE> n -= 1 <NEW_LINE> <DEDENT> other = other + relativedelta(months=n) <NEW_LINE> wkday, _ = tslib.monthrange(other.year, other.month) <NEW_LINE> first = _get_firstbday(wkday) <NEW_LINE> result = datetime(other.year, other.month, first) <NEW_LINE> return result <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def onOffset(cls, dt): <NEW_LINE> <INDENT> first_weekday, _ = tslib.monthrange(dt.year, dt.month) <NEW_LINE> if first_weekday == 5: <NEW_LINE> <INDENT> return dt.day == 3 <NEW_LINE> <DEDENT> elif first_weekday == 6: <NEW_LINE> <INDENT> return dt.day == 2 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return dt.day == 1 <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def rule_code(self): <NEW_LINE> <INDENT> return 'BMS'
DateOffset of one business month at beginning
62598fb157b8e32f5250814a
class RMSProp(LearningRule): <NEW_LINE> <INDENT> def __init__(self, decay=0.9, max_scaling=1e5, max_colm_norm=False, max_norm=15.0): <NEW_LINE> <INDENT> assert 0. <= decay < 1., 'decay must be: 0. <= decay < 1' <NEW_LINE> assert max_scaling > 0., 'max_scaling must be > 0.' <NEW_LINE> self.decay = sharedX_value(decay, name='decay', borrow=True) <NEW_LINE> self.epsilon = 1. / max_scaling <NEW_LINE> self.mean_square_grads = None <NEW_LINE> self._first_time = True <NEW_LINE> self.max_colm_norm = max_colm_norm <NEW_LINE> self.max_norm = max_norm <NEW_LINE> <DEDENT> def get_updates(self, learning_rate, params, grads, lr_scalers): <NEW_LINE> <INDENT> if self._first_time: <NEW_LINE> <INDENT> self.mean_square_grads = [ sharedX_mtx( param.get_value() * 0., name='mean_square_grad_'+param.name, borrow=True) for param in params] <NEW_LINE> self._first_time = False <NEW_LINE> <DEDENT> updates = [] <NEW_LINE> for (param, grad, mean_square_grad, lr_sc) in zip( params, grads, self.mean_square_grads, lr_scalers): <NEW_LINE> <INDENT> new_mean_square_grad = ( self.decay * mean_square_grad + (1-self.decay) * T.sqr(grad)) <NEW_LINE> rms_grad_t = T.sqrt(new_mean_square_grad) <NEW_LINE> rms_grad_t = T.maximum(rms_grad_t, self.epsilon) <NEW_LINE> lr_scaled = learning_rate * lr_sc <NEW_LINE> delta_x_t = - lr_scaled * grad / rms_grad_t <NEW_LINE> new_param = param + delta_x_t <NEW_LINE> if self.max_colm_norm and param.name in ["W", "w"]: <NEW_LINE> <INDENT> new_param_final = norm_constraint(tensor_var=new_param, max_norm=self.max_norm) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> new_param_final = new_param <NEW_LINE> <DEDENT> updates.append((param, new_param_final)) <NEW_LINE> updates.append((mean_square_grad, new_mean_square_grad)) <NEW_LINE> <DEDENT> return updates
Implements the RMSProp learning rule as described in [1]. The RMSProp rule was described in [1]. The idea is similar to the AdaDelta, which consists of dividing the learning rate for a weight by a running average of the magintudes of recent graidients of that weight. Parameters: decay: float Decay constant similar to the one used in AdaDelta, and Momentum. max_scaling: float Restrict the RMSProp gradient scaling coefficient to values below 'max_scaling' to avoid a learning rate too small (almost zero). [1]: 'Neural Networks for Machine Learning, Lecture 6a Overview of mini-­‐batch gradient descent', a lecture by Hinton et al. (http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf)
62598fb191f36d47f2230ed6
class Adjunto(models.Model): <NEW_LINE> <INDENT> nombre = models.CharField(max_length=100, null=True) <NEW_LINE> descripcion = models.TextField() <NEW_LINE> binario = models.BinaryField(null=True, blank=True) <NEW_LINE> content_type = models.CharField(null=True, editable=False, max_length=50) <NEW_LINE> fechaCreacion = models.DateTimeField(auto_now_add=True) <NEW_LINE> trabajo = models.ForeignKey(Trabajo) <NEW_LINE> def img64(self): <NEW_LINE> <INDENT> return b64encode(force_bytes(self.binario)) <NEW_LINE> <DEDENT> def get_download_url(self): <NEW_LINE> <INDENT> return reverse_lazy('download_attachment', args=[self.pk])
Modelo que repsenta a un archivo @cvar binario: Campo de tipo binario que almacena el archivo adjunto @cvar id_trabajo: clave foranea a un trabajo en el cual se cargo el archivo @cvar nombre: un campo de texto con el nombre que representa el archivo
62598fb144b2445a339b69a0
class DescribeRestoreJobController(object): <NEW_LINE> <INDENT> @probe.Probe(__name__) <NEW_LINE> def process_request(self, req, project_id, table_name, restore_job_id): <NEW_LINE> <INDENT> utils.check_project_id(req.context, project_id) <NEW_LINE> req.context.tenant = project_id <NEW_LINE> validation.validate_table_name(table_name) <NEW_LINE> restore_job = None <NEW_LINE> href_prefix = req.path_url <NEW_LINE> response = parser.Parser.format_restore_job(restore_job, href_prefix) <NEW_LINE> return response
Describes a restore job.
62598fb1cc0a2c111447b070
class BinNodeList(osid_objects.OsidList): <NEW_LINE> <INDENT> def get_next_bin_node(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> next_bin_node = property(fget=get_next_bin_node) <NEW_LINE> def get_next_bin_nodes(self, n): <NEW_LINE> <INDENT> return
Like all ``OsidLists,`` ``BinNodeList`` provides a means for accessing ``BinNode`` elements sequentially either one at a time or many at a time. Examples: while (bnl.hasNext()) { BinNode node = bnl.getNextBinNode(); } or while (bnl.hasNext()) { BinNode[] nodes = bnl.getNextBinNodes(bnl.available()); }
62598fb17d43ff2487427431
class Video(models.Model): <NEW_LINE> <INDENT> id=models.AutoField(primary_key=True) <NEW_LINE> Catalog = models.ForeignKey('Catalog', on_delete=models.PROTECT, null=True, verbose_name="目录项") <NEW_LINE> over_time = models.CharField(max_length=128,verbose_name="完成最短用时") <NEW_LINE> video = models.FileField(upload_to='upload/video/course/%Y/%m/%d', null=True,verbose_name="视频") <NEW_LINE> c_time = models.DateTimeField(auto_now_add=True) <NEW_LINE> u_time = models.DateTimeField(auto_now=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.id.__str__() <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> db_table = "video" <NEW_LINE> ordering = ['c_time'] <NEW_LINE> verbose_name = '视频' <NEW_LINE> verbose_name_plural = '视频'
视频表
62598fb163b5f9789fe851c7
class LogParabolaSpectralModel(SpectralModel): <NEW_LINE> <INDENT> tag = ["LogParabolaSpectralModel", "lp"] <NEW_LINE> amplitude = Parameter( "amplitude", "1e-12 cm-2 s-1 TeV-1", scale_method="scale10", interp="log" ) <NEW_LINE> reference = Parameter("reference", "10 TeV", frozen=True) <NEW_LINE> alpha = Parameter("alpha", 2) <NEW_LINE> beta = Parameter("beta", 1) <NEW_LINE> @classmethod <NEW_LINE> def from_log10(cls, amplitude, reference, alpha, beta): <NEW_LINE> <INDENT> beta_ = beta / np.log(10) <NEW_LINE> return cls(amplitude=amplitude, reference=reference, alpha=alpha, beta=beta_) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def evaluate(energy, amplitude, reference, alpha, beta): <NEW_LINE> <INDENT> xx = energy / reference <NEW_LINE> exponent = -alpha - beta * np.log(xx) <NEW_LINE> return amplitude * np.power(xx, exponent) <NEW_LINE> <DEDENT> @property <NEW_LINE> def e_peak(self): <NEW_LINE> <INDENT> reference = self.reference.quantity <NEW_LINE> alpha = self.alpha.quantity <NEW_LINE> beta = self.beta.quantity <NEW_LINE> return reference * np.exp((2 - alpha) / (2 * beta))
Spectral log parabola model. For more information see :ref:`logparabola-spectral-model`. Parameters ---------- amplitude : `~astropy.units.Quantity` :math:`\phi_0` reference : `~astropy.units.Quantity` :math:`E_0` alpha : `~astropy.units.Quantity` :math:`\alpha` beta : `~astropy.units.Quantity` :math:`\beta` See Also -------- LogParabolaNormSpectralModel
62598fb1aad79263cf42e831
class FileIDType(Enum): <NEW_LINE> <INDENT> SettlementFund = 70 <NEW_LINE> Trade = 84 <NEW_LINE> InvestorPosition = 80 <NEW_LINE> SubEntryFund = 79 <NEW_LINE> CZCECombinationPos = 67 <NEW_LINE> CSRCData = 82 <NEW_LINE> CZCEClose = 76 <NEW_LINE> CZCENoClose = 78 <NEW_LINE> PositionDtl = 68 <NEW_LINE> OptionStrike = 83 <NEW_LINE> SettlementPriceComparison = 77 <NEW_LINE> NonTradePosChange = 66 <NEW_LINE> def __int__(self): <NEW_LINE> <INDENT> return self.value <NEW_LINE> <DEDENT> def __char__(self): <NEW_LINE> <INDENT> return chr(self.value)
文件标识类型
62598fb1e5267d203ee6b966
class New(object): <NEW_LINE> <INDENT> form = web.form.Form( web.form.Textbox('name', not_too_short(3), size=30, description='Model name:'), web.form.Textarea('json', not_bad_json, rows=40, cols=80, description=None), web.form.Button('Save') ) <NEW_LINE> def GET(self): <NEW_LINE> <INDENT> return render.new(self.form()) <NEW_LINE> <DEDENT> def POST(self): <NEW_LINE> <INDENT> web.header('Content-Type', 'application/json; charset=utf-8') <NEW_LINE> form = self.form() <NEW_LINE> if not form.validates(): <NEW_LINE> <INDENT> return render.new(form) <NEW_LINE> <DEDENT> id = models.new_model(form.d.name, form.d.json, owner=get_username()) <NEW_LINE> return json.dumps(id)
Create a new model. To create a new model, go here: * https://csdms.colorado.edu/wmt/models/new You could also just POST some JSON to this URL. A valid JSON description of a model is simply a valid JSON file of an object with a member called *model*. The simplest example would be:: { "model": 0 } > curl -i -X POST -F name=ModelName -F json=@model.json https://csdms.colorado.edu/wmt/models/new
62598fb166656f66f7d5a44e
class RewardRequest(Model): <NEW_LINE> <INDENT> _validation = { 'value': {'required': True}, } <NEW_LINE> _attribute_map = { 'value': {'key': 'value', 'type': 'float'}, } <NEW_LINE> def __init__(self, *, value: float, **kwargs) -> None: <NEW_LINE> <INDENT> super(RewardRequest, self).__init__(**kwargs) <NEW_LINE> self.value = value
Reward given to a rank response. All required parameters must be populated in order to send to Azure. :param value: Required. Reward to be assigned to an action. Value should be between -1 and 1 inclusive. :type value: float
62598fb1aad79263cf42e832
@tag('medida') <NEW_LINE> class MedidaListViewTestCase(MedidaViewHelper): <NEW_LINE> <INDENT> target_url = reverse('medidas:lista-medidas') <NEW_LINE> def test_url_view_correspondence(self): <NEW_LINE> <INDENT> self.login() <NEW_LINE> response = self.client.get(self.target_url) <NEW_LINE> actual = response.resolver_match.func.__name__ <NEW_LINE> expected = MedidaListView.as_view().__name__ <NEW_LINE> self.assertEqual(actual, expected, 'La vista de listado de medidas no ' 'es MedidaListView') <NEW_LINE> <DEDENT> def test_login_required(self): <NEW_LINE> <INDENT> login_url = reverse('login') <NEW_LINE> response = self.client.get(self.target_url) <NEW_LINE> actual = response <NEW_LINE> expected = login_url + '?next=' + self.target_url <NEW_LINE> self.assertRedirects(actual, expected, msg_prefix='La vista de listado de medidas no requiered login') <NEW_LINE> <DEDENT> def test_contexto_tiene_lista(self): <NEW_LINE> <INDENT> self.login() <NEW_LINE> response = self.client.get(self.target_url) <NEW_LINE> actual = response.context['object_list'] <NEW_LINE> expected = Medida.objects.all() <NEW_LINE> self.assertEqual(list(actual), list(expected), 'La lista de medidas no es correcta') <NEW_LINE> <DEDENT> def test_template_correcto(self): <NEW_LINE> <INDENT> self.login() <NEW_LINE> response = self.client.get(self.target_url) <NEW_LINE> actual = response <NEW_LINE> expected = 'medidas/list.html' <NEW_LINE> self.assertTemplateUsed(actual, expected)
Pruebas para la vista de listado de medidas
62598fb123849d37ff851112