code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class FileObjectAdapter(tink_bindings.PythonFileObjectAdapter): <NEW_LINE> <INDENT> def __init__(self, file_object: BinaryIO): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self._file_object = file_object <NEW_LINE> <DEDENT> def write(self, data: bytes) -> int: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> written = self._file_object.write(data) <NEW_LINE> return 0 if written is None else written <NEW_LINE> <DEDENT> except io.BlockingIOError as e: <NEW_LINE> <INDENT> return e.characters_written <NEW_LINE> <DEDENT> <DEDENT> def close(self) -> None: <NEW_LINE> <INDENT> self._file_object.close() <NEW_LINE> <DEDENT> def read(self, size: int) -> bytes: <NEW_LINE> <INDENT> if size < 0: <NEW_LINE> <INDENT> raise ValueError('size must be non-negative') <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> data = self._file_object.read(size) <NEW_LINE> if data is None: <NEW_LINE> <INDENT> return b'' <NEW_LINE> <DEDENT> elif not data and size > 0: <NEW_LINE> <INDENT> raise EOFError('EOF') <NEW_LINE> <DEDENT> return data <NEW_LINE> <DEDENT> except io.BlockingIOError: <NEW_LINE> <INDENT> return b'' | Adapts a Python file object for use in C++. | 62598f9d60cbc95b06364128 |
class AirflowNetworkDistributionComponentLeak(DataObject): <NEW_LINE> <INDENT> _schema = {'extensible-fields': OrderedDict(), 'fields': OrderedDict([(u'name', {'name': u'Name', 'pyname': u'name', 'required-field': True, 'autosizable': False, 'autocalculatable': False, 'type': u'alpha'}), (u'air mass flow coefficient', {'name': u'Air Mass Flow Coefficient', 'pyname': u'air_mass_flow_coefficient', 'minimum>': 0.0, 'required-field': True, 'autosizable': False, 'autocalculatable': False, 'type': u'real', 'unit': u'kg/s'}), (u'air mass flow exponent', {'name': u'Air Mass Flow Exponent', 'pyname': u'air_mass_flow_exponent', 'default': 0.65, 'maximum': 1.0, 'required-field': False, 'autosizable': False, 'minimum': 0.5, 'autocalculatable': False, 'type': u'real', 'unit': u'dimensionless'})]), 'format': None, 'group': u'Natural Ventilation and Duct Leakage', 'min-fields': 3, 'name': u'AirflowNetwork:Distribution:Component:Leak', 'pyname': u'AirflowNetworkDistributionComponentLeak', 'required-object': False, 'unique-object': False} <NEW_LINE> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self["Name"] <NEW_LINE> <DEDENT> @name.setter <NEW_LINE> def name(self, value=None): <NEW_LINE> <INDENT> self["Name"] = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def air_mass_flow_coefficient(self): <NEW_LINE> <INDENT> return self["Air Mass Flow Coefficient"] <NEW_LINE> <DEDENT> @air_mass_flow_coefficient.setter <NEW_LINE> def air_mass_flow_coefficient(self, value=None): <NEW_LINE> <INDENT> self["Air Mass Flow Coefficient"] = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def air_mass_flow_exponent(self): <NEW_LINE> <INDENT> return self["Air Mass Flow Exponent"] <NEW_LINE> <DEDENT> @air_mass_flow_exponent.setter <NEW_LINE> def air_mass_flow_exponent(self, value=0.65): <NEW_LINE> <INDENT> self["Air Mass Flow Exponent"] = value | Corresponds to IDD object `AirflowNetwork:Distribution:Component:Leak`
This object defines the characteristics of a supply or return air leak. | 62598f9d7b25080760ed7281 |
class Toolbar_Videos_Izquierda(Gtk.Toolbar): <NEW_LINE> <INDENT> __gsignals__ = { "borrar": (GObject.SIGNAL_RUN_FIRST, GObject.TYPE_NONE, []), "mover_videos": (GObject.SIGNAL_RUN_FIRST, GObject.TYPE_NONE, [])} <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> Gtk.Toolbar.__init__(self) <NEW_LINE> self.insert(get_separador(draw=False, ancho=0, expand=True), -1) <NEW_LINE> archivo = os.path.join(BASE_PATH, "Iconos", "alejar.svg") <NEW_LINE> boton = get_boton(archivo, flip=False, pixels=24) <NEW_LINE> boton.set_tooltip_text("Borrar Lista") <NEW_LINE> boton.connect("clicked", self.__emit_borrar) <NEW_LINE> self.insert(boton, -1) <NEW_LINE> archivo = os.path.join(BASE_PATH, "Iconos", "iconplay.svg") <NEW_LINE> boton = get_boton(archivo, flip=False, pixels=24) <NEW_LINE> boton.set_tooltip_text("Enviar a Descargas") <NEW_LINE> boton.connect("clicked", self.__emit_adescargas) <NEW_LINE> self.insert(boton, -1) <NEW_LINE> self.show_all() <NEW_LINE> <DEDENT> def __emit_adescargas(self, widget): <NEW_LINE> <INDENT> self.emit('mover_videos') <NEW_LINE> <DEDENT> def __emit_borrar(self, widget): <NEW_LINE> <INDENT> self.emit('borrar') | toolbar inferior izquierda para videos encontrados. | 62598f9d6e29344779b00437 |
class SingleValueFitnessFunction(FitnessFunction): <NEW_LINE> <INDENT> def __call__(self, individual): <NEW_LINE> <INDENT> self.eval_count += 1 <NEW_LINE> return individual.value | Fitness for single valued chromosomes
Fitness equals the chromosomes value. | 62598f9d009cb60464d01300 |
class DWalker: <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def entries(fs_entry_params): <NEW_LINE> <INDENT> for rpath, dnames, fnames in os.walk(fs_entry_params.src_dir): <NEW_LINE> <INDENT> fs_entry_params.rpath = rpath <NEW_LINE> if fs_entry_params.skip_iteration: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> fs_entry_params.fnames = fnames <NEW_LINE> fs_entry_params.dnames = dnames <NEW_LINE> dnames[:] = fs_entry_params.merged_dnames <NEW_LINE> yield from fs_entry_params.fs_entry_builder.build_root_entry(fs_entry_params) <NEW_LINE> yield from fs_entry_params.fs_entry_builder.build_entry(fs_entry_params) <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def file_entries(fs_entry_params, pass_filter = None): <NEW_LINE> <INDENT> if not pass_filter: <NEW_LINE> <INDENT> pass_filter = lambda f: True <NEW_LINE> <DEDENT> for entry in DWalker.entries(fs_entry_params): <NEW_LINE> <INDENT> if entry.type in (FSEntryType.ROOT, FSEntryType.DIR): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if not pass_filter(entry.realpath): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> yield entry <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def dir_entries(fs_entry_params, pass_filter = None): <NEW_LINE> <INDENT> if not pass_filter: <NEW_LINE> <INDENT> pass_filter = lambda f: True <NEW_LINE> <DEDENT> for entry in DWalker.entries(fs_entry_params): <NEW_LINE> <INDENT> if entry.type in (FSEntryType.ROOT, FSEntryType.FILE): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if not pass_filter(entry.realpath): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> yield entry | Walks content of a directory, generating
a sequence of structured FS elements (FSEntry) | 62598f9da79ad16197769e3f |
class ExpectimaxAgent(MultiAgentSearchAgent): <NEW_LINE> <INDENT> def value(self, gameState, agentIndex, depth): <NEW_LINE> <INDENT> numAgents=gameState.getNumAgents() <NEW_LINE> if gameState.isWin() or gameState.isLose(): <NEW_LINE> <INDENT> v=self.evaluationFunction(gameState) <NEW_LINE> <DEDENT> elif agentIndex==(numAgents-1): <NEW_LINE> <INDENT> v=self.maxValue(gameState, depth) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> agentIndex+=1 <NEW_LINE> v=self.expValue(gameState, agentIndex,depth) <NEW_LINE> <DEDENT> return v <NEW_LINE> <DEDENT> def expValue(self, gameState, agentIndex, depth): <NEW_LINE> <INDENT> v=0 <NEW_LINE> listOfActions=gameState.getLegalActions(agentIndex) <NEW_LINE> for action in listOfActions: <NEW_LINE> <INDENT> successor=gameState.generateSuccessor(agentIndex,action) <NEW_LINE> p=1.0/len(listOfActions) <NEW_LINE> v+=p*self.value(successor, agentIndex, depth) <NEW_LINE> <DEDENT> return v <NEW_LINE> <DEDENT> def maxValue(self, gameState, depth): <NEW_LINE> <INDENT> if depth==self.depth: <NEW_LINE> <INDENT> v=self.evaluationFunction(gameState) <NEW_LINE> return v <NEW_LINE> <DEDENT> depth+=1 <NEW_LINE> v=-float('inf') <NEW_LINE> listOfActions=gameState.getLegalActions(0) <NEW_LINE> for action in listOfActions: <NEW_LINE> <INDENT> successor=gameState.generateSuccessor(0,action) <NEW_LINE> v=max(v, self.value(successor,0,depth)) <NEW_LINE> <DEDENT> return v <NEW_LINE> <DEDENT> def minValue(self, gameState, agentIndex, depth): <NEW_LINE> <INDENT> v=float('inf') <NEW_LINE> listOfActions=gameState.getLegalActions(agentIndex) <NEW_LINE> for action in listOfActions: <NEW_LINE> <INDENT> successor=gameState.generateSuccessor(agentIndex,action) <NEW_LINE> v=min(v,self.value(successor, agentIndex, depth)) <NEW_LINE> <DEDENT> return v <NEW_LINE> <DEDENT> def getBestAction(self, gameState): <NEW_LINE> <INDENT> listOfActions=gameState.getLegalActions(0) <NEW_LINE> v=-float('inf') <NEW_LINE> best=-float('inf') <NEW_LINE> bestAction=Directions.STOP <NEW_LINE> allActions=[] <NEW_LINE> for action in listOfActions: <NEW_LINE> <INDENT> if action!=Directions.STOP: <NEW_LINE> <INDENT> allActions.append(action) <NEW_LINE> listOfActions.remove(action) <NEW_LINE> <DEDENT> <DEDENT> for action in listOfActions: <NEW_LINE> <INDENT> allActions.append(action) <NEW_LINE> <DEDENT> for action in allActions: <NEW_LINE> <INDENT> successor=gameState.generateSuccessor(0,action) <NEW_LINE> if successor.isWin() or successor.isLose(): <NEW_LINE> <INDENT> v=self.evaluationFunction(successor) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> v=max(v, self.expValue(successor, 1, 1)) <NEW_LINE> <DEDENT> if v>best: <NEW_LINE> <INDENT> best=v <NEW_LINE> bestAction=action <NEW_LINE> <DEDENT> <DEDENT> return bestAction <NEW_LINE> <DEDENT> def getAction(self, gameState): <NEW_LINE> <INDENT> action=self.getBestAction(gameState) <NEW_LINE> return action | Your expectimax agent (question 4) | 62598f9d4f6381625f1993a9 |
class PascalProgram(object): <NEW_LINE> <INDENT> def __init__(self, file): <NEW_LINE> <INDENT> self._file = file <NEW_LINE> self._name = None <NEW_LINE> self._uses = None <NEW_LINE> self._block = None <NEW_LINE> self._code = dict() <NEW_LINE> self._meta_comment = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def code(self): <NEW_LINE> <INDENT> return self._code <NEW_LINE> <DEDENT> @property <NEW_LINE> def uses(self): <NEW_LINE> <INDENT> return self._uses.units <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @property <NEW_LINE> def block(self): <NEW_LINE> <INDENT> return self._block <NEW_LINE> <DEDENT> def resolve_function_call(self, function): <NEW_LINE> <INDENT> for unit in self._uses._units: <NEW_LINE> <INDENT> result = unit.points_to.contents.resolve_function_call(function) <NEW_LINE> if result != None: <NEW_LINE> <INDENT> return result <NEW_LINE> <DEDENT> <DEDENT> return None <NEW_LINE> <DEDENT> def resolve_variable(self, var): <NEW_LINE> <INDENT> for unit in self._uses._units: <NEW_LINE> <INDENT> for (key, variable) in unit.points_to.contents.variables.items(): <NEW_LINE> <INDENT> if (var == variable.name): <NEW_LINE> <INDENT> return variable <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return None <NEW_LINE> <DEDENT> def parse(self, tokens): <NEW_LINE> <INDENT> tokens.match_token(TokenKind.Identifier, 'program'); <NEW_LINE> self._name = tokens.match_token(TokenKind.Identifier)._value; <NEW_LINE> tokens.match_token(TokenKind.Symbol, ';') <NEW_LINE> if (tokens.match_lookahead(TokenKind.Identifier, 'uses')): <NEW_LINE> <INDENT> self._uses = PascalUsesClause(self._file) <NEW_LINE> self._uses.parse(tokens) <NEW_LINE> <DEDENT> self._block = PascalBlock(None, self._file) <NEW_LINE> self._block.parse(tokens) <NEW_LINE> <DEDENT> def to_code(self): <NEW_LINE> <INDENT> import converter_helper <NEW_LINE> if (self._uses != None): <NEW_LINE> <INDENT> self._uses.to_code() <NEW_LINE> <DEDENT> self._block.to_code() <NEW_LINE> for (name, module) in converter_helper.converters.items(): <NEW_LINE> <INDENT> my_data = dict() <NEW_LINE> if (self._uses != None): <NEW_LINE> <INDENT> my_data[name +'_uses'] = self._uses.code[name] <NEW_LINE> <DEDENT> my_data[name + '_name'] = self._name <NEW_LINE> my_data[name + '_block'] = self._block.code[name] <NEW_LINE> self._code[name] = module.program_template % my_data | The model object to represent a pascal program:
Syntax for a program is:
program = "program", identifier, ";", [uses clause], block, "." ;
block = "begin", { statement }+(";"), "end" ; | 62598f9d56b00c62f0fb268c |
class AttackManager(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(AttackManager, self).__init__() <NEW_LINE> <DEDENT> def manage(self, event): <NEW_LINE> <INDENT> LOGGER.info('Managing event: %s' % event) | Manager for attack type events. | 62598f9d01c39578d7f12b59 |
class GRUCell(RNNCellBase): <NEW_LINE> <INDENT> def __init__(self, input_size, hidden_size, bias=True): <NEW_LINE> <INDENT> super(GRUCell, self).__init__() <NEW_LINE> self.input_size = input_size <NEW_LINE> self.hidden_size = hidden_size <NEW_LINE> self.bias = bias <NEW_LINE> self.weight_ih = Parameter(torch.Tensor(3*hidden_size, input_size)) <NEW_LINE> self.weight_hh = Parameter(torch.Tensor(3*hidden_size, hidden_size)) <NEW_LINE> if bias: <NEW_LINE> <INDENT> self.bias_ih = Parameter(torch.Tensor(3*hidden_size)) <NEW_LINE> self.bias_hh = Parameter(torch.Tensor(3*hidden_size)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.register_parameter('bias_ih', None) <NEW_LINE> self.register_parameter('bias_hh', None) <NEW_LINE> <DEDENT> self.reset_parameters() <NEW_LINE> <DEDENT> def reset_parameters(self): <NEW_LINE> <INDENT> stdv = 1.0 / math.sqrt(self.hidden_size) <NEW_LINE> for weight in self.parameters(): <NEW_LINE> <INDENT> weight.data.uniform_(-stdv, stdv) <NEW_LINE> <DEDENT> <DEDENT> def forward(self, input, hx): <NEW_LINE> <INDENT> return self._backend.GRUCell( input, hx, self.weight_ih, self.weight_hh, self.bias_ih, self.bias_hh, ) | A gated recurrent unit (GRU) cell
.. math::
\begin{array}{ll}
r = sigmoid(W_{ir} x + b_{ir} + W_{hr} h + b_{hr}) \\
i = sigmoid(W_{ii} x + b_{ii} + W_{hi} h + b_{hi}) \\
n = \tanh(W_{in} x + r * W_{hn} h) \\
h' = (1 - i) * n + i * h
\end{array}
Args:
input_size: The number of expected features in the input x
hidden_size: The number of features in the hidden state h
bias: If `False`, then the layer does not use bias weights `b_ih` and `b_hh`. Default: `True`
Inputs: `input, hidden`
- `input` : A `(batch x input_size)` tensor containing input features
- `hidden` : A `(batch x hidden_size)` tensor containing the initial hidden state for each element in the batch.
Outputs: `h'`
- `h'`: A `(batch x hidden_size)` tensor containing the next hidden state for each element in the batch
Attributes:
weight_ih: the learnable input-hidden weights, of shape `(input_size x hidden_size)`
weight_hh: the learnable hidden-hidden weights, of shape `(hidden_size x hidden_size)`
bias_ih: the learnable input-hidden bias, of shape `(hidden_size)`
bias_hh: the learnable hidden-hidden bias, of shape `(hidden_size)`
Examples::
>>> rnn = nn.RNNCell(10, 20)
>>> input = Variable(torch.randn(6, 3, 10))
>>> hx = Variable(torch.randn(3, 20))
>>> output = []
>>> for i in range(6):
... hx = rnn(input, hx)
... output[i] = hx | 62598f9d442bda511e95c237 |
class IRmiSiteLayer(IDefaultBrowserLayer): <NEW_LINE> <INDENT> pass | Marker interface that defines a browser layer. | 62598f9d3c8af77a43b67e2c |
class __Instance: <NEW_LINE> <INDENT> def __init__(self, arg=None): <NEW_LINE> <INDENT> self.val = arg | a sample instance w/ only one param, arg | 62598f9d090684286d5935c8 |
class MPLengthHypothesis: <NEW_LINE> <INDENT> RATING_THRESHOLD = 0.3 <NEW_LINE> def __init__(self, maximum_interesting_length=4): <NEW_LINE> <INDENT> self.maximum_interesting_length = maximum_interesting_length <NEW_LINE> <DEDENT> def update(self, meta_path: MetaPath, rating: float) -> None: <NEW_LINE> <INDENT> if rating > self.RATING_THRESHOLD and len(meta_path) > self.maximum_interesting_length: <NEW_LINE> <INDENT> self.maximum_interesting_length = len(meta_path) <NEW_LINE> <DEDENT> <DEDENT> def predict_rating(self, meta_path: MetaPath) -> float: <NEW_LINE> <INDENT> if len(meta_path) > self.maximum_interesting_length: <NEW_LINE> <INDENT> return 1.0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 0.0 | A Hypothesis over a rating of meta-paths. It decides which meta-path will be sent to the oracle next.
This is just a simple example with a hypothesis, that the rating depends on the length of the meta-path and has a
cutoff at some length. | 62598f9d24f1403a926857a0 |
class AvroSerDeBase(ConfluentMessageSerializer): <NEW_LINE> <INDENT> def decode_message(self, message): <NEW_LINE> <INDENT> if message is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if len(message) <= 5: <NEW_LINE> <INDENT> raise SerializerError("message is too small to decode") <NEW_LINE> <DEDENT> with ContextStringIO(message) as payload: <NEW_LINE> <INDENT> magic, schema_id = struct.unpack(">bI", payload.read(5)) <NEW_LINE> if magic != MAGIC_BYTE: <NEW_LINE> <INDENT> raise SerializerError("message does not start with magic byte") <NEW_LINE> <DEDENT> decoder_func = self._get_decoder_func(schema_id, payload) <NEW_LINE> return _wrap(decoder_func(payload), self.registry_client.get_by_id(schema_id)) | A subclass of MessageSerializer from Confluent's kafka-python,
adding schema to deserialized Avro messages. | 62598f9d4e4d5625663721ff |
class SceneBalloonComponent(Component): <NEW_LINE> <INDENT> def __init__(self,owner): <NEW_LINE> <INDENT> Component.__init__(self,owner) | Balloon component for scene | 62598f9dd268445f26639a71 |
class _Collection(SlotNode): <NEW_LINE> <INDENT> __slots__ = () <NEW_LINE> def addChild(self, child): <NEW_LINE> <INDENT> if child.getName() != 'package': <NEW_LINE> <INDENT> raise UnknownElement(child) <NEW_LINE> <DEDENT> child.name = None <NEW_LINE> child.arch = None <NEW_LINE> child.version = None <NEW_LINE> child.release = None <NEW_LINE> child.checksum = None <NEW_LINE> child.archiveSize = None <NEW_LINE> child.location = '' <NEW_LINE> for attr, value in child.iterAttributes(): <NEW_LINE> <INDENT> if attr == 'name': <NEW_LINE> <INDENT> child.name = value <NEW_LINE> <DEDENT> elif attr == 'arch': <NEW_LINE> <INDENT> child.arch = value <NEW_LINE> <DEDENT> elif attr == 'version': <NEW_LINE> <INDENT> child.version = value <NEW_LINE> <DEDENT> elif attr == 'release': <NEW_LINE> <INDENT> child.release = value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise UnknownAttributeError(child, attr) <NEW_LINE> <DEDENT> <DEDENT> SlotNode.addChild(self, child) | Represents a pkglist collection in updateinfo.xml. | 62598f9d004d5f362081eeeb |
class ArrayPool(OutputPool): <NEW_LINE> <INDENT> def _make_store_for(self, node): <NEW_LINE> <INDENT> if not self.has_context: <NEW_LINE> <INDENT> raise ValueError('ArrayPool has no context set') <NEW_LINE> <DEDENT> os.makedirs(self.path, exist_ok=True) <NEW_LINE> filename = os.path.join(self.path, node) <NEW_LINE> return NpyStore(filename, self.batch_size) | OutputPool that uses binary .npy files as default stores.
The default store medium for output data is a NumPy binary `.npy` file for NumPy
array data. You can however also add other types of stores as well.
Notes
-----
The default store is implemented in elfi.store.NpyStore that uses NpyArrays as stores.
The NpyArray is a wrapper over NumPy .npy binary file for array data and supports
appending the .npy file. It uses the .npy format 2.0 files. | 62598f9d3cc13d1c6d465548 |
class CreateFolderMixin: <NEW_LINE> <INDENT> def _process(self): <NEW_LINE> <INDENT> form = AttachmentFolderForm(obj=FormDefaults(is_always_visible=True), linked_object=self.object) <NEW_LINE> if form.validate_on_submit(): <NEW_LINE> <INDENT> folder = AttachmentFolder(object=self.object) <NEW_LINE> form.populate_obj(folder, skip={'acl'}) <NEW_LINE> if folder.is_self_protected: <NEW_LINE> <INDENT> folder.acl = form.acl.data <NEW_LINE> <DEDENT> db.session.add(folder) <NEW_LINE> logger.info('Folder %s created by %s', folder, session.user) <NEW_LINE> signals.attachments.folder_created.send(folder, user=session.user) <NEW_LINE> flash(_("Folder \"{name}\" created").format(name=folder.title), 'success') <NEW_LINE> return jsonify_data(attachment_list=_render_attachment_list(self.object)) <NEW_LINE> <DEDENT> return jsonify_template('attachments/create_folder.html', form=form, protection_message=_render_protection_message(self.object)) | Create a new empty folder. | 62598f9dd7e4931a7ef3be75 |
class EntityTemplateTask(TypedDict, total=False): <NEW_LINE> <INDENT> complete: bool <NEW_LINE> description: str <NEW_LINE> external_id: str <NEW_LINE> owner_ids: List[ str ] | Request parameters for specifying how to pre-populate a task through a template. | 62598f9dd99f1b3c44d0548c |
class SearchableMixin: <NEW_LINE> <INDENT> __searchable__ = [] <NEW_LINE> @classmethod <NEW_LINE> def fulltext_query(cls, query_str, db_query): <NEW_LINE> <INDENT> query_str = '%{}%'.format(query_str) <NEW_LINE> condition = sqlalchemy.or_( *[getattr(cls, col).like(query_str) for col in cls.__searchable__] ) <NEW_LINE> return db_query.filter(condition) | Mixin for models that support fulltext query | 62598f9d1f037a2d8b9e3ec3 |
class KongZhengmin_Classifier(nn.Module): <NEW_LINE> <INDENT> def __init__(self, in_features, n_classes, return_sequence=False): <NEW_LINE> <INDENT> super(KongZhengmin_Classifier, self).__init__() <NEW_LINE> self.return_sequnce = return_sequence <NEW_LINE> self.module = nn.Sequential( nn.Linear(in_features=in_features, out_features=50), nn.ReLU(), nn.Linear(in_features=50, out_features=50), nn.ReLU(), nn.Linear(in_features=50, out_features=n_classes) ) <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> if self.return_sequnce: <NEW_LINE> <INDENT> return self.module(x) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.module(x[:, -1, :]) | Classifier of the Kong Zhengmin model.
Parameters
----------
in_features: int
Number of features of the input tensors
n_classes: int
Number of classes to predict at the end of the network
return_sequence: bool, defaults=True
Parameter that controls wether the module returns the sequence or the prediction.
Returns
-------
`LightningModule`
A pyTorch Lightning Module instance. | 62598f9d8e71fb1e983bb892 |
class ComputeInstancesSetTagsRequest(_messages.Message): <NEW_LINE> <INDENT> instance = _messages.StringField(1, required=True) <NEW_LINE> project = _messages.StringField(2, required=True) <NEW_LINE> tags = _messages.MessageField('Tags', 3) <NEW_LINE> zone = _messages.StringField(4, required=True) | A ComputeInstancesSetTagsRequest object.
Fields:
instance: Name of the instance scoping this request.
project: Project ID for this request.
tags: A Tags resource to be passed as the request body.
zone: The name of the zone for this request. | 62598f9d498bea3a75a578fd |
class ProyectoForm(forms.ModelForm): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = Proyecto <NEW_LINE> exclude = ('macroproyecto',) <NEW_LINE> labels={ 'nombreProyecto': ("Nombre"), 'descripcionProyecto': ("Descripción"), 'm2PorProyecto': ("Metros Cuadrados"), } | Form definition for Proyecto. | 62598f9d7047854f4633f1bf |
class DihedralType(_ListItem, _ParameterType): <NEW_LINE> <INDENT> def __init__(self, phi_k, per, phase, scee=1.0, scnb=1.0, list=None): <NEW_LINE> <INDENT> _ParameterType.__init__(self) <NEW_LINE> self.phi_k = _strip_units(phi_k, u.kilocalories_per_mole) <NEW_LINE> self.per = per <NEW_LINE> self.phase = _strip_units(phase, u.degrees) <NEW_LINE> self.scee = scee <NEW_LINE> self.scnb = scnb <NEW_LINE> self.list = list <NEW_LINE> self._idx = -1 <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return (self.phi_k == other.phi_k and self.per == other.per and self.phase == other.phase and self.scee == other.scee and self.scnb == other.scnb) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return ('<%s; phi_k=%.3f, per=%d, phase=%.3f, scee=%.3f, scnb=%.3f>' % (type(self).__name__, self.phi_k, self.per, self.phase, self.scee, self.scnb)) <NEW_LINE> <DEDENT> def __copy__(self): <NEW_LINE> <INDENT> return DihedralType(self.phi_k, self.per, self.phase, self.scee, self.scnb) | A dihedral type with a set of dihedral parameters
Parameters
----------
phi_k : ``float``
The force constant in kcal/mol
per : ``int``
The dihedral periodicity
phase : ``float``
The dihedral phase in degrees
scee : ``float``
1-4 electrostatic scaling factor
scnb : ``float``
1-4 Lennard-Jones scaling factor
list : :class:`TrackedList`
A list of `DihedralType`s in which this is a member
Inherited Attributes
--------------------
idx : ``int``
The index of this DihedralType inside its containing list
Notes
-----
Two :class:`DihedralType`s are equal if their `phi_k`, `per`, `phase`,
`scee`, and `scnb` attributes are equal
Examples
--------
>>> dt1 = DihedralType(10.0, 2, 180.0, 1.2, 2.0)
>>> dt2 = DihedralType(10.0, 2, 180.0, 1.2, 2.0)
>>> dt1 is dt2
False
>>> dt1 == dt2
True
>>> dt1.idx # not part of any list or iterable
-1
As part of a list, they can be indexed
>>> dihedral_list = []
>>> dihedral_list.append(DihedralType(10.0, 2, 180.0, 1.2, 2.0,
... list=dihedral_list))
>>> dihedral_list.append(DihedralType(10.0, 2, 180.0, 1.2, 2.0,
... list=dihedral_list))
>>> dihedral_list[0].idx
0
>>> dihedral_list[1].idx
1 | 62598f9d097d151d1a2c0e04 |
class Cart(object): <NEW_LINE> <INDENT> openapi_types = { 'cart_id': 'str', 'cart_total': 'float', 'contact': 'ContactBaseExtraFull', 'products': 'list[Product]' } <NEW_LINE> attribute_map = { 'cart_id': 'cart_id', 'cart_total': 'cart_total', 'contact': 'contact', 'products': 'products' } <NEW_LINE> def __init__(self, cart_id=None, cart_total=None, contact=None, products=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._cart_id = None <NEW_LINE> self._cart_total = None <NEW_LINE> self._contact = None <NEW_LINE> self._products = None <NEW_LINE> self.discriminator = None <NEW_LINE> if cart_id is not None: <NEW_LINE> <INDENT> self.cart_id = cart_id <NEW_LINE> <DEDENT> if cart_total is not None: <NEW_LINE> <INDENT> self.cart_total = cart_total <NEW_LINE> <DEDENT> if contact is not None: <NEW_LINE> <INDENT> self.contact = contact <NEW_LINE> <DEDENT> if products is not None: <NEW_LINE> <INDENT> self.products = products <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def cart_id(self): <NEW_LINE> <INDENT> return self._cart_id <NEW_LINE> <DEDENT> @cart_id.setter <NEW_LINE> def cart_id(self, cart_id): <NEW_LINE> <INDENT> self._cart_id = cart_id <NEW_LINE> <DEDENT> @property <NEW_LINE> def cart_total(self): <NEW_LINE> <INDENT> return self._cart_total <NEW_LINE> <DEDENT> @cart_total.setter <NEW_LINE> def cart_total(self, cart_total): <NEW_LINE> <INDENT> self._cart_total = cart_total <NEW_LINE> <DEDENT> @property <NEW_LINE> def contact(self): <NEW_LINE> <INDENT> return self._contact <NEW_LINE> <DEDENT> @contact.setter <NEW_LINE> def contact(self, contact): <NEW_LINE> <INDENT> self._contact = contact <NEW_LINE> <DEDENT> @property <NEW_LINE> def products(self): <NEW_LINE> <INDENT> return self._products <NEW_LINE> <DEDENT> @products.setter <NEW_LINE> def products(self, products): <NEW_LINE> <INDENT> self._products = products <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.openapi_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, Cart): <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, Cart): <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. | 62598f9d4527f215b58e9cc0 |
@python_2_unicode_compatible <NEW_LINE> class RegistrationProfile(models.Model): <NEW_LINE> <INDENT> ACTIVATED = "ALREADY_ACTIVATED" <NEW_LINE> user = models.ForeignKey(UserModelString(), unique=True, verbose_name=_('user')) <NEW_LINE> activation_key = models.CharField(_('activation key'), max_length=40) <NEW_LINE> objects = RegistrationManager() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = _('registration profile') <NEW_LINE> verbose_name_plural = _('registration profiles') <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "Registration information for %s" % self.user <NEW_LINE> <DEDENT> def activation_key_expired(self): <NEW_LINE> <INDENT> expiration_date = datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS) <NEW_LINE> return (self.activation_key == self.ACTIVATED or (self.user.date_joined + expiration_date <= datetime_now())) <NEW_LINE> <DEDENT> activation_key_expired.boolean = True <NEW_LINE> def send_activation_email(self, site, request=None): <NEW_LINE> <INDENT> ctx_dict = {} <NEW_LINE> if request is not None: <NEW_LINE> <INDENT> ctx_dict = RequestContext(request, ctx_dict) <NEW_LINE> <DEDENT> ctx_dict.update({ 'user': self.user, 'activation_key': self.activation_key, 'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS, 'site': site, }) <NEW_LINE> subject = getattr(settings, 'REGISTRATION_EMAIL_SUBJECT_PREFIX', '') + render_to_string('registration/activation_email_subject.txt', ctx_dict) <NEW_LINE> subject = ''.join(subject.splitlines()) <NEW_LINE> message_txt = render_to_string('registration/activation_email.txt', ctx_dict) <NEW_LINE> email_message = EmailMultiAlternatives(subject, message_txt, settings.DEFAULT_FROM_EMAIL, [self.user.email]) <NEW_LINE> try: <NEW_LINE> <INDENT> message_html = render_to_string('registration/activation_email.html', ctx_dict) <NEW_LINE> <DEDENT> except TemplateDoesNotExist: <NEW_LINE> <INDENT> message_html = None <NEW_LINE> <DEDENT> if message_html: <NEW_LINE> <INDENT> email_message.attach_alternative(message_html, 'text/html') <NEW_LINE> <DEDENT> email_message.send() | A simple profile which stores an activation key for use during
user account registration.
Generally, you will not want to interact directly with instances
of this model; the provided manager includes methods
for creating and activating new accounts, as well as for cleaning
out accounts which have never been activated.
While it is possible to use this model as the value of the
``AUTH_PROFILE_MODULE`` setting, it's not recommended that you do
so. This model's sole purpose is to store data temporarily during
account registration and activation. | 62598f9d91f36d47f2230d8e |
class md4_mac: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.key = urandom(32) <NEW_LINE> <DEDENT> def tag(self, message): <NEW_LINE> <INDENT> s = md4() <NEW_LINE> return s.digest(self.key+message) <NEW_LINE> <DEDENT> def validate(self, message, tag): <NEW_LINE> <INDENT> return self.tag(message) == tag | keyed mac. appends randomly generated key to message and applies md4 hash
function | 62598f9d97e22403b383ace8 |
class DeleteInventoryItemsInputSet(InputSet): <NEW_LINE> <INDENT> def set_SKUs(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'SKUs', value) <NEW_LINE> <DEDENT> def set_AWSAccessKeyId(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'AWSAccessKeyId', value) <NEW_LINE> <DEDENT> def set_AWSMarketplaceId(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'AWSMarketplaceId', value) <NEW_LINE> <DEDENT> def set_AWSMerchantId(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'AWSMerchantId', value) <NEW_LINE> <DEDENT> def set_AWSSecretKeyId(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'AWSSecretKeyId', value) <NEW_LINE> <DEDENT> def set_DeleteOptions(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'DeleteOptions', value) <NEW_LINE> <DEDENT> def set_Endpoint(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'Endpoint', value) <NEW_LINE> <DEDENT> def set_TimeToWait(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'TimeToWait', value) | An InputSet with methods appropriate for specifying the inputs to the DeleteInventoryItems
Choreo. The InputSet object is used to specify input parameters when executing this Choreo. | 62598f9d3d592f4c4edbacab |
class DownloadDestructionReportView(UserPassesTestMixin, DetailView): <NEW_LINE> <INDENT> sendfile_options = None <NEW_LINE> model = DestructionReport <NEW_LINE> def test_func(self): <NEW_LINE> <INDENT> config = ArchiveConfig.get_solo() <NEW_LINE> if not config.destruction_report_downloadable: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> user = self.request.user <NEW_LINE> if not user.is_authenticated: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if user.is_superuser: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> report = self.get_object() <NEW_LINE> if ( user == report.process_owner or user.role.type == RoleTypeChoices.functional_admin ): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def get_sendfile_opts(self): <NEW_LINE> <INDENT> return self.sendfile_options or {} <NEW_LINE> <DEDENT> def get(self, request, *args, **kwargs): <NEW_LINE> <INDENT> form = ReportTypeForm(request.GET) <NEW_LINE> form.is_valid() <NEW_LINE> if form.errors: <NEW_LINE> <INDENT> return HttpResponseBadRequest("Invalid document type") <NEW_LINE> <DEDENT> file_field = f"content_{form.cleaned_data['type']}" <NEW_LINE> filename = getattr(self.get_object(), file_field).path <NEW_LINE> sendfile_options = self.get_sendfile_opts() <NEW_LINE> return sendfile(request, filename, **sendfile_options) | Verify the permission required and send the filefield via sendfile.
:param permission_required: the permission required to view the file
:param model: the model class to look up the object
:param file_field: the name of the ``Filefield`` | 62598f9d07f4c71912baf228 |
class _form_field(object): <NEW_LINE> <INDENT> scope = None <NEW_LINE> registry = { SCOPE_USER: {}, SCOPE_GROUP: {} } <NEW_LINE> def __init__(self, field, backend=BACKEND_ALL): <NEW_LINE> <INDENT> assert self.scope <NEW_LINE> self.field = field <NEW_LINE> self.backend = backend <NEW_LINE> <DEDENT> def __call__(self, factory): <NEW_LINE> <INDENT> scope_reg = self.registry[self.scope] <NEW_LINE> backend_reg = scope_reg.setdefault(self.backend, {}) <NEW_LINE> backend_reg[self.field] = factory <NEW_LINE> return factory <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def factory(cls, field, backend=BACKEND_ALL): <NEW_LINE> <INDENT> assert cls.scope <NEW_LINE> scope_reg = cls.registry[cls.scope] <NEW_LINE> for backend_name in (backend, BACKEND_ALL): <NEW_LINE> <INDENT> backend_reg = scope_reg.setdefault(backend_name, {}) <NEW_LINE> factory = backend_reg.get(field) <NEW_LINE> if factory: <NEW_LINE> <INDENT> return factory <NEW_LINE> <DEDENT> <DEDENT> return default_form_field_factory | Abstract form field factory registry and decorator.
| 62598f9da79ad16197769e41 |
class GenshiMixin(object): <NEW_LINE> <INDENT> def render_template(self, filename, _method=None, **context): <NEW_LINE> <INDENT> request_context = dict(self.request.context) <NEW_LINE> request_context.update(context) <NEW_LINE> return render_template(filename, _method=_method, **request_context) <NEW_LINE> <DEDENT> def render_response(self, filename, _method=None, **context): <NEW_LINE> <INDENT> request_context = dict(self.request.context) <NEW_LINE> request_context.update(context) <NEW_LINE> return render_response(filename, _method=_method, **request_context) | :class:`tipfy.RequestHandler` mixin that add ``render_template`` and
``render_response`` methods to a :class:`tipfy.RequestHandler`. It will
use the request context to render templates. | 62598f9d4f6381625f1993aa |
class PeerReviewInvitationReplyForm(forms.ModelForm): <NEW_LINE> <INDENT> def clean_accepted(self): <NEW_LINE> <INDENT> data = self.cleaned_data["accepted"] <NEW_LINE> if data is None: <NEW_LINE> <INDENT> raise forms.ValidationError("Please accept or decline the invitation") <NEW_LINE> <DEDENT> return data <NEW_LINE> <DEDENT> def save(self, commit=True): <NEW_LINE> <INDENT> invitation = super().save(commit=commit) <NEW_LINE> if invitation.accepted: <NEW_LINE> <INDENT> invitation.accept() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> invitation.decline() <NEW_LINE> <DEDENT> return invitation <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> model = PeerReviewInvitation <NEW_LINE> fields = ["accepted"] | Processes a peer review invitation reply (accept / decline) from a candidate reviewer | 62598f9d435de62698e9bbd1 |
class ATLinkSchemaModifier(object): <NEW_LINE> <INDENT> adapts(IATLink) <NEW_LINE> implements(IOrderableSchemaExtender) <NEW_LINE> _fields = [ _StringExtensionField('obrirfinestra', required=False, searchable=True, widget=BooleanWidget( label='Open in a new window', label_msgid='upc.genweb.banners_label_Obrirennovafinestra', i18n_domain='upc.genweb.banners', ) ) ] <NEW_LINE> def __init__(self, newsItem): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def getFields(self): <NEW_LINE> <INDENT> return self._fields <NEW_LINE> <DEDENT> def getOrder(self, original): <NEW_LINE> <INDENT> new = original.copy() <NEW_LINE> defaultSchemaFields = new['default'] <NEW_LINE> defaultSchemaFields.remove('obrirfinestra') <NEW_LINE> defaultSchemaFields.insert(defaultSchemaFields.index('remoteUrl') + 1, 'obrirfinestra') <NEW_LINE> return new | Afegeix un check nou al contingut enllas | 62598f9d0a50d4780f7051b7 |
class EmployeeDetail(generics.RetrieveAPIView): <NEW_LINE> <INDENT> queryset = Employee.objects.all() <NEW_LINE> serializer_class = EmployeeSerializer | Вывод детальной информации одного сотрудника | 62598f9ddd821e528d6d8d12 |
class DummyStdout: <NEW_LINE> <INDENT> def write(self, _): <NEW_LINE> <INDENT> pass | Used to disable write to stdout
| 62598f9deab8aa0e5d30bb63 |
class NamedURL(object): <NEW_LINE> <INDENT> def __init__(self, name, *args, **kwargs): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.args = args <NEW_LINE> self.kwargs = kwargs <NEW_LINE> <DEDENT> def reverse_url(self): <NEW_LINE> <INDENT> return reverse(self.name, args=self.args, kwargs=self.kwargs) | Wrapper over named URLs to provide lazy reversion | 62598f9de5267d203ee6b6eb |
class Value: <NEW_LINE> <INDENT> def __repr__(self): <NEW_LINE> <INDENT> return str(self) <NEW_LINE> <DEDENT> def bool_evaluate(self): <NEW_LINE> <INDENT> code = self.fetch_to_stack() <NEW_LINE> code += ['; Bool evaluation', '\tPOP R0', '\tCMP R0, 0', '\tMOVE SR, R0', '\tAND R0, 8, R0', '\tXOR R0, 8, R0', '\tSHR R0, 3, R0', '\tPUSH R0'] <NEW_LINE> return code <NEW_LINE> <DEDENT> def fetch_to_stack(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def save_from_stack(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def fetch_address_to_stack(self): <NEW_LINE> <INDENT> raise NotImplementedError | A value of an expression | 62598f9d99cbb53fe6830cb0 |
class OffensEval2019Task2Processor(DataProcessor): <NEW_LINE> <INDENT> def get_example_from_tensor_dict(self, tensor_dict): <NEW_LINE> <INDENT> return InputExample(tensor_dict['idx'].numpy(), tensor_dict['sentence'].numpy().decode('utf-8'), None, str(tensor_dict['label'].numpy())) <NEW_LINE> <DEDENT> def get_train_examples(self, data_dir): <NEW_LINE> <INDENT> logger.info("LOOKING AT {}".format(os.path.join(data_dir, "train.tsv"))) <NEW_LINE> return self._create_examples( self._read_tsv(os.path.join(data_dir, "train.tsv")), "train") <NEW_LINE> <DEDENT> def get_dev_examples(self, data_dir): <NEW_LINE> <INDENT> return self._create_examples( self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev") <NEW_LINE> <DEDENT> def get_pred_examples(self, data_dir): <NEW_LINE> <INDENT> return self._create_examples( self._read_tsv(os.path.join(data_dir, "dev.tsv")), "pred") <NEW_LINE> <DEDENT> def get_labels(self): <NEW_LINE> <INDENT> return ["TIN", "UNT"] <NEW_LINE> <DEDENT> def _create_examples(self, lines, set_type): <NEW_LINE> <INDENT> examples = [] <NEW_LINE> for (i, line) in enumerate(lines): <NEW_LINE> <INDENT> if i == 0: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> guid = "%s-%s" % (set_type, i) <NEW_LINE> if set_type == "train" or set_type == "dev": <NEW_LINE> <INDENT> text_a = line[1] <NEW_LINE> label = line[0] <NEW_LINE> examples.append(InputExample(guid=guid, text_a=text_a, text_b=None, label=label)) <NEW_LINE> <DEDENT> elif set_type == "predict": <NEW_LINE> <INDENT> text_a = line[1] <NEW_LINE> examples.append(InputExample(guid=guid, text_a=text_a, text_b=None, label=None)) <NEW_LINE> <DEDENT> <DEDENT> return examples | Processor for the OffensEval2019Task2 data set (My version). | 62598f9da8370b77170f01c1 |
class ContentContentRepresentation(object): <NEW_LINE> <INDENT> swagger_types = { 'name': 'str', 'path': 'str', 'validation_string': 'str' } <NEW_LINE> attribute_map = { 'name': 'name', 'path': 'path', 'validation_string': 'validationString' } <NEW_LINE> def __init__(self, name=None, path=None, validation_string=None): <NEW_LINE> <INDENT> self._name = None <NEW_LINE> self._path = None <NEW_LINE> self._validation_string = None <NEW_LINE> self.discriminator = None <NEW_LINE> if name is not None: <NEW_LINE> <INDENT> self.name = name <NEW_LINE> <DEDENT> if path is not None: <NEW_LINE> <INDENT> self.path = path <NEW_LINE> <DEDENT> if validation_string is not None: <NEW_LINE> <INDENT> self.validation_string = validation_string <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @name.setter <NEW_LINE> def name(self, name): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> <DEDENT> @property <NEW_LINE> def path(self): <NEW_LINE> <INDENT> return self._path <NEW_LINE> <DEDENT> @path.setter <NEW_LINE> def path(self, path): <NEW_LINE> <INDENT> self._path = path <NEW_LINE> <DEDENT> @property <NEW_LINE> def validation_string(self): <NEW_LINE> <INDENT> return self._validation_string <NEW_LINE> <DEDENT> @validation_string.setter <NEW_LINE> def validation_string(self, validation_string): <NEW_LINE> <INDENT> self._validation_string = validation_string <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, ContentContentRepresentation): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 62598f9d56ac1b37e6301fc8 |
class ConvBN(nn.Module): <NEW_LINE> <INDENT> def __init__(self, ch_in, ch_out, kernel_size = 3, stride=1, padding=0): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.conv = nn.Conv2d(ch_in, ch_out, kernel_size=kernel_size, stride=stride, padding=padding, bias=False) <NEW_LINE> self.bn = nn.BatchNorm2d(ch_out, momentum=0.01) <NEW_LINE> self.relu = nn.LeakyReLU(0.1, inplace=True) <NEW_LINE> <DEDENT> def forward(self, x): return self.relu(self.bn(self.conv(x))) | convolutional layer then batchnorm | 62598f9d63d6d428bbee2590 |
class ResultsCollection: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._list = list() <NEW_LINE> <DEDENT> def add_result(self, r): <NEW_LINE> <INDENT> self._list.append(r) <NEW_LINE> <DEDENT> def add_results(self, res): <NEW_LINE> <INDENT> for r in res: <NEW_LINE> <INDENT> self.add_result(r) <NEW_LINE> <DEDENT> <DEDENT> def get_results(self): <NEW_LINE> <INDENT> return self._list <NEW_LINE> <DEDENT> def get_result(self, idx): <NEW_LINE> <INDENT> return self._list[idx] <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> for el in self._list: <NEW_LINE> <INDENT> yield el <NEW_LINE> <DEDENT> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self._list) <NEW_LINE> <DEDENT> def state_dict(self, retain_keys: list = None): <NEW_LINE> <INDENT> if retain_keys is None: <NEW_LINE> <INDENT> retain_keys = [] <NEW_LINE> <DEDENT> return [r.state_dict(retain_keys) for r in self] | Base class to handle detection results and IO of results | 62598f9d1f5feb6acb162a00 |
class MatchMplsTcIDL(object): <NEW_LINE> <INDENT> thrift_spec = (None, (1, TType.I32, 'sense', None, None), (2, TType.LIST, 'mplsTc', (TType.BYTE, None), None)) <NEW_LINE> def __init__(self, sense = None, mplsTc = None): <NEW_LINE> <INDENT> self.sense = sense <NEW_LINE> self.mplsTc = mplsTc <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid,) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 1: <NEW_LINE> <INDENT> if ftype == TType.I32: <NEW_LINE> <INDENT> self.sense = iprot.readI32() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 2: <NEW_LINE> <INDENT> if ftype == TType.LIST: <NEW_LINE> <INDENT> self.mplsTc = [] <NEW_LINE> (_etype101, _size98,) = iprot.readListBegin() <NEW_LINE> for _i102 in xrange(_size98): <NEW_LINE> <INDENT> _elem103 = iprot.readByte() <NEW_LINE> self.mplsTc.append(_elem103) <NEW_LINE> <DEDENT> iprot.readListEnd() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('MatchMplsTcIDL') <NEW_LINE> if self.sense != None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('sense', TType.I32, 1) <NEW_LINE> oprot.writeI32(self.sense) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.mplsTc != None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('mplsTc', TType.LIST, 2) <NEW_LINE> oprot.writeListBegin(TType.BYTE, len(self.mplsTc)) <NEW_LINE> for iter104 in self.mplsTc: <NEW_LINE> <INDENT> oprot.writeByte(iter104) <NEW_LINE> <DEDENT> oprot.writeListEnd() <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> def validate(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = [ '%s=%r' % (key, value) for (key, value,) in self.__dict__.iteritems() ] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | MPLS Traffic Class match
Attributes:
- sense
- mplsTc | 62598f9d99cbb53fe6830cb1 |
class AccessRights(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): <NEW_LINE> <INDENT> REGISTRY_READ = "RegistryRead" <NEW_LINE> REGISTRY_WRITE = "RegistryWrite" <NEW_LINE> SERVICE_CONNECT = "ServiceConnect" <NEW_LINE> DEVICE_CONNECT = "DeviceConnect" <NEW_LINE> REGISTRY_READ_REGISTRY_WRITE = "RegistryRead, RegistryWrite" <NEW_LINE> REGISTRY_READ_SERVICE_CONNECT = "RegistryRead, ServiceConnect" <NEW_LINE> REGISTRY_READ_DEVICE_CONNECT = "RegistryRead, DeviceConnect" <NEW_LINE> REGISTRY_WRITE_SERVICE_CONNECT = "RegistryWrite, ServiceConnect" <NEW_LINE> REGISTRY_WRITE_DEVICE_CONNECT = "RegistryWrite, DeviceConnect" <NEW_LINE> SERVICE_CONNECT_DEVICE_CONNECT = "ServiceConnect, DeviceConnect" <NEW_LINE> REGISTRY_READ_REGISTRY_WRITE_SERVICE_CONNECT = "RegistryRead, RegistryWrite, ServiceConnect" <NEW_LINE> REGISTRY_READ_REGISTRY_WRITE_DEVICE_CONNECT = "RegistryRead, RegistryWrite, DeviceConnect" <NEW_LINE> REGISTRY_READ_SERVICE_CONNECT_DEVICE_CONNECT = "RegistryRead, ServiceConnect, DeviceConnect" <NEW_LINE> REGISTRY_WRITE_SERVICE_CONNECT_DEVICE_CONNECT = "RegistryWrite, ServiceConnect, DeviceConnect" <NEW_LINE> REGISTRY_READ_REGISTRY_WRITE_SERVICE_CONNECT_DEVICE_CONNECT = "RegistryRead, RegistryWrite, ServiceConnect, DeviceConnect" | The permissions assigned to the shared access policy.
| 62598f9d656771135c489461 |
class Index(PostsCollection): <NEW_LINE> <INDENT> _path_template_key = 'index pages path template' <NEW_LINE> _template_file_key = 'index' <NEW_LINE> def __init__(self, page_number, posts, settings, newer_index_url=None, older_index_url=None): <NEW_LINE> <INDENT> super().__init__(posts=posts, settings=settings) <NEW_LINE> self.page_number = page_number <NEW_LINE> self.newer_index_url = newer_index_url <NEW_LINE> self.older_index_url = older_index_url <NEW_LINE> if page_number == 1: <NEW_LINE> <INDENT> self.path_part = 'index.html' <NEW_LINE> self.url = settings['site']['url'] <NEW_LINE> <DEDENT> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return (post for post in self.posts) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> attrs = ['page_number', 'posts', 'output_path', 'url', 'newer_index_url', 'older_index_url'] <NEW_LINE> return all(getattr(self, a) == getattr(other, a) for a in attrs) <NEW_LINE> <DEDENT> def __lt__(self, other): <NEW_LINE> <INDENT> return self.page_number < other.page_number <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> template = 'Index page {page_number}, {num_posts} posts ({url})' <NEW_LINE> return template.format(page_number=self.page_number, num_posts=len(self.posts), url=self.url) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def paginate_posts(cls, posts, settings): <NEW_LINE> <INDENT> posts_per_page = settings['index']['posts per page'] <NEW_LINE> posts_newest_first = sorted(posts, reverse=True) <NEW_LINE> chunked = chunk(posts_newest_first, chunk_length=posts_per_page) <NEW_LINE> index_list = [cls(page_number=n, settings=settings, posts=post_list) for n, post_list in enumerate(chunked, start=1)] <NEW_LINE> for n, index_object in enumerate(index_list): <NEW_LINE> <INDENT> if n != 0: <NEW_LINE> <INDENT> index_object.newer_index_url = index_list[n - 1].url <NEW_LINE> <DEDENT> if n + 1 < len(index_list): <NEW_LINE> <INDENT> index_object.older_index_url = index_list[n + 1].url <NEW_LINE> <DEDENT> <DEDENT> return index_list | Index represents a blog index page
It has the following attributes:
page_number: 1 to len(index_pages)
newer_index_url: url to an index with more recent posts or None
older_index_url: url to an index with less recent posts or None
output_path: path the index should be written to (pathlib.Path)
url: url of the index (str)
posts: [Post] to be rendered on the index page
An Index created with page_number 1 is always saved to a file named
index.html and its url is the site's url.
The class method .paginate_posts creates a list of Index objects out
of a list of posts. | 62598f9d45492302aabfc2b6 |
class FakeAPIView(CrudAPIView): <NEW_LINE> <INDENT> model = FakeModel <NEW_LINE> url_lookup = "some_id" | Fake CrudAPI imoplementation for tests. | 62598f9d7047854f4633f1c1 |
class Section (object): <NEW_LINE> <INDENT> def __init__(self, key, dialog, app, label=u"", icon=None): <NEW_LINE> <INDENT> self.key = key <NEW_LINE> self.dialog = dialog <NEW_LINE> self.label = label <NEW_LINE> self.icon = icon <NEW_LINE> self.frame = gtk.Frame("") <NEW_LINE> self.frame.get_label_widget().set_text("<b>%s</b>" % label) <NEW_LINE> self.frame.get_label_widget().set_use_markup(True) <NEW_LINE> self.frame.set_property("shadow-type", gtk.SHADOW_NONE) <NEW_LINE> self.__align = gtk.Alignment() <NEW_LINE> self.__align.set_padding(10, 0, 10, 0) <NEW_LINE> self.__align.show() <NEW_LINE> self.frame.add(self.__align) <NEW_LINE> <DEDENT> def get_default_widget(self): <NEW_LINE> <INDENT> return self.__align <NEW_LINE> <DEDENT> def load_options(self, app): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def save_options(self, app): <NEW_LINE> <INDENT> pass | A Section in the Options Dialog | 62598f9d097d151d1a2c0e06 |
class KNearestNeighbour: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def train(self, x, y): <NEW_LINE> <INDENT> self.x_train = x <NEW_LINE> self.y_train = y <NEW_LINE> <DEDENT> def predict(self, x, k=1, num_loops=0): <NEW_LINE> <INDENT> if num_loops == 0: <NEW_LINE> <INDENT> dists = self.compute_distance_no_loops(x) <NEW_LINE> <DEDENT> elif num_loops == 1: <NEW_LINE> <INDENT> dists = self.compute_distance_one_loop(x) <NEW_LINE> <DEDENT> elif num_loops == 2: <NEW_LINE> <INDENT> dists = self.compute_distance_two_loop(x) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('Invalid value %d for num_loops' % num_loops) <NEW_LINE> <DEDENT> return self.predict_labels(dists,k=k) <NEW_LINE> <DEDENT> def compute_distance_two_loops(self, x): <NEW_LINE> <INDENT> num_test = x.shape[0] <NEW_LINE> num_train = self.x_train.shape[0] <NEW_LINE> dists = np.zeros(num_test, num_train) <NEW_LINE> for i in xrange(num_test): <NEW_LINE> <INDENT> for j in xrange(num_train): <NEW_LINE> <INDENT> dists[i, j] = np.sum(self.x_train[j, :] - x[i, :] ** 2) <NEW_LINE> <DEDENT> <DEDENT> return dists <NEW_LINE> <DEDENT> def compute_distance_one_loop(self, x): <NEW_LINE> <INDENT> num_test = x.shape[0] <NEW_LINE> num_train = self.x_train.shape[0] <NEW_LINE> dists = np.zeros(num_test, num_train) <NEW_LINE> for i in xrange(num_test): <NEW_LINE> <INDENT> train_2 = np.sum((self.x_train) ** 2, axis=1).T <NEW_LINE> test_2 = np.tile(np.sum(x[i, :] ** 2), [1, num_train]) <NEW_LINE> test_train = x[i, :].dot(self.x_train.T) <NEW_LINE> dists[i, :] = train_2 + test_2 - 2 * test_train <NEW_LINE> <DEDENT> return dists <NEW_LINE> <DEDENT> def compute_dsitance_no_loop(self, x): <NEW_LINE> <INDENT> num_test = x.shape[0] <NEW_LINE> num_train = self.x_train.shape[0] <NEW_LINE> dists = np.zeros(num_test, num_train) <NEW_LINE> train_2 = np.tile(np.sum((self.x_train)**2, axis=1), [num_test, 1]) <NEW_LINE> test_2 = np.tile(np.sum(x ** 2, axis=1), [num_train, 1]).T <NEW_LINE> test_train = x.dot(self.x_train.T) <NEW_LINE> dists = train_2 + test_2 - 2 * test_train <NEW_LINE> return dists <NEW_LINE> <DEDENT> def predict_labels(self, dists, k=1): <NEW_LINE> <INDENT> num_test = dists.shape[0] <NEW_LINE> y_pred = np.zeros(num_test) <NEW_LINE> for i in xrange(num_test): <NEW_LINE> <INDENT> closest_y = [] <NEW_LINE> closest_idx = np.argsort(dists[i, :])[: k].tolist() <NEW_LINE> closest_y = self.y_train[closest_idx] <NEW_LINE> counts = np.bincount(closest_y) <NEW_LINE> y_pred[i] = np.argmax(counts) <NEW_LINE> <DEDENT> return y_pred | L2 distance | 62598f9d3539df3088ecc094 |
class BuildCoreHierarchyAction(BuildAction): <NEW_LINE> <INDENT> def run(self): <NEW_LINE> <INDENT> if self.groupName: <NEW_LINE> <INDENT> grpNode = pm.group(name=self.groupName, em=True, p=self.rig) <NEW_LINE> for a in ('tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz'): <NEW_LINE> <INDENT> grpNode.attr(a).setLocked(True) <NEW_LINE> grpNode.attr(a).setKeyable(False) <NEW_LINE> <DEDENT> if not self.groupVisible: <NEW_LINE> <INDENT> grpNode.v.set(False) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> grpNode = self.rig <NEW_LINE> <DEDENT> nodes = self.nodes <NEW_LINE> if not nodes: <NEW_LINE> <INDENT> nodes = self.getUnorganizedNodes() <NEW_LINE> <DEDENT> if nodes: <NEW_LINE> <INDENT> tops = pulse.nodes.getParentNodes(nodes) <NEW_LINE> if len(tops) > 0: <NEW_LINE> <INDENT> pm.parent(tops, grpNode) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def getUnorganizedNodes(self): <NEW_LINE> <INDENT> def shouldInclude(node): <NEW_LINE> <INDENT> if node.numChildren() == 1 and len(node.getShapes(typ='camera')) == 1: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> nodes = pm.ls(assemblies=True) <NEW_LINE> if self.rig in nodes: <NEW_LINE> <INDENT> nodes.remove(self.rig) <NEW_LINE> <DEDENT> nodes = [n for n in nodes if shouldInclude(n)] <NEW_LINE> return nodes | Builds a core hierarchy of the rig.
This creates a group for one of the rig's main
features (usually ctls, joints, or meshes) and
parents the corresponding nodes. | 62598f9da219f33f346c65f8 |
class DynCodeHook(Hook): <NEW_LINE> <INDENT> def __init__(self, se_obj, emu_eng, cb, ctx=[]): <NEW_LINE> <INDENT> super(DynCodeHook, self).__init__(se_obj, emu_eng, cb) | This hook type is used to get a callback when dynamically created/copied code is executed
Currently, this will only fire once per dynamic code mapping. Could be useful for unpacking. | 62598f9d7cff6e4e811b5801 |
class get_results_metadata_result(object): <NEW_LINE> <INDENT> thrift_spec = ( (0, TType.STRUCT, 'success', (ResultsMetadata, ResultsMetadata.thrift_spec), None, ), (1, TType.STRUCT, 'error', (QueryNotFoundException, QueryNotFoundException.thrift_spec), None, ), ) <NEW_LINE> def __init__(self, success=None, error=None,): <NEW_LINE> <INDENT> self.success = success <NEW_LINE> self.error = error <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 0: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.success = ResultsMetadata() <NEW_LINE> self.success.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.error = QueryNotFoundException() <NEW_LINE> self.error.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('get_results_metadata_result') <NEW_LINE> if self.success is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('success', TType.STRUCT, 0) <NEW_LINE> self.success.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.error is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('error', TType.STRUCT, 1) <NEW_LINE> self.error.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) | Attributes:
- success
- error | 62598f9d4527f215b58e9cc2 |
class DerivedParameters(parametertools.SubParameters): <NEW_LINE> <INDENT> _PARCLASSES = (TOY, Seconds, NmbSubsteps, VQ) | Derived parameters of HydPy-L-Lake, indirectly defined by the user. | 62598f9d97e22403b383acea |
class Station(Producer): <NEW_LINE> <INDENT> key_schema = avro.load(f"{Path(__file__).parents[0]}/schemas/arrival_key.json") <NEW_LINE> value_schema = avro.load(f"{Path(__file__).parents[0]}/schemas/arrival_value.json") <NEW_LINE> def __init__(self, station_id, name, color, direction_a=None, direction_b=None): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> station_name = ( self.name.lower() .replace("/", "_and_") .replace(" ", "_") .replace("-", "_") .replace("'", "") ) <NEW_LINE> topic_name = f"{station_name}" <NEW_LINE> super().__init__( topic_name, key_schema=Station.key_schema, value_schema=Station.value_schema, num_partitions=1, num_replicas=1, ) <NEW_LINE> self.station_id = int(station_id) <NEW_LINE> self.color = color <NEW_LINE> self.dir_a = direction_a <NEW_LINE> self.dir_b = direction_b <NEW_LINE> self.a_train = None <NEW_LINE> self.b_train = None <NEW_LINE> self.turnstile = Turnstile(self) <NEW_LINE> <DEDENT> def run(self, train, direction, prev_station_id, prev_direction): <NEW_LINE> <INDENT> logger.info("arrival kafka integration complete - DONE") <NEW_LINE> self.producer.produce( topic=self.topic_name, key={"timestamp": self.time_millis()}, value_schema=self.value_schema, value={ "station_id": self.station_id, "train_id": train.train_id, "direction": direction, "line": self.color, "train_status": train.status, "prev_station_id": prev_station_id, "prev_direction": prev_direction }, ) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "Station | {:^5} | {:<30} | Direction A: | {:^5} | departing to {:<30} | Direction B: | {:^5} | departing to {:<30} | ".format( self.station_id, self.name, self.a_train.train_id if self.a_train is not None else "---", self.dir_a.name if self.dir_a is not None else "---", self.b_train.train_id if self.b_train is not None else "---", self.dir_b.name if self.dir_b is not None else "---", ) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return str(self) <NEW_LINE> <DEDENT> def arrive_a(self, train, prev_station_id, prev_direction): <NEW_LINE> <INDENT> self.a_train = train <NEW_LINE> self.run(train, "a", prev_station_id, prev_direction) <NEW_LINE> <DEDENT> def arrive_b(self, train, prev_station_id, prev_direction): <NEW_LINE> <INDENT> self.b_train = train <NEW_LINE> self.run(train, "b", prev_station_id, prev_direction) <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> self.turnstile.close() <NEW_LINE> super(Station, self).close() | Defines a single station | 62598f9d57b8e32f5250800b |
class Loan: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.id = 0 <NEW_LINE> self.user_id = 0 <NEW_LINE> self.account_type = AccountType.INVALID <NEW_LINE> self.symbol = "" <NEW_LINE> self.currency = "" <NEW_LINE> self.loan_amount = 0.0 <NEW_LINE> self.loan_balance = 0.0 <NEW_LINE> self.interest_rate = 0.0 <NEW_LINE> self.interest_amount = 0.0 <NEW_LINE> self.interest_balance = 0.0 <NEW_LINE> self.state = LoanOrderState.INVALID <NEW_LINE> self.created_timestamp = 0 <NEW_LINE> self.accrued_timestamp = 0 <NEW_LINE> self.updated_timestamp = 0 <NEW_LINE> self.deduct_rate = 0 <NEW_LINE> self.paid_point = 0.0 <NEW_LINE> self.deduct_currency = "" <NEW_LINE> self.account_id = 0 <NEW_LINE> self.paid_coin = 0.0 <NEW_LINE> self.deduct_amount = 0.0 <NEW_LINE> <DEDENT> def print_object(self, format_data=""): <NEW_LINE> <INDENT> from hbclient.trade.base.printobject import PrintBasic <NEW_LINE> PrintBasic.print_basic(self.currency, format_data + "Currency") <NEW_LINE> PrintBasic.print_basic(self.symbol, format_data + "Symbol") <NEW_LINE> PrintBasic.print_basic(self.deduct_rate, format_data + "Deduct Rate") <NEW_LINE> PrintBasic.print_basic(self.paid_point, format_data + "Paid Point") <NEW_LINE> PrintBasic.print_basic(self.deduct_currency, format_data + "Deduct Currency") <NEW_LINE> PrintBasic.print_basic(self.user_id, format_data + "User Id") <NEW_LINE> PrintBasic.print_basic(self.created_timestamp, format_data + "Create Time") <NEW_LINE> PrintBasic.print_basic(self.account_id, format_data + "Account Id") <NEW_LINE> PrintBasic.print_basic(self.paid_coin, format_data + "Paid Coin") <NEW_LINE> PrintBasic.print_basic(self.loan_amount, format_data + "Load Amount") <NEW_LINE> PrintBasic.print_basic(self.interest_amount, format_data + "Interest Amount") <NEW_LINE> PrintBasic.print_basic(self.deduct_amount, format_data + "Deduct Amount") <NEW_LINE> PrintBasic.print_basic(self.loan_balance, format_data + "Loan Balance") <NEW_LINE> PrintBasic.print_basic(self.interest_balance, format_data + "Interest Balance") <NEW_LINE> PrintBasic.print_basic(self.updated_timestamp, format_data + "Update Time") <NEW_LINE> PrintBasic.print_basic(self.accrued_timestamp, format_data + "Accrued Time") <NEW_LINE> PrintBasic.print_basic(self.interest_rate, format_data + "Interest Rate") <NEW_LINE> PrintBasic.print_basic(self.id, format_data + "ID") <NEW_LINE> PrintBasic.print_basic(self.state, format_data + "Loan Order State") | The margin order information.
:member
id: The order id.
user_id: The user id.
account_type: The account type which created the loan order.
symbol: The symbol, like "btcusdt".
currency: The currency name.
loan_amount: The amount of the origin loan.
loan_balance: The amount of the loan left.
interest_rate: The loan interest rate.
interest_amount: The accumulated loan interest.
interest_balance: The amount of loan interest left.
state: The loan stats, possible values: created, accrual, cleared, invalid.
created_timestamp: The UNIX formatted timestamp in UTC when the order was created.
accrued_timestamp: The UNIX formatted timestamp in UTC when the last accrue happened. | 62598f9d3d592f4c4edbacad |
class McgLogCombiner: <NEW_LINE> <INDENT> mcgLogAllName = "mcgLog_all.log" <NEW_LINE> def __init__(self, issueArchiveDir): <NEW_LINE> <INDENT> issueArchivePath = Path(issueArchiveDir) <NEW_LINE> if issueArchivePath.exists(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> mcgLogAllPath = issueArchivePath / McgLogCombiner.mcgLogAllName <NEW_LINE> if mcgLogAllPath.exists(): <NEW_LINE> <INDENT> mcgLogAllPath.unlink() <NEW_LINE> <DEDENT> mcgLogAllFile = mcgLogAllPath.open(mode='a', newline='') <NEW_LINE> mcgLogPath = issueArchivePath / "usr" / "local" / "data" / "log" <NEW_LINE> fileList = sorted(mcgLogPath.glob("mcgLogger.log*"), key=str, reverse=True) <NEW_LINE> for file in fileList: <NEW_LINE> <INDENT> print("mcgLog file %s" % (str(file))) <NEW_LINE> with file.open(mode='r') as infile: <NEW_LINE> <INDENT> for line in infile: <NEW_LINE> <INDENT> mcgLogAllFile.write(line) <NEW_LINE> <DEDENT> infile.close() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except BaseException: <NEW_LINE> <INDENT> exc_type, exc_value, exc_traceback = sys.exc_info() <NEW_LINE> traceback.print_tb(exc_traceback) | classdocs | 62598f9d596a897236127a5a |
class WCV(NMEASentence): <NEW_LINE> <INDENT> fields = ( ("Velocity", "velocity"), ("Velocity Units", "vel_units"), ("Waypoint ID", "waypoint_id") ) | Waypoint Closure Velocity
| 62598f9d30bbd72246469866 |
class Records(object): <NEW_LINE> <INDENT> def __init__(self, rectype, rdataset): <NEW_LINE> <INDENT> self.type = rectype <NEW_LINE> self._rdataset = rdataset <NEW_LINE> <DEDENT> def add(self, item): <NEW_LINE> <INDENT> if self.type == 'MX': <NEW_LINE> <INDENT> assert type(item) == types.TupleType <NEW_LINE> assert len(item) == 2 <NEW_LINE> assert type(item[0]) == types.IntType <NEW_LINE> assert type(item[1]) == types.StringType <NEW_LINE> <DEDENT> elif self.type == 'SRV': <NEW_LINE> <INDENT> assert type(item) == types.TupleType <NEW_LINE> assert len(item) == 4 <NEW_LINE> assert type(item[0]) == types.IntType <NEW_LINE> assert type(item[1]) == types.IntType <NEW_LINE> assert type(item[2]) == types.IntType <NEW_LINE> assert type(item[3]) == types.StringType <NEW_LINE> <DEDENT> elif self.type == 'TXT': <NEW_LINE> <INDENT> assert type(item) == types.StringType <NEW_LINE> if item.startswith('"') and item.endswith('"'): <NEW_LINE> <INDENT> item = item[1:-1] <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> assert type(item) == types.StringType <NEW_LINE> <DEDENT> rd = _new_rdata(self.type, item) <NEW_LINE> self._rdataset.add(rd) <NEW_LINE> <DEDENT> def delete(self, item): <NEW_LINE> <INDENT> rd = _new_rdata(self.type, item) <NEW_LINE> try: <NEW_LINE> <INDENT> self._rdataset.remove(rd) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise RecordsError("No such item in record: %s" %item) <NEW_LINE> <DEDENT> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> self._item_iter = iter(self._rdataset.items) <NEW_LINE> return self <NEW_LINE> <DEDENT> def next(self): <NEW_LINE> <INDENT> if self.type == 'MX': <NEW_LINE> <INDENT> r = self._item_iter.next() <NEW_LINE> return (r.preference, str(r.exchange)) <NEW_LINE> <DEDENT> if self.type == 'SRV': <NEW_LINE> <INDENT> r = self._item_iter.next() <NEW_LINE> return (r.priority, r.weight, r.port, str(r.target)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return str(self._item_iter.next()) <NEW_LINE> <DEDENT> <DEDENT> def get_items(self): <NEW_LINE> <INDENT> return [r for r in self] <NEW_LINE> <DEDENT> items = property(get_items) | Represents the records associated with a name node.
Record items are common DNS types such as 'A', 'MX',
'NS', etc. | 62598f9d01c39578d7f12b5d |
class GyroSensor(Sensor): <NEW_LINE> <INDENT> SYSTEM_CLASS_NAME = Sensor.SYSTEM_CLASS_NAME <NEW_LINE> SYSTEM_DEVICE_NAME_CONVENTION = Sensor.SYSTEM_DEVICE_NAME_CONVENTION <NEW_LINE> MODE_GYRO_ANG = 'GYRO-ANG' <NEW_LINE> MODE_GYRO_RATE = 'GYRO-RATE' <NEW_LINE> MODE_GYRO_FAS = 'GYRO-FAS' <NEW_LINE> MODE_GYRO_G_A = 'GYRO-G&A' <NEW_LINE> MODE_GYRO_CAL = 'GYRO-CAL' <NEW_LINE> MODE_TILT_ANG = 'TILT-ANGLE' <NEW_LINE> MODE_TILT_RATE = 'TILT-RATE' <NEW_LINE> MODES = ( MODE_GYRO_ANG, MODE_GYRO_RATE, MODE_GYRO_FAS, MODE_GYRO_G_A, MODE_GYRO_CAL, MODE_TILT_ANG, MODE_TILT_RATE, ) <NEW_LINE> def __init__(self, address=None, name_pattern=SYSTEM_DEVICE_NAME_CONVENTION, name_exact=False, **kwargs): <NEW_LINE> <INDENT> super(GyroSensor, self).__init__(address, name_pattern, name_exact, driver_name='lego-ev3-gyro', **kwargs) <NEW_LINE> self._direct = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def angle(self): <NEW_LINE> <INDENT> self._ensure_mode(self.MODE_GYRO_ANG) <NEW_LINE> return self.value(0) <NEW_LINE> <DEDENT> @property <NEW_LINE> def rate(self): <NEW_LINE> <INDENT> self._ensure_mode(self.MODE_GYRO_RATE) <NEW_LINE> return self.value(0) <NEW_LINE> <DEDENT> @property <NEW_LINE> def angle_and_rate(self): <NEW_LINE> <INDENT> self._ensure_mode(self.MODE_GYRO_G_A) <NEW_LINE> return self.value(0), self.value(1) <NEW_LINE> <DEDENT> @property <NEW_LINE> def tilt_angle(self): <NEW_LINE> <INDENT> self._ensure_mode(self.MODE_TILT_ANG) <NEW_LINE> return self.value(0) <NEW_LINE> <DEDENT> @property <NEW_LINE> def tilt_rate(self): <NEW_LINE> <INDENT> self._ensure_mode(self.MODE_TILT_RATE) <NEW_LINE> return self.value(0) <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self._ensure_mode(self.MODE_GYRO_ANG) <NEW_LINE> self._direct = self.set_attr_raw(self._direct, 'direct', 17) <NEW_LINE> <DEDENT> def wait_until_angle_changed_by(self, delta, direction_sensitive=False): <NEW_LINE> <INDENT> assert self.mode in (self.MODE_GYRO_G_A, self.MODE_GYRO_ANG, self.MODE_TILT_ANG), 'Gyro mode should be MODE_GYRO_ANG, MODE_GYRO_G_A or MODE_TILT_ANG' <NEW_LINE> start_angle = self.value(0) <NEW_LINE> if direction_sensitive: <NEW_LINE> <INDENT> if delta > 0: <NEW_LINE> <INDENT> while (self.value(0) - start_angle) < delta: <NEW_LINE> <INDENT> time.sleep(0.01) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> delta *= -1 <NEW_LINE> while (start_angle - self.value(0)) < delta: <NEW_LINE> <INDENT> time.sleep(0.01) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> while abs(start_angle - self.value(0)) < delta: <NEW_LINE> <INDENT> time.sleep(0.01) | LEGO EV3 gyro sensor. | 62598f9d8e7ae83300ee8e7f |
class kstwobign_gen(rv_continuous): <NEW_LINE> <INDENT> def _cdf(self, x): <NEW_LINE> <INDENT> return 1.0 - sc.kolmogorov(x) <NEW_LINE> <DEDENT> def _sf(self, x): <NEW_LINE> <INDENT> return sc.kolmogorov(x) <NEW_LINE> <DEDENT> def _ppf(self, q): <NEW_LINE> <INDENT> return sc.kolmogi(1.0 - q) | Kolmogorov-Smirnov two-sided test for large N.
%(default)s | 62598f9dcb5e8a47e493c064 |
class SteelCommand(BaseCommand): <NEW_LINE> <INDENT> keyword = 'steel' <NEW_LINE> help = 'SteelScript commands' <NEW_LINE> submodule = 'steelscript.commands' <NEW_LINE> @property <NEW_LINE> def subcommands(self): <NEW_LINE> <INDENT> if not self._subcommands_loaded: <NEW_LINE> <INDENT> super(SteelCommand, self).subcommands <NEW_LINE> for obj in iter_entry_points(group='steel.commands', name=None): <NEW_LINE> <INDENT> i = obj.load(obj) <NEW_LINE> if hasattr(i, 'Command'): <NEW_LINE> <INDENT> self._load_command(i) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cmd = BaseCommand(self) <NEW_LINE> cmd.keyword = obj.name <NEW_LINE> cmd.submodule = i.__name__ <NEW_LINE> cmd.help = ('Commands for {mod} module' .format(mod=i.__name__)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return self._subcommands | The 'steel' command, top of all other commands. | 62598f9deab8aa0e5d30bb65 |
class TestNodeNetworkInterfaceProperties(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testNodeNetworkInterfaceProperties(self): <NEW_LINE> <INDENT> pass | NodeNetworkInterfaceProperties unit test stubs | 62598f9d8da39b475be02fbe |
class CandidatePrometheus(object): <NEW_LINE> <INDENT> def __init__(self, push_gateaway, nodename, jobname = "Duty"): <NEW_LINE> <INDENT> self.push_gateaway = push_gateaway <NEW_LINE> self.registry = pc.CollectorRegistry() <NEW_LINE> self.nodename = nodename <NEW_LINE> self.jobname = jobname <NEW_LINE> self.heimdall_up = pc.Enum('cands_heimdall_up', 'Heimdall candidates present', states=['yes', 'no'], labelnames = ['node', 'antenna'] ) <NEW_LINE> self.fredda_up = pc.Enum('cands_fredda_up', 'Fredda candidates present', states=['yes', 'no'], labelnames = ['node', 'antenna'] ) <NEW_LINE> self.heimdall_n = pc.Gauge('cands_heimdall_num', 'Heimdall candidates number', labelnames = ['node', 'antenna'] ) <NEW_LINE> self.fredda_n = pc.Gauge('cands_fredda_num', 'Fredda candidates number', labelnames = ['node', 'antenna'] ) <NEW_LINE> <DEDENT> def __push(self): <NEW_LINE> <INDENT> pc.push_to_gateway(self.push_gateaway, job=self.jobname, registry = self.registry) <NEW_LINE> <DEDENT> def Prom(self, x): <NEW_LINE> <INDENT> if isinstance(x, NullCandidateData): <NEW_LINE> <INDENT> self.heimdall_n.labels(node=self.nodename, antenna='ea??').set(0) <NEW_LINE> <DEDENT> elif isinstance(x, CandidateData): <NEW_LINE> <INDENT> self.heimdall_up.labels(node=self.nodename, antenna=x.ant).state('yes') <NEW_LINE> self.heimdall_n.labels(node=self.nodename, antenna=x.ant).set(x.n) <NEW_LINE> <DEDENT> self.__push() | Prometheus for candidates | 62598f9d24f1403a926857a2 |
class ModelTestCase(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.category_name = "Test" <NEW_LINE> self.category = Category(name=self.category_name) <NEW_LINE> <DEDENT> def test_model_can_create_a_category(self): <NEW_LINE> <INDENT> old_count = Category.objects.count() <NEW_LINE> self.category.save() <NEW_LINE> new_count = Category.objects.count() <NEW_LINE> self.assertNotEqual(old_count, new_count) | This class defines the test suite for the Category model. | 62598f9d4e4d562566372203 |
class IPhotoFolder(Interface): <NEW_LINE> <INDENT> pass | Photo Folders store images and present a slideshow display
| 62598f9d30dc7b766599f62d |
class Meme(db.Model): <NEW_LINE> <INDENT> uid = db.StringProperty() <NEW_LINE> top = db.StringProperty() <NEW_LINE> bottom = db.StringProperty() <NEW_LINE> meme = db.BlobProperty(default=None) <NEW_LINE> thumb = db.BlobProperty(default=None) <NEW_LINE> meme_width = db.IntegerProperty <NEW_LINE> meme_height = db.IntegerProperty <NEW_LINE> template_uid = db.StringProperty() <NEW_LINE> timestamp = db.DateTimeProperty(auto_now=True) | Finalized meem | 62598f9dd7e4931a7ef3be79 |
class RecoverAccount(db.Document): <NEW_LINE> <INDENT> user = db.ReferenceField('User') <NEW_LINE> requestIP = db.StringField(default="") <NEW_LINE> created = db.DateTimeField(default=datetime.utcnow()) | An object for recovering an account | 62598f9dd99f1b3c44d05490 |
class CmdGen(): <NEW_LINE> <INDENT> def __init__(self, cmd_prototype, dataset_name): <NEW_LINE> <INDENT> self.cmd_prototype = cmd_prototype <NEW_LINE> self.dname = dataset_name <NEW_LINE> self.dataset = get_dataset(dataset_name).get_index() <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> self.i = 0 <NEW_LINE> return self <NEW_LINE> <DEDENT> def __next__(self): <NEW_LINE> <INDENT> if self.i >= len(self.dataset): <NEW_LINE> <INDENT> raise StopIteration <NEW_LINE> <DEDENT> data = self.dataset[self.i] <NEW_LINE> cmd = self.cmd_prototype.format(self.dname, data) <NEW_LINE> cmd = 'qrsh -now no -w n -cwd -noshell /bin/bash -l -c "{}"'.format(cmd) <NEW_LINE> self.i += 1 <NEW_LINE> return cmd <NEW_LINE> <DEDENT> def get_cmd_prototype(self): <NEW_LINE> <INDENT> return self.cmd_prototype <NEW_LINE> <DEDENT> def get_total_num(self): <NEW_LINE> <INDENT> return len(self.dataset) | command generator | 62598f9d1f5feb6acb162a02 |
class ResidualSeqTransducer(transducers.SeqTransducer, Serializable): <NEW_LINE> <INDENT> yaml_tag = '!ResidualSeqTransducer' <NEW_LINE> @events.register_xnmt_handler <NEW_LINE> @serializable_init <NEW_LINE> def __init__(self, child: transducers.SeqTransducer, input_dim: numbers.Integral, layer_norm: bool = False, dropout=Ref("exp_global.dropout", default=0.0), layer_norm_component: xnmt.norms.LayerNorm = None) -> None: <NEW_LINE> <INDENT> self.child = child <NEW_LINE> self.dropout = dropout <NEW_LINE> self.input_dim = input_dim <NEW_LINE> self.layer_norm = layer_norm <NEW_LINE> if layer_norm: <NEW_LINE> <INDENT> self.layer_norm_component = self.add_serializable_component("layer_norm_component", layer_norm_component, lambda: xnmt.norms.LayerNorm(hidden_dim=input_dim)) <NEW_LINE> <DEDENT> <DEDENT> @ events.handle_xnmt_event <NEW_LINE> def on_set_train(self, val): <NEW_LINE> <INDENT> self.train = val <NEW_LINE> <DEDENT> def transduce(self, seq: expression_seqs.ExpressionSequence) -> expression_seqs.ExpressionSequence: <NEW_LINE> <INDENT> if self.train and self.dropout > 0.0: <NEW_LINE> <INDENT> seq_tensor = tt.dropout(self.child.transduce(seq).as_tensor(), self.dropout) + seq.as_tensor() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> seq_tensor = self.child.transduce(seq).as_tensor() + seq.as_tensor() <NEW_LINE> <DEDENT> if self.layer_norm: <NEW_LINE> <INDENT> batch_size = tt.batch_size(seq_tensor) <NEW_LINE> merged_seq_tensor = tt.merge_time_batch_dims(seq_tensor) <NEW_LINE> transformed_seq_tensor = self.layer_norm_component.transform(merged_seq_tensor) <NEW_LINE> seq_tensor = tt.unmerge_time_batch_dims(transformed_seq_tensor, batch_size) <NEW_LINE> <DEDENT> return expression_seqs.ExpressionSequence(expr_tensor=seq_tensor) <NEW_LINE> <DEDENT> def get_final_states(self) -> List[transducers.FinalTransducerState]: <NEW_LINE> <INDENT> return self.child.get_final_states() | A sequence transducer that wraps a :class:`xnmt.transducers.base.SeqTransducer` in an additive residual
connection, and optionally performs some variety of normalization.
Args:
child: the child transducer to wrap
layer_norm: whether to perform layer normalization
dropout: whether to apply residual dropout | 62598f9dfff4ab517ebcd5ce |
class ApplyTransforms(bpy.types.Operator): <NEW_LINE> <INDENT> bl_label = "Apply Transforms" <NEW_LINE> bl_idname = "object.apply_transforms" <NEW_LINE> bl_options = {'REGISTER', 'UNDO'} <NEW_LINE> loc = BoolProperty(name="Location", default=False) <NEW_LINE> rot = BoolProperty(name="Rotation", default=True) <NEW_LINE> scale = BoolProperty(name="Scale", default=True) <NEW_LINE> def execute(self, context): <NEW_LINE> <INDENT> selected = bpy.context.selected_objects <NEW_LINE> if selected: <NEW_LINE> <INDENT> message = "Applying object transforms." <NEW_LINE> bpy.ops.object.transform_apply( location=self.loc, rotation=self.rot, scale=self.scale) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> message = "No Object Selected." <NEW_LINE> <DEDENT> self.report({'INFO'}, message) <NEW_LINE> return {'FINISHED'} <NEW_LINE> <DEDENT> def invoke(self, context, event): <NEW_LINE> <INDENT> if len(context.selected_objects) == 0: <NEW_LINE> <INDENT> self.report( {'ERROR'}, "Select one or more objects in OBJECT mode.") <NEW_LINE> return {'FINISHED'} <NEW_LINE> <DEDENT> return self.execute(context) | Click to apply transforms on selected objects. | 62598f9de76e3b2f99fd8817 |
class TaggedName(GenericTaggedItemBase, ReadPermissionMixin): <NEW_LINE> <INDENT> tag = models.ForeignKey(Tag, related_name="%(app_label)s_%(class)s_tags") | Tags to represent people names.
This class has been created to allow define restrictions on it. If had not been needed an only read view set
through the model this would not overwritten it. | 62598f9d097d151d1a2c0e08 |
class User(UserMixin, db.Model): <NEW_LINE> <INDENT> __tablename__ = 'users' <NEW_LINE> __table_args__ = {'mysql_engine': 'InnoDB'} <NEW_LINE> id = db.Column(db.String(11), doc='手机号码', primary_key=True) <NEW_LINE> password = db.Column(db.String(32), doc='密码', nullable=False) <NEW_LINE> payPassword = db.Column(db.String(32), doc='支付密码', nullable=False) <NEW_LINE> nickname = db.Column(db.String(20), doc='昵称', default='猿眼用户', nullable=False) <NEW_LINE> money = db.Column(db.Float, doc='账户余额', default=50, nullable=False) <NEW_LINE> description = db.Column(db.String(50), doc='个性签名', default='这个人很懒,什么也没留下', nullable=False) <NEW_LINE> avatar = db.Column(db.String(32), doc='头像路径', default='MonkeyEye.webp') <NEW_LINE> isAdmin = db.Column(db.Boolean, doc='是否管理员', default=False) <NEW_LINE> orders = db.relationship('Order', backref='users', cascade='all', lazy='dynamic') <NEW_LINE> coupons = db.relationship('Coupon', backref='users', cascade='all', lazy='dynamic') <NEW_LINE> favorites = db.relationship('Favorite', backref='users', cascade='all', lazy='dynamic') <NEW_LINE> comments = db.relationship('Comment', backref='users', cascade='all', lazy='dynamic') <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return '%s <%s>' % (self.nickname, self.id) <NEW_LINE> <DEDENT> def __json__(self): <NEW_LINE> <INDENT> return { 'id': self.id, 'nickname': self.nickname, 'avatar': '/static/images/user/%s' % self.avatar, 'description': self.description, 'money': self.money } | 用户 | 62598f9d498bea3a75a57902 |
class Filler: <NEW_LINE> <INDENT> chunksize = 1000 <NEW_LINE> def __init__(self, infile, sound, samplerate=None): <NEW_LINE> <INDENT> self.sound = sound <NEW_LINE> self.infile = infile <NEW_LINE> self.ratefilter = ratefilter.RateFilter() <NEW_LINE> self.samplerate = samplerate <NEW_LINE> self._write_cur = 0 <NEW_LINE> <DEDENT> def prep(self, chunk): <NEW_LINE> <INDENT> if RESAMPLE and self.ratefilter.in_hz != self.ratefilter.out_hz: <NEW_LINE> <INDENT> self.ratefilter.write(ar) <NEW_LINE> items = self.ratefilter.readable() <NEW_LINE> chunk = self.ratefilter.read(items) <NEW_LINE> <DEDENT> return chunk <NEW_LINE> <DEDENT> def write(self, chunk): <NEW_LINE> <INDENT> items = len(chunk) <NEW_LINE> if items > len(self.sound) - self._write_cur: <NEW_LINE> <INDENT> raise ValueError('not enough room in Sound buffer') <NEW_LINE> <DEDENT> dest = self.sound[self._write_cur:self._write_cur+items] <NEW_LINE> dest += chunk <NEW_LINE> self._write_cur += items <NEW_LINE> return items <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> start = time.time() <NEW_LINE> total = 0 <NEW_LINE> while True: <NEW_LINE> <INDENT> chunk = self.infile.read(self.chunksize) <NEW_LINE> total += len(chunk) <NEW_LINE> if len(chunk): <NEW_LINE> <INDENT> self.write(chunk) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> ms = (time.time() - start) * 1000.0 <NEW_LINE> msg = 'FILLED %s (%i frames in %f ms)' % (self.infile, self.infile.length, ms) <NEW_LINE> self.full = True | buffer filler | 62598f9d3d592f4c4edbacaf |
class InlineAdminForm(DjangoInlineAdminForm, AdminForm): <NEW_LINE> <INDENT> def __init__(self, formset, form, fieldsets, prepopulated_fields, original, readonly_fields=None, model_admin=None): <NEW_LINE> <INDENT> self.formset = formset <NEW_LINE> self.model_admin = model_admin <NEW_LINE> self.original = original <NEW_LINE> self.show_url = original and hasattr(original, 'get_absolute_url') <NEW_LINE> AdminForm.__init__(self, form, fieldsets, prepopulated_fields, readonly_fields, model_admin) <NEW_LINE> <DEDENT> def pk_field(self): <NEW_LINE> <INDENT> if hasattr(self.formset, "_pk_field"): <NEW_LINE> <INDENT> return DjangoInlineAdminForm.pk_field(self) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> for name, options in self.fieldsets: <NEW_LINE> <INDENT> yield InlineFieldset(self.formset, self.form, name, self.readonly_fields, model_admin=self.model_admin, **options) | A wrapper around an inline form for use in the admin system. | 62598f9da79ad16197769e45 |
class LoginPage(base.Page): <NEW_LINE> <INDENT> URL = environment.APP_URL <NEW_LINE> def __init__(self, driver): <NEW_LINE> <INDENT> super(LoginPage, self).__init__(driver) <NEW_LINE> self.button_login = base.Button(driver, locator.Login.BUTTON_LOGIN) <NEW_LINE> <DEDENT> def login(self): <NEW_LINE> <INDENT> self.button_login.click() <NEW_LINE> return dashboard.Dashboard(self._driver) <NEW_LINE> <DEDENT> def login_as(self, user_name, user_email): <NEW_LINE> <INDENT> raise NotImplementedError | Login page model. | 62598f9d91af0d3eaad39bec |
class Player(): <NEW_LINE> <INDENT> def __init__(self, name, hand): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.hand = hand <NEW_LINE> <DEDENT> def play_card(self): <NEW_LINE> <INDENT> drawn_card = self.hand.remove_card() <NEW_LINE> print("{} has placed: {}".format(self.name,drawn_card)) <NEW_LINE> print('\n') <NEW_LINE> return drawn_card <NEW_LINE> <DEDENT> def remove_war_cards(self): <NEW_LINE> <INDENT> war_cards = [] <NEW_LINE> if len(self.hand.cards) < 3: <NEW_LINE> <INDENT> return war_cards <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for x in range(3): <NEW_LINE> <INDENT> war_cards.append(self.hand.cards.pop()) <NEW_LINE> <DEDENT> return war_cards <NEW_LINE> <DEDENT> <DEDENT> def still_has_cards(self): <NEW_LINE> <INDENT> return len(self.hand.cards) != 0 | This is the Player class, which takes in a name and an instance of a Hand
class object. The Payer can then play cards and check if they still have cards. | 62598f9d01c39578d7f12b5f |
class PhabricatorSource: <NEW_LINE> <INDENT> base_url: str <NEW_LINE> token: str <NEW_LINE> story_limit: int <NEW_LINE> def __init__(self, server, token, story_limit): <NEW_LINE> <INDENT> self.base_url = f"{server}/api" <NEW_LINE> self.token = token <NEW_LINE> self.story_limit = story_limit <NEW_LINE> <DEDENT> def _request(self, endpoint, **query_parameters): <NEW_LINE> <INDENT> query_parameters = {k: v for k, v in query_parameters.items() if v} <NEW_LINE> url = f"{self.base_url}/{endpoint}" <NEW_LINE> body = { "params": json.dumps( {"__conduit__": {"token": self.token}, **query_parameters} ) } <NEW_LINE> try: <NEW_LINE> <INDENT> result = requests.post(url, data=body) <NEW_LINE> <DEDENT> except RequestException: <NEW_LINE> <INDENT> raise PhabricatorException("Could not communicate with Phabricator") <NEW_LINE> <DEDENT> if result.status_code != 200: <NEW_LINE> <INDENT> raise PhabricatorException( f"Phabricator request had incorrect status of {result.status_code}. " f"The full response is: {result.text}" ) <NEW_LINE> <DEDENT> body = result.json() <NEW_LINE> if body["error_code"]: <NEW_LINE> <INDENT> raise PhabricatorException(f"Phabricator request had an error: {body}") <NEW_LINE> <DEDENT> return body <NEW_LINE> <DEDENT> def fetch_feed_end(self): <NEW_LINE> <INDENT> body = self._request("feed.for_email.status") <NEW_LINE> return int(body["result"]) <NEW_LINE> <DEDENT> def fetch_next(self, after): <NEW_LINE> <INDENT> body = self._request( "feed.for_email.query", storyLimit=self.story_limit, after=after if after else None, ) <NEW_LINE> return json.loads(body["result"]) | Fetches feed information directly from the Phabricator API. | 62598f9d0c0af96317c56164 |
class JoinFinishForm(forms.ModelForm): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = Member <NEW_LINE> fields = ('image',) <NEW_LINE> <DEDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(JoinFinishForm, self).__init__(*args, **kwargs) <NEW_LINE> self.fields['image'].label = _("Upload a picture") <NEW_LINE> self.fields['image'].help_text = _("JPG, GIF or PNG accepted. Square is best. Keep it under 1MB.") <NEW_LINE> self.fields['image'].widget = forms.FileInput() <NEW_LINE> self.default_avatars = DefaultAvatar.objects.all() <NEW_LINE> <DEDENT> def clean(self): <NEW_LINE> <INDENT> cleaned_data = super(JoinFinishForm, self).clean() <NEW_LINE> if not cleaned_data.get('image'): <NEW_LINE> <INDENT> if not self.data.has_key('default_avatar_id'): <NEW_LINE> <INDENT> raise forms.ValidationError(_("Please upload or select a picture.")) <NEW_LINE> <DEDENT> <DEDENT> return cleaned_data <NEW_LINE> <DEDENT> def save(self, commit=True): <NEW_LINE> <INDENT> instance = super(JoinFinishForm, self).save(commit=commit) <NEW_LINE> if not instance.image and self.data.has_key('default_avatar_id'): <NEW_LINE> <INDENT> obj = DefaultAvatar.objects.get(id=self.data['default_avatar_id']) <NEW_LINE> instance.image = obj.image <NEW_LINE> if commit: <NEW_LINE> <INDENT> instance.save() <NEW_LINE> <DEDENT> <DEDENT> return instance <NEW_LINE> <DEDENT> as_div = as_div | Show avatar selection form | 62598f9db5575c28eb712bbe |
class MotionController(Protocol): <NEW_LINE> <INDENT> async def halt(self) -> None: <NEW_LINE> <INDENT> ... <NEW_LINE> <DEDENT> async def stop(self, home_after: bool = True) -> None: <NEW_LINE> <INDENT> ... <NEW_LINE> <DEDENT> async def reset(self) -> None: <NEW_LINE> <INDENT> ... <NEW_LINE> <DEDENT> async def home_z(self, mount: Optional[Mount] = None) -> None: <NEW_LINE> <INDENT> ... <NEW_LINE> <DEDENT> async def home_plunger(self, mount: Mount) -> None: <NEW_LINE> <INDENT> ... <NEW_LINE> <DEDENT> async def home(self, axes: Optional[List[Axis]] = None) -> None: <NEW_LINE> <INDENT> ... <NEW_LINE> <DEDENT> async def current_position( self, mount: Mount, critical_point: Optional[CriticalPoint] = None, refresh: bool = False, fail_on_not_homed: bool = False, ) -> Dict[Axis, float]: <NEW_LINE> <INDENT> ... <NEW_LINE> <DEDENT> async def gantry_position( self, mount: Mount, critical_point: Optional[CriticalPoint] = None, refresh: bool = False, fail_on_not_homed: bool = False, ) -> Point: <NEW_LINE> <INDENT> ... <NEW_LINE> <DEDENT> async def move_to( self, mount: Mount, abs_position: Point, speed: Optional[float] = None, critical_point: Optional[CriticalPoint] = None, max_speeds: Optional[Dict[Axis, float]] = None, ) -> None: <NEW_LINE> <INDENT> ... <NEW_LINE> <DEDENT> async def move_rel( self, mount: Mount, delta: Point, speed: Optional[float] = None, max_speeds: Optional[Dict[Axis, float]] = None, check_bounds: MotionChecks = MotionChecks.NONE, fail_on_not_homed: bool = False, ) -> None: <NEW_LINE> <INDENT> ... <NEW_LINE> <DEDENT> def get_engaged_axes(self) -> Dict[Axis, bool]: <NEW_LINE> <INDENT> ... <NEW_LINE> <DEDENT> @property <NEW_LINE> def engaged_axes(self) -> Dict[Axis, bool]: <NEW_LINE> <INDENT> return self.get_engaged_axes() <NEW_LINE> <DEDENT> async def disengage_axes(self, which: List[Axis]) -> None: <NEW_LINE> <INDENT> ... <NEW_LINE> <DEDENT> async def retract(self, mount: Mount, margin: float = 10) -> None: <NEW_LINE> <INDENT> ... | Protocol specifying fundamental motion controls. | 62598f9df7d966606f747dc9 |
class WindowedTextsAnalyzer(UsesDictionary): <NEW_LINE> <INDENT> def __init__(self, relevant_ids, dictionary): <NEW_LINE> <INDENT> super(WindowedTextsAnalyzer, self).__init__(relevant_ids, dictionary) <NEW_LINE> self._none_token = self._vocab_size <NEW_LINE> <DEDENT> def accumulate(self, texts, window_size): <NEW_LINE> <INDENT> relevant_texts = self._iter_texts(texts) <NEW_LINE> windows = utils.iter_windows( relevant_texts, window_size, ignore_below_size=False, include_doc_num=True) <NEW_LINE> for doc_num, virtual_document in windows: <NEW_LINE> <INDENT> self.analyze_text(virtual_document, doc_num) <NEW_LINE> self.num_docs += 1 <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> def _iter_texts(self, texts): <NEW_LINE> <INDENT> dtype = np.uint16 if np.iinfo(np.uint16).max >= self._vocab_size else np.uint32 <NEW_LINE> for text in texts: <NEW_LINE> <INDENT> if self.text_is_relevant(text): <NEW_LINE> <INDENT> yield np.array([ self.id2contiguous[self.token2id[w]] if w in self.relevant_words else self._none_token for w in text], dtype=dtype) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def text_is_relevant(self, text): <NEW_LINE> <INDENT> for word in text: <NEW_LINE> <INDENT> if word in self.relevant_words: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False | Gather some stats about relevant terms of a corpus by iterating over windows of texts. | 62598f9d0a50d4780f7051bb |
class BaseSSHTransportDHGroupExchangeSHA1Tests( BaseSSHTransportDHGroupExchangeBaseCase, DHGroupExchangeSHA1Mixin, TransportTestCase): <NEW_LINE> <INDENT> pass | diffie-hellman-group-exchange-sha1 tests for TransportBase. | 62598f9d99cbb53fe6830cb4 |
class ParentPathError(Exception): <NEW_LINE> <INDENT> def __init__(self, path: str, parent_path: str, message: Optional[str] = None): <NEW_LINE> <INDENT> self.path = path <NEW_LINE> self.sandbox_path = parent_path <NEW_LINE> self.message = message or f'{path} is not a part of {parent_path}' <NEW_LINE> super().__init__(self.message) | ParentPathError class. | 62598f9d090684286d5935cb |
class TaskPool(BasePool): <NEW_LINE> <INDENT> Pool = Pool <NEW_LINE> requires_mediator = True <NEW_LINE> uses_semaphore = True <NEW_LINE> def on_start(self): <NEW_LINE> <INDENT> self._pool = self.Pool(processes=self.limit, initializer=process_initializer, **self.options) <NEW_LINE> self.on_apply = self._pool.apply_async <NEW_LINE> <DEDENT> def did_start_ok(self): <NEW_LINE> <INDENT> return self._pool.did_start_ok() <NEW_LINE> <DEDENT> def on_stop(self): <NEW_LINE> <INDENT> if self._pool is not None and self._pool._state in (RUN, CLOSE): <NEW_LINE> <INDENT> self._pool.close() <NEW_LINE> self._pool.join() <NEW_LINE> self._pool = None <NEW_LINE> <DEDENT> <DEDENT> def on_terminate(self): <NEW_LINE> <INDENT> if self._pool is not None: <NEW_LINE> <INDENT> self._pool.terminate() <NEW_LINE> self._pool = None <NEW_LINE> <DEDENT> <DEDENT> def on_close(self): <NEW_LINE> <INDENT> if self._pool is not None and self._pool._state == RUN: <NEW_LINE> <INDENT> self._pool.close() <NEW_LINE> <DEDENT> <DEDENT> def terminate_job(self, pid, signal=None): <NEW_LINE> <INDENT> _kill(pid, signal or _signal.SIGTERM) <NEW_LINE> <DEDENT> def grow(self, n=1): <NEW_LINE> <INDENT> return self._pool.grow(n) <NEW_LINE> <DEDENT> def shrink(self, n=1): <NEW_LINE> <INDENT> return self._pool.shrink(n) <NEW_LINE> <DEDENT> def restart(self): <NEW_LINE> <INDENT> self._pool.restart() <NEW_LINE> <DEDENT> def _get_info(self): <NEW_LINE> <INDENT> return {"max-concurrency": self.limit, "processes": [p.pid for p in self._pool._pool], "max-tasks-per-child": self._pool._maxtasksperchild, "put-guarded-by-semaphore": self.putlocks, "timeouts": (self._pool.soft_timeout, self._pool.timeout)} <NEW_LINE> <DEDENT> def set_on_process_up(self, callback): <NEW_LINE> <INDENT> self._pool.on_process_up <NEW_LINE> <DEDENT> def _get_on_process_up(self): <NEW_LINE> <INDENT> return self._pool.on_process_up <NEW_LINE> <DEDENT> def _set_on_process_up(self, fun): <NEW_LINE> <INDENT> self._pool.on_process_up = fun <NEW_LINE> <DEDENT> on_process_up = property(_get_on_process_up, _set_on_process_up) <NEW_LINE> def _get_on_process_down(self): <NEW_LINE> <INDENT> return self._pool.on_process_down <NEW_LINE> <DEDENT> def _set_on_process_down(self, fun): <NEW_LINE> <INDENT> self._pool.on_process_down = fun <NEW_LINE> <DEDENT> on_process_down = property(_get_on_process_down, _set_on_process_down) <NEW_LINE> @property <NEW_LINE> def num_processes(self): <NEW_LINE> <INDENT> return self._pool._processes <NEW_LINE> <DEDENT> @property <NEW_LINE> def readers(self): <NEW_LINE> <INDENT> return self._pool.readers <NEW_LINE> <DEDENT> @property <NEW_LINE> def writers(self): <NEW_LINE> <INDENT> return self._pool.writers <NEW_LINE> <DEDENT> @property <NEW_LINE> def timers(self): <NEW_LINE> <INDENT> return {self._pool.maintain_pool: 30} | Multiprocessing Pool implementation. | 62598f9d67a9b606de545dab |
class TestEmbeddedStruct(rdf_structs.RDFProtoStruct): <NEW_LINE> <INDENT> type_description = type_info.TypeDescriptorSet( rdf_structs.ProtoString(name="e_string_field", field_number=1), rdf_structs.ProtoDouble(name="e_double_field", field_number=2)) | Custom struct for testing schema generation. | 62598f9d656771135c489465 |
class State(Base): <NEW_LINE> <INDENT> __tablename__ = 'states' <NEW_LINE> id = Column(Integer, unique=True, primary_key=True, nullable=False) <NEW_LINE> name = Column(String(128), nullable=False) | Class of states table | 62598f9d097d151d1a2c0e0a |
class NotRespondingError(PJCError): <NEW_LINE> <INDENT> pass | Exception raised if the device does not appear to be responding; that is, it never sent back
a response to a sent command. | 62598f9e21a7993f00c65d65 |
class ParserVariable: <NEW_LINE> <INDENT> def __init__(self, s, rvalue): <NEW_LINE> <INDENT> self.className = None <NEW_LINE> self.methodName = None <NEW_LINE> self.value = None <NEW_LINE> self.comment = None <NEW_LINE> self.isCustomClass = False <NEW_LINE> if s is not None: <NEW_LINE> <INDENT> s = s.strip() <NEW_LINE> if rvalue is not None: <NEW_LINE> <INDENT> if s.startswith("#"): <NEW_LINE> <INDENT> raise ValueError("A comment can't be an lvalue.") <NEW_LINE> <DEDENT> self.className = None <NEW_LINE> if rvalue.className == 'None': <NEW_LINE> <INDENT> self.className = s <NEW_LINE> <DEDENT> self.value = s <NEW_LINE> if Parser.isEnclosed(s, "<"): <NEW_LINE> <INDENT> self.className = s[1:-1] <NEW_LINE> self.isCustomClass = True <NEW_LINE> <DEDENT> elif s.endswith("()"): <NEW_LINE> <INDENT> raise ValueError("A method can't be an lvalue.") <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if s.startswith("#"): <NEW_LINE> <INDENT> s = "" <NEW_LINE> self.comment = s[1:] <NEW_LINE> <DEDENT> if len(s) == 0: <NEW_LINE> <INDENT> self.value = None <NEW_LINE> self.className = 'None' <NEW_LINE> <DEDENT> elif Parser.isQuoted(s): <NEW_LINE> <INDENT> self.value = s[1:-1] <NEW_LINE> self.className = 'string' <NEW_LINE> <DEDENT> elif s.endswith("()"): <NEW_LINE> <INDENT> self.value = s <NEW_LINE> self.methodName = s[:-2] <NEW_LINE> <DEDENT> elif Parser.isEnclosed(s, '('): <NEW_LINE> <INDENT> v = s[1:-1] <NEW_LINE> try: <NEW_LINE> <INDENT> values = [int(c) for c in v.split(",")] <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> values = [float(c) for c in v.split(",")] <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> values = v.split(",") <NEW_LINE> warn("A tuple of this type is not" " implemented, it will have strings:" " `{}`".format(s)) <NEW_LINE> <DEDENT> <DEDENT> self.value = tuple(values) <NEW_LINE> self.className = 'tuple' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.value = int(s) <NEW_LINE> self.className = "int" <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.value = float(s) <NEW_LINE> self.className = "float" <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> self.value = s <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def __get__(self, instance, owner): <NEW_LINE> <INDENT> return self.value <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.value) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return str(self.value) <NEW_LINE> <DEDENT> def __set__(self, instance, value): <NEW_LINE> <INDENT> self.value = value | A ParserVariable instance holds information about a value.
Properties:
className -- The class of the value, if detected. If the type is
None, then className holds a string of the word 'None'.
However, if no type is detected, then className
actually is None. | 62598f9e7cff6e4e811b5805 |
class Encoder(nn.Module): <NEW_LINE> <INDENT> num_blocks: int <NEW_LINE> num_channels: int <NEW_LINE> bottlenecked_num_channels: int <NEW_LINE> downsampling_rates: Sequence[Tuple[int, int]] <NEW_LINE> precision: Optional[jax.lax.Precision] = None <NEW_LINE> def setup(self): <NEW_LINE> <INDENT> self._in_conv = blocks_lib.get_vdvae_convolution( self.num_channels, (3, 3), name='in_conv', precision=self.precision) <NEW_LINE> sampling_rates = sorted(self.downsampling_rates) <NEW_LINE> num_blocks = self.num_blocks <NEW_LINE> current_sequence_start = 0 <NEW_LINE> blocks = [] <NEW_LINE> for block_idx, rate in sampling_rates: <NEW_LINE> <INDENT> if rate == 1: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> sequence_length = block_idx - current_sequence_start <NEW_LINE> if sequence_length > 0: <NEW_LINE> <INDENT> for i in range(current_sequence_start, block_idx): <NEW_LINE> <INDENT> blocks.append( blocks_lib.ResBlock( self.bottlenecked_num_channels, self.num_channels, downsampling_rate=1, use_residual_connection=True, last_weights_scale=np.sqrt(1.0 / self.num_blocks), precision=self.precision, name=f'res_block_{i}')) <NEW_LINE> <DEDENT> <DEDENT> blocks.append( blocks_lib.ResBlock( self.bottlenecked_num_channels, self.num_channels, downsampling_rate=rate, use_residual_connection=True, last_weights_scale=np.sqrt(1.0 / self.num_blocks), precision=self.precision, name=f'res_block_{block_idx}')) <NEW_LINE> current_sequence_start = block_idx + 1 <NEW_LINE> <DEDENT> sequence_length = num_blocks - current_sequence_start <NEW_LINE> if sequence_length > 0: <NEW_LINE> <INDENT> for i in range(current_sequence_start, num_blocks): <NEW_LINE> <INDENT> blocks.append( blocks_lib.ResBlock( self.bottlenecked_num_channels, self.num_channels, downsampling_rate=1, use_residual_connection=True, last_weights_scale=np.sqrt(1.0 / self.num_blocks), precision=self.precision, name=f'res_block_{i}')) <NEW_LINE> <DEDENT> <DEDENT> self._blocks = blocks <NEW_LINE> <DEDENT> def __call__( self, inputs, context_vectors = None, ): <NEW_LINE> <INDENT> if inputs.dtype != jnp.float32: <NEW_LINE> <INDENT> raise ValueError('Expected inputs to be of type float32 but got ' f'{inputs.dtype}') <NEW_LINE> <DEDENT> if len(inputs.shape) != 4 or inputs.shape[1] != inputs.shape[2]: <NEW_LINE> <INDENT> raise ValueError('inputs should be a batch of images of shape ' f'[B, H, W, C] with H=W, but got {inputs.shape}') <NEW_LINE> <DEDENT> outputs = self._in_conv(inputs) <NEW_LINE> resolution = outputs.shape[1] <NEW_LINE> activations = {resolution: outputs} <NEW_LINE> for block in self._blocks: <NEW_LINE> <INDENT> outputs = block(outputs, context_vectors) <NEW_LINE> resolution = outputs.shape[1] <NEW_LINE> activations[resolution] = outputs <NEW_LINE> <DEDENT> return activations | The Encoder of a VDVAE, mapping from images to latents. | 62598f9e8e7ae83300ee8e82 |
class Scheduler(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.events = list() <NEW_LINE> self.update = self.update_noprofile <NEW_LINE> self._profile = False <NEW_LINE> self.profile = False <NEW_LINE> self._profiler = cProfile.Profile() <NEW_LINE> self.error_handler = None <NEW_LINE> <DEDENT> def update_profiled(self): <NEW_LINE> <INDENT> self._profiler.runcall(self.update_noprofile) <NEW_LINE> <DEDENT> def print_stats(self): <NEW_LINE> <INDENT> self._profiler.print_stats(1) <NEW_LINE> <DEDENT> def update_noprofile(self): <NEW_LINE> <INDENT> errors = list() <NEW_LINE> for event in self.events: <NEW_LINE> <INDENT> if event.time_until_next_run <= 0: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> keep = event() <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> exception_info = sys.exc_info() <NEW_LINE> errors.append((err, exception_info)) <NEW_LINE> keep = False <NEW_LINE> <DEDENT> if not keep: <NEW_LINE> <INDENT> self.events.remove(event) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> for err in errors: <NEW_LINE> <INDENT> if self.error_handler is None: <NEW_LINE> <INDENT> print("ARRGH!") <NEW_LINE> raise err[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.error_handler(err[1]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def register(self, event): <NEW_LINE> <INDENT> self.events.append(event) <NEW_LINE> <DEDENT> def remove(self, event): <NEW_LINE> <INDENT> self.events.remove(event) <NEW_LINE> <DEDENT> @property <NEW_LINE> def profile(self): <NEW_LINE> <INDENT> return self._profile <NEW_LINE> <DEDENT> @profile.setter <NEW_LINE> def profile(self, val): <NEW_LINE> <INDENT> self._profile = val <NEW_LINE> if val: <NEW_LINE> <INDENT> self.update = self.update_profiled <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.update = self.update_noprofile | A scheduler for running functions. By default one is initilized
in bge.logic.scheduler, though others can easily be created.
Note that the scheduler has to be updated manually each frame. | 62598f9e38b623060ffa8e74 |
class MeanAbsoluteError(function_node.FunctionNode): <NEW_LINE> <INDENT> def __init__(self, ignore_nan=False): <NEW_LINE> <INDENT> self.ignore_nan = ignore_nan <NEW_LINE> <DEDENT> def check_type_forward(self, in_types): <NEW_LINE> <INDENT> type_check.expect(in_types.size() == 2) <NEW_LINE> type_check.expect( in_types[0].dtype == numpy.float32, in_types[1].dtype == numpy.float32, in_types[0].shape == in_types[1].shape ) <NEW_LINE> <DEDENT> def forward_cpu(self, inputs): <NEW_LINE> <INDENT> self.retain_inputs((0, 1)) <NEW_LINE> x0, x1 = inputs <NEW_LINE> diff = (inputs[0] - inputs[1]).ravel() <NEW_LINE> if self.ignore_nan: <NEW_LINE> <INDENT> diff[numpy.isnan(diff)] = 0. <NEW_LINE> <DEDENT> return numpy.array(abs(diff).sum() / diff.size, dtype=diff.dtype), <NEW_LINE> <DEDENT> def forward_gpu(self, inputs): <NEW_LINE> <INDENT> self.retain_inputs((0, 1)) <NEW_LINE> cupy = cuda.cupy <NEW_LINE> diff = (inputs[0] - inputs[1]).ravel() <NEW_LINE> if self.ignore_nan: <NEW_LINE> <INDENT> diff[cupy.isnan(diff)] = 0. <NEW_LINE> <DEDENT> return abs(diff).sum() / diff.dtype.type(diff.size), <NEW_LINE> <DEDENT> def backward(self, indexes, gy): <NEW_LINE> <INDENT> x0, x1 = self.get_retained_inputs() <NEW_LINE> xp = cuda.get_array_module(x0) <NEW_LINE> diff = x0 - x1 <NEW_LINE> if self.ignore_nan: <NEW_LINE> <INDENT> diff = chainer.functions.where(xp.isnan(diff.array), xp.zeros_like(diff.array), diff) <NEW_LINE> <DEDENT> gy0 = chainer.functions.broadcast_to(gy[0], diff.shape) <NEW_LINE> gx0 = gy0 * chainer.functions.sign(diff) * 1. / diff.size <NEW_LINE> return gx0, -gx0 | Mean absolute error function. | 62598f9e60cbc95b06364130 |
class SPMError(EntropyException): <NEW_LINE> <INDENT> pass | Source Package Manager generic errors | 62598f9e4428ac0f6e65830d |
class NavigationDrawerException(Exception): <NEW_LINE> <INDENT> pass | Raised when add_widget or remove_widget called incorrectly on a
NavigationDrawer. | 62598f9e9c8ee8231304005f |
class BudgetYearAddTest(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> create_user() <NEW_LINE> systems = create_financial_code_systems() <NEW_LINE> self.valid_data = { "financial_code_system": systems[0].id, "date_start": "2017-04-01", "date_end": "2018-03-31", "short_name": "2017-2018", } <NEW_LINE> <DEDENT> def test_year_add_redirect_if_not_logged_in(self): <NEW_LINE> <INDENT> response = self.client.get(reverse("financial_codes:year_add")) <NEW_LINE> self.assertEqual(response.status_code, 302) <NEW_LINE> <DEDENT> def test_year_add_no_redirect_if_logged_in(self): <NEW_LINE> <INDENT> self.client.login(username="user", password="abcd123456") <NEW_LINE> response = self.client.get(reverse("financial_codes:year_add")) <NEW_LINE> self.assertEqual(str(response.context['user']), 'user') <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> <DEDENT> def test_year_add_url_exists_at_desired_location(self): <NEW_LINE> <INDENT> self.client.login(username="user", password="abcd123456") <NEW_LINE> response = self.client.get("/settings/codes/year/add/") <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> <DEDENT> def test_year_add_accessible_by_name(self): <NEW_LINE> <INDENT> self.client.login(username="user", password="abcd123456") <NEW_LINE> response = self.client.get(reverse("financial_codes:year_add")) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> <DEDENT> def test_year_add_template(self): <NEW_LINE> <INDENT> self.client.login(username="user", password="abcd123456") <NEW_LINE> response = self.client.get(reverse("financial_codes:year_add")) <NEW_LINE> self.assertTemplateUsed(response, "financial_codes/add_edit.html") <NEW_LINE> <DEDENT> def test_year_add_redirect_to_dashboard(self): <NEW_LINE> <INDENT> self.client.login(username="user", password="abcd123456") <NEW_LINE> response = self.client.post( reverse("financial_codes:year_add"), self.valid_data, follow=True, ) <NEW_LINE> self.assertRedirects(response, reverse("financial_codes:dashboard")) <NEW_LINE> <DEDENT> def test_year_add_confirm_add(self): <NEW_LINE> <INDENT> self.client.login(username="user", password="abcd123456") <NEW_LINE> self.client.post( reverse("financial_codes:year_add"), self.valid_data, follow=True, ) <NEW_LINE> self.assertEqual(1, BudgetYear.objects.count()) <NEW_LINE> <DEDENT> def test_year_add_no_redirect_on_invalid_data(self): <NEW_LINE> <INDENT> invalid_data = self.valid_data <NEW_LINE> invalid_data["date_start"] = '' <NEW_LINE> self.client.login(username="user", password="abcd123456") <NEW_LINE> response = self.client.post( reverse("financial_codes:year_add"), invalid_data, follow=True, ) <NEW_LINE> self.assertEqual(response.status_code, 200) | Tests for the add financial code group view | 62598f9e07f4c71912baf22e |
class Settings(dict): <NEW_LINE> <INDENT> app_id = None <NEW_LINE> settings_directory = None <NEW_LINE> settings_file = None <NEW_LINE> _settings_types = {} <NEW_LINE> _settings_defaults = {} <NEW_LINE> def __init__(self, app_id): <NEW_LINE> <INDENT> self.app_id = app_id <NEW_LINE> self.settings_directory = appdirs.user_data_dir(app_id, appauthor=app_id, roaming=True) <NEW_LINE> self.settings_file = os.path.join(self.settings_directory, "settings.cfg") <NEW_LINE> super(Settings, self).__init__() <NEW_LINE> <DEDENT> def add_setting(self, setting_name, setting_type=str, default=None): <NEW_LINE> <INDENT> self._settings_types[setting_name] = setting_type <NEW_LINE> self._settings_defaults[setting_name] = default <NEW_LINE> <DEDENT> def load_settings(self): <NEW_LINE> <INDENT> for key, value in self._settings_defaults.items(): <NEW_LINE> <INDENT> if key not in self._settings_types: <NEW_LINE> <INDENT> self._settings_types[key] = str <NEW_LINE> <DEDENT> super(Settings, self).__setitem__(key, value) <NEW_LINE> <DEDENT> parser = configparser.RawConfigParser() <NEW_LINE> try: <NEW_LINE> <INDENT> with open(self.settings_file, 'r') as settings_fp: <NEW_LINE> <INDENT> parser.readfp(settings_fp) <NEW_LINE> for key, value in parser.items('settings'): <NEW_LINE> <INDENT> if key not in self._settings_types: <NEW_LINE> <INDENT> self._settings_types[key] = str <NEW_LINE> <DEDENT> adjusted_value = value <NEW_LINE> if issubclass(self._settings_types[key], bool): <NEW_LINE> <INDENT> adjusted_value = parser.getboolean('settings', key) <NEW_LINE> <DEDENT> elif issubclass(self._settings_types[key], int): <NEW_LINE> <INDENT> adjusted_value = parser.getint('settings', key) <NEW_LINE> <DEDENT> elif issubclass(self._settings_types[key], float): <NEW_LINE> <INDENT> adjusted_value = parser.getfloat('settings', key) <NEW_LINE> <DEDENT> elif issubclass(self._settings_types[key], (dict, list, set)): <NEW_LINE> <INDENT> adjusted_value = self._settings_types[key]( ast.literal_eval(value)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> adjusted_value = self._settings_types[key](value) <NEW_LINE> <DEDENT> super(Settings, self).__setitem__(key, adjusted_value) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except IOError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def save_settings(self): <NEW_LINE> <INDENT> if not os.path.exists(self.settings_directory): <NEW_LINE> <INDENT> os.makedirs(self.settings_directory, 0o755) <NEW_LINE> <DEDENT> parser = configparser.RawConfigParser() <NEW_LINE> parser.add_section('settings') <NEW_LINE> for key, value in self.items(): <NEW_LINE> <INDENT> parser.set('settings', key, value) <NEW_LINE> <DEDENT> with open(self.settings_file, 'w') as settings_fp: <NEW_LINE> <INDENT> parser.write(settings_fp) <NEW_LINE> <DEDENT> <DEDENT> def __getattr__(self, setting_name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return super(Settings, self).__getitem__(setting_name) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise AttributeError <NEW_LINE> <DEDENT> <DEDENT> def __setattr__(self, setting_name, setting_value): <NEW_LINE> <INDENT> if setting_name in self._settings_defaults: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return super(Settings, self).__setitem__(setting_name, setting_value) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise AttributeError <NEW_LINE> <DEDENT> <DEDENT> return super(Settings, self).__setattr__(setting_name, setting_value) | Provide interface for portable persistent user editable settings | 62598f9e498bea3a75a57904 |
class VideoDescriptor(VideoFields, RawDescriptor): <NEW_LINE> <INDENT> module_class = VideoModule <NEW_LINE> stores_state = True <NEW_LINE> template_dir_name = "video" | Descriptor for `VideoModule`. | 62598f9e01c39578d7f12b61 |
class InfoDownloader(Downloader): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> Downloader.__init__(self) <NEW_LINE> <DEDENT> def cache_artist_info(self, artist): <NEW_LINE> <INDENT> if not get_network_available("DATA"): <NEW_LINE> <INDENT> self.emit("artist-info-changed", artist) <NEW_LINE> return <NEW_LINE> <DEDENT> App().task_helper.run(self.__cache_artist_info, artist) <NEW_LINE> <DEDENT> def _get_audiodb_artist_info(self, artist): <NEW_LINE> <INDENT> if not get_network_available("AUDIODB"): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> artist = GLib.uri_escape_string(artist, None, True) <NEW_LINE> uri = "https://theaudiodb.com/api/v1/json/" <NEW_LINE> uri += "%s/search.php?s=%s" % (AUDIODB_CLIENT_ID, artist) <NEW_LINE> (status, data) = App().task_helper.load_uri_content_sync(uri, None) <NEW_LINE> if status: <NEW_LINE> <INDENT> decode = json.loads(data.decode("utf-8")) <NEW_LINE> language = getdefaultlocale()[0][-2:] <NEW_LINE> for item in decode["artists"]: <NEW_LINE> <INDENT> for key in ["strBiography%s" % language, "strBiographyEN"]: <NEW_LINE> <INDENT> info = item[key] <NEW_LINE> if info is not None: <NEW_LINE> <INDENT> return info.encode("utf-8") <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> Logger.error("InfoDownloader::_get_audiodb_artist_info: %s, %s" % (e, artist)) <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def _get_lastfm_artist_info(self, artist): <NEW_LINE> <INDENT> info = None <NEW_LINE> try: <NEW_LINE> <INDENT> if App().lastfm is not None and get_network_available("LASTFM"): <NEW_LINE> <INDENT> info = App().lastfm.get_artist_bio(artist) <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> Logger.error("InfoDownloader::_get_lastfm_artist_info(): %s" % e) <NEW_LINE> <DEDENT> return info <NEW_LINE> <DEDENT> def __cache_artist_info(self, artist): <NEW_LINE> <INDENT> content = None <NEW_LINE> try: <NEW_LINE> <INDENT> if get_network_available("WIKIPEDIA"): <NEW_LINE> <INDENT> wikipedia = Wikipedia() <NEW_LINE> content = wikipedia.get_content(artist) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for (api, a_helper, ar_helper, helper) in self._WEBSERVICES: <NEW_LINE> <INDENT> if helper is None: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> method = getattr(self, helper) <NEW_LINE> content = method(artist) <NEW_LINE> if content is not None: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> Logger.error( "InfoDownloader::__cache_artists_artwork(): %s" % e) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self.save_artist_information(artist, content) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> Logger.info("InfoDownloader::__cache_artist_info(): %s" % e) <NEW_LINE> <DEDENT> GLib.idle_add(self.emit, "artist-info-changed", artist) | Download info from the web | 62598f9ec432627299fa2dbc |
class covariance_test(two_sample_test): <NEW_LINE> <INDENT> required_capabilities = (ProducesSpikeTrains, ) <NEW_LINE> def generate_prediction(self, model, **kwargs): <NEW_LINE> <INDENT> covariances = self.get_prediction(model) <NEW_LINE> if covariances is None: <NEW_LINE> <INDENT> if kwargs: <NEW_LINE> <INDENT> self.params.update(kwargs) <NEW_LINE> <DEDENT> if 'binsize' not in self.params and 'num_bins' not in self.params: <NEW_LINE> <INDENT> self.params['binsize'] = 2*ms <NEW_LINE> <DEDENT> self.spiketrains = model.produce_spiketrains(**self.params) <NEW_LINE> covariances = self.generate_covariances(self.spiketrains, **self.params) <NEW_LINE> self.set_prediction(model, covariances) <NEW_LINE> <DEDENT> return covariances <NEW_LINE> <DEDENT> def validate_observation(self, observation): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def generate_covariances(self, spiketrain_list=None, binary=False, ** kwargs): <NEW_LINE> <INDENT> def robust_BinnedSpikeTrain(spiketrains, binsize=None, num_bins=None, t_start=None, t_stop=None, **add_args): <NEW_LINE> <INDENT> return BinnedSpikeTrain(spiketrains, binsize=binsize, num_bins=num_bins, t_start=t_start, t_stop=t_stop) <NEW_LINE> <DEDENT> if spiketrain_list is None: <NEW_LINE> <INDENT> binned_sts = robust_BinnedSpikeTrain(self.spiketrains, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> binned_sts = robust_BinnedSpikeTrain(spiketrain_list, **kwargs) <NEW_LINE> <DEDENT> cov_matrix = covariance(binned_sts, binary=binary) <NEW_LINE> idx = triu_indices(len(cov_matrix), 1) <NEW_LINE> return cov_matrix[idx] | Test to compare the pairwise covariances of a set of neurons in a network.
The statistical testing method needs to be set in form of a
sciunit.Score as score_type.
Parameters (in dict params):
----------
binsize: quantity, None (default: 2*ms)
Size of bins used to calculate the correlation coefficients.
num_bins: int, None (default: None)
Number of bins within t_start and t_stop used to calculate
the correlation coefficients.
t_start: quantity, None
Start of time window used to calculate the correlation coefficients.
t_stop: quantity, None
Stop of time window used to calculate the correlation coefficients.
binary: bool
If true, the binned spike trains are set to be binary. | 62598f9e4f6381625f1993ad |
class RandomUserAgentMiddleware(UserAgentMiddleware): <NEW_LINE> <INDENT> def process_request(self, request, spider): <NEW_LINE> <INDENT> ua = random.choice(USER_AGENT_LIST) <NEW_LINE> request.headers.setdefault("User-Agent", ua) | 方法说明
随机指定一个user agent | 62598f9e8e7ae83300ee8e83 |
class InvalidTagException(Exception): <NEW_LINE> <INDENT> pass | * Raised if tag that isn't defined is found.
@exception .InvalidTagException | 62598f9ecb5e8a47e493c066 |
class PropertyExists(ResourceConflict): <NEW_LINE> <INDENT> pass | Raised when a property already exists. | 62598f9e090684286d5935cc |
class Sum(Stage): <NEW_LINE> <INDENT> def __init__(self, name, inputNames, numComponents, outputDim, defaultValue=0.0): <NEW_LINE> <INDENT> Stage.__init__( self, name=name, inputNames=inputNames, outputDim=outputDim, defaultValue=defaultValue) <NEW_LINE> self.numComponents = numComponents <NEW_LINE> <DEDENT> def forward(self, X): <NEW_LINE> <INDENT> return np.sum( X.reshape(X.shape[0], self.numComponents, X.shape[1] / self.numComponents), axis=1) <NEW_LINE> <DEDENT> def backward(self, dEdY): <NEW_LINE> <INDENT> self.dEdW = 0.0 <NEW_LINE> return np.tile(dEdY, self.numComponents) | Stage summing first half of the input with second half. | 62598f9edd821e528d6d8d19 |
class Melon(object): <NEW_LINE> <INDENT> def __init__(self, melon_type, shape_rating, color_rating, harvested_from_field, harvested_by): <NEW_LINE> <INDENT> self.melon_type = melon_type <NEW_LINE> self.shape_rating = shape_rating <NEW_LINE> self.color_rating = color_rating <NEW_LINE> self.harvested_from_field = harvested_from_field <NEW_LINE> self.harvested_by = harvested_by <NEW_LINE> <DEDENT> def is_sellable(self): <NEW_LINE> <INDENT> is_sellable = False <NEW_LINE> if self.shape_rating > 5 and self.color_rating > 5 and self.harvested_from_field != 3: <NEW_LINE> <INDENT> is_sellable = True <NEW_LINE> <DEDENT> return is_sellable | A melon in a melon harvest. | 62598f9ed7e4931a7ef3be7d |
class Course(object): <NEW_LINE> <INDENT> name = "" <NEW_LINE> def getAssignmentsForCredit(self,credit): <NEW_LINE> <INDENT> assignments = [] <NEW_LINE> for a in self.assignments.keys(): <NEW_LINE> <INDENT> if self.assignments[a]==credit: <NEW_LINE> <INDENT> assignments.append(a) <NEW_LINE> <DEDENT> elif self.assignments[a]=="%d" % credit: <NEW_LINE> <INDENT> assignments.append(a) <NEW_LINE> <DEDENT> <DEDENT> return assignments <NEW_LINE> <DEDENT> def getScoresForCredit(self,credit): <NEW_LINE> <INDENT> scores = {} <NEW_LINE> creditAssignments = self.getAssignmentsForCredit(credit) <NEW_LINE> for s in self.students: <NEW_LINE> <INDENT> scores[s.lastName+","+s.firstName] = 0 <NEW_LINE> studentAssignments = s.getAssignmentsForCredit("%d"%credit) <NEW_LINE> studentAssignmentPoints = 0 <NEW_LINE> studentNotesPoints = 0 <NEW_LINE> studentProjectPoints = 0 <NEW_LINE> assignmentPoints=0 <NEW_LINE> notesPoints=0 <NEW_LINE> projectPoints=0 <NEW_LINE> for a in studentAssignments: <NEW_LINE> <INDENT> if "Notes" in a.number: <NEW_LINE> <INDENT> studentNotesPoints+=int(a.score) <NEW_LINE> <DEDENT> elif "Project" in a.number: <NEW_LINE> <INDENT> studentProjectPoints+=int(a.score) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> studentAssignmentPoints+=int(a.score) <NEW_LINE> <DEDENT> <DEDENT> for a in creditAssignments: <NEW_LINE> <INDENT> if "Notes" in a: <NEW_LINE> <INDENT> notesPoints+=100 <NEW_LINE> <DEDENT> elif "Project" in a: <NEW_LINE> <INDENT> projectPoints+=100 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assignmentPoints+=100 <NEW_LINE> <DEDENT> <DEDENT> if assignmentPoints>0: <NEW_LINE> <INDENT> if notesPoints>0: <NEW_LINE> <INDENT> if projectPoints==0: <NEW_LINE> <INDENT> assignmentPercentage = studentAssignmentPoints/assignmentPoints*.7 <NEW_LINE> notesPercentage = studentNotesPoints/notesPoints*.3 <NEW_LINE> scores[s.lastName+","+s.firstName]=assignmentPercentage+notesPercentage <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assignmentPercentage = studentAssignmentPoints/assignmentPoints*.4 <NEW_LINE> notesPercentage = studentNotesPoints/notesPoints*.3 <NEW_LINE> projectPercentage = studentProjectPoints/projectPoints*.3 <NEW_LINE> scores[s.lastName+","+s.firstName]=assignmentPercentage+notesPercentage+projectPercentage <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if projectPoints==0: <NEW_LINE> <INDENT> scores[s.lastName+","+s.firstName]=studentAssignmentPoints/assignmentPoints <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assignmentPercentage = studentAssignmentPoints/assignmentPoints*.7 <NEW_LINE> projectPercentage = studentProjectPoints/projectPoints*.3 <NEW_LINE> scores[s.lastName+","+s.firstName]=assignmentPercentage+projectPercentage <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> scores[s.lastName+","+s.firstName]=-1 <NEW_LINE> <DEDENT> <DEDENT> return scores <NEW_LINE> <DEDENT> def __init__(self, name): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.assignments = {} <NEW_LINE> self.students = [] <NEW_LINE> self.notesWeight = .3 <NEW_LINE> self.projectWeight = .3 | classdocs | 62598f9e1f5feb6acb162a06 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.