code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class Dipole(BaseRx): <NEW_LINE> <INDENT> def __init__(self, locsM, locsN, times, rxType='phi', **kwargs): <NEW_LINE> <INDENT> assert locsM.shape == locsN.shape, ( 'locsM and locsN need to be the same size' ) <NEW_LINE> locs = [np.atleast_2d(locsM), np.atleast_2d(locsN)] <NEW_LINE> BaseRx.__init__(self, locs, times, rxType) <NEW_LINE> <DEDENT> @property <NEW_LINE> def nD(self): <NEW_LINE> <INDENT> return self.locs[0].shape[0] <NEW_LINE> <DEDENT> @property <NEW_LINE> def nRx(self): <NEW_LINE> <INDENT> return self.locs[0].shape[0] <NEW_LINE> <DEDENT> def getP(self, mesh, Gloc): <NEW_LINE> <INDENT> if mesh in self._Ps: <NEW_LINE> <INDENT> return self._Ps[mesh] <NEW_LINE> <DEDENT> P0 = mesh.getInterpolationMat(self.locs[0], Gloc) <NEW_LINE> P1 = mesh.getInterpolationMat(self.locs[1], Gloc) <NEW_LINE> P = P0 - P1 <NEW_LINE> if self.data_type == 'apparent_resistivity': <NEW_LINE> <INDENT> P = sdiag(1./self.geometric_factor) * P <NEW_LINE> <DEDENT> elif self.data_type == 'apparent_chargeability': <NEW_LINE> <INDENT> P = sdiag(1./self.dc_voltage) * P <NEW_LINE> <DEDENT> if self.storeProjections: <NEW_LINE> <INDENT> self._Ps[mesh] = P <NEW_LINE> <DEDENT> return P
Dipole receiver
6259905e4e4d562566373a76
class FixMariadbHealthCheck(Migrate.Step): <NEW_LINE> <INDENT> version = Migrate.Version(5,2,0) <NEW_LINE> def cutover(self, dmd): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ctx = sm.ServiceContext() <NEW_LINE> <DEDENT> except sm.ServiceMigrationError: <NEW_LINE> <INDENT> log.info("Couldn't generate service context, skipping.") <NEW_LINE> return <NEW_LINE> <DEDENT> mariadb_model = filter(lambda s: s.name == "mariadb-model", ctx.services) <NEW_LINE> mariadb_events = filter(lambda s: s.name == "mariadb-events", ctx.services) <NEW_LINE> mariadb_core = filter(lambda s: s.name == "mariadb", ctx.services) <NEW_LINE> for service in mariadb_model: <NEW_LINE> <INDENT> healthChecks = filter(lambda hc: hc.name == "answering", service.healthChecks) <NEW_LINE> for check in healthChecks: <NEW_LINE> <INDENT> if "mysql --protocol TCP -uroot -hlocalhost -P3306 -e 'select 1' > /dev/null" in check.script: <NEW_LINE> <INDENT> check.script = "mysql --protocol TCP -u{{(getContext . \"global.conf.zodb-admin-user\")}} -h{{(getContext . \"global.conf.zodb-host\")}} -P{{(getContext . \"global.conf.zodb-port\")}} -p{{getContext . \"global.conf.zodb-admin-password\"}} -e 'select 1' > /dev/null" <NEW_LINE> log.info("Updated 'answering' healthcheck for mariadb-model") <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> for service in mariadb_events: <NEW_LINE> <INDENT> healthChecks = filter(lambda hc: hc.name == "answering", service.healthChecks) <NEW_LINE> for check in healthChecks: <NEW_LINE> <INDENT> if "mysql --protocol TCP -uroot -hlocalhost -P3306 -e 'select 1' > /dev/null" in check.script: <NEW_LINE> <INDENT> check.script = "mysql --protocol TCP -u{{(getContext . \"global.conf.zep-admin-user\")}} -h{{(getContext . \"global.conf.zep-host\")}} -P{{(getContext . \"global.conf.zep-port\")}} -p{{getContext . \"global.conf.zep-admin-password\"}} -e 'select 1' > /dev/null" <NEW_LINE> log.info("Updated 'answering' healthcheck for mariadb-events") <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> for service in mariadb_core: <NEW_LINE> <INDENT> healthChecks = filter(lambda hc: hc.name == "answering", service.healthChecks) <NEW_LINE> for check in healthChecks: <NEW_LINE> <INDENT> if "mysql --protocol TCP -uroot -hlocalhost -P3306 -e 'select 1' > /dev/null" in check.script: <NEW_LINE> <INDENT> check.script = "mysql --protocol TCP -u{{(getContext . \"global.conf.zep-admin-user\")}} -h{{(getContext . \"global.conf.zep-host\")}} -P{{(getContext . \"global.conf.zep-port\")}} -p{{getContext . \"global.conf.zep-admin-password\"}} -e 'select 1' > /dev/null" <NEW_LINE> log.info("Updated 'answering' healthcheck for mariadb") <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> ctx.commit()
Use different curl request to prevent `authentication failed` spam in audit.log
6259905e8e7ae83300eea6fd
class prop_logicTest(unittest.TestCase): <NEW_LINE> <INDENT> P = Expr('P') <NEW_LINE> def test_pl_true_P_true(self): <NEW_LINE> <INDENT> self.assertEqual(pl_true(self.P, {self.P: True}), True) <NEW_LINE> <DEDENT> def test_pl_true_P_false(self): <NEW_LINE> <INDENT> self.assertEqual(pl_true(self.P, {self.P: False}), False)
Testing basic propositional logic functionality
6259905e15baa72349463602
class Parameters(object): <NEW_LINE> <INDENT> def __init__(self, parameters_etree=None, defaults=None): <NEW_LINE> <INDENT> if defaults is not None: <NEW_LINE> <INDENT> self._defaults = defaults <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._defaults = { 'Energy': 300, 'EnergyModel': 'energy_model.default_energy_model.DefaultEnergyModel', 'Iterations': 10000, 'Time': 1000, 'RadiationRate': 0.0, 'EnergyInput': 0.0, 'Reactions': 'chemistry_model.emergent_reactions.EmergentReactions', 'ProductSelectionStrategy': 'energy', 'Molecule': 'kinetic_molecule.KineticMolecule', 'Vessel': 'reactor_model.spatial_reaction_vessel.SpatialReactionVessel', 'DipoleForceConstant': 0.01, 'repeats': 1, 'DeltaT': 1.0, 'IterationBlocksize': 50, 'recover': True, 'seed': None, 'StateRecordRate': 10.0, } <NEW_LINE> <DEDENT> if parameters_etree is None: <NEW_LINE> <INDENT> self._parameters = ElementTree.fromstring("<dummy></dummy>") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._parameters = parameters_etree <NEW_LINE> <DEDENT> <DEDENT> def get(self, parameter, default=True): <NEW_LINE> <INDENT> result = self._parameters.find(parameter) <NEW_LINE> if result is None: <NEW_LINE> <INDENT> if default and parameter in self._defaults.keys(): <NEW_LINE> <INDENT> return self._defaults[parameter] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> if len(result) == 0: <NEW_LINE> <INDENT> return Parameters.convert_if_boolean(result.text.rstrip()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return result <NEW_LINE> <DEDENT> <DEDENT> def get_attrib(self, attrib, default=True): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> result = self._parameters.get(attrib).rstrip() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> if default and attrib in self._defaults.keys(): <NEW_LINE> <INDENT> result = self._defaults[attrib] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> return Parameters.convert_if_boolean(result) <NEW_LINE> <DEDENT> def get_filename(self, filename): <NEW_LINE> <INDENT> path = self._parameters.find(filename).text.rstrip() <NEW_LINE> if not os.path.isabs(path): <NEW_LINE> <INDENT> path = os.path.join(config.DataDir, path) <NEW_LINE> <DEDENT> return os.path.normpath(path) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def convert_if_boolean(cls, text): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> l = text.lower() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return text <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if l == 'true': <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif l == 'false': <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return text <NEW_LINE> <DEDENT> <DEDENT> def to_xml(self): <NEW_LINE> <INDENT> return ElementTree.tostring(self._parameters)
Simple wrapper to provide a smarter method to get experiment parameters than the raw XML API.
6259905eac7a0e7691f73b53
class PriceViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = Price.objects.all() <NEW_LINE> serializer_class = PriceSerializer <NEW_LINE> filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter] <NEW_LINE> filterset_fields = ['user__username', 'code', 'label'] <NEW_LINE> search_fields = ["id", "user__username", "code", "label", "created_at", "update_at"] <NEW_LINE> ordering_fields = ['user__username', 'created_at', 'update_at'] <NEW_LINE> permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsUserOrReadOnly,] <NEW_LINE> def perform_create(self, serializer): <NEW_LINE> <INDENT> serializer.save(user=self.request.user) <NEW_LINE> <DEDENT> def perform_destroy(self, instance): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> instance.delete() <NEW_LINE> <DEDENT> except ProtectedError as err: <NEW_LINE> <INDENT> raise APIException( code=502, detail="Protected error: {0}".format(err) )
Ce viewset fournit automatiquement les actions `list`, `create`, `retrieve`, `update` et `destroy` pour les prix
6259905e6e29344779b01cbe
class AbstractItem(QtWidgets.QGraphicsItemGroup): <NEW_LINE> <INDENT> def __init__(self, rect: QtCore.QRectF, parent=None): <NEW_LINE> <INDENT> QtWidgets.QGraphicsItemGroup.__init__(self, parent=parent) <NEW_LINE> self.shape = None <NEW_LINE> self.penwidth = None <NEW_LINE> self.prepShape(rect) <NEW_LINE> <DEDENT> def prepShape(self, rect): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def changeRect(self, rect): <NEW_LINE> <INDENT> if self.shape is not None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.shape.prepareGeometryChange() <NEW_LINE> self.shape.setRect(rect) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def adjustRect(self, dx, dy): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> rect: QtCore.QRectF = self.shape.rect() <NEW_LINE> rect.adjust(-dx, -dy, dx, dy) <NEW_LINE> self.shape.prepareGeometryChange() <NEW_LINE> self.shape.setRect(rect) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def getRealRect(self): <NEW_LINE> <INDENT> res = None <NEW_LINE> try: <NEW_LINE> <INDENT> res = self.shape.rect() <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return res <NEW_LINE> <DEDENT> def changePen(self, pen=None, width=None, color=None): <NEW_LINE> <INDENT> def _parse(elements, pen=None, width=None, color=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> for el in elements: <NEW_LINE> <INDENT> if isinstance(el, QtWidgets.QGraphicsItemGroup): <NEW_LINE> <INDENT> _parse(el.childItems(), pen=pen, width=width, color=color) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if not isinstance(pen, QtGui.QPen): <NEW_LINE> <INDENT> pen = el.pen() <NEW_LINE> <DEDENT> if isinstance(width, int): <NEW_LINE> <INDENT> pen.setWidth(width) <NEW_LINE> <DEDENT> if isinstance(color, QtGui.QColor): <NEW_LINE> <INDENT> pen.setColor(color) <NEW_LINE> <DEDENT> el.prepareGeometryChange() <NEW_LINE> el.setPen(pen) <NEW_LINE> <DEDENT> <DEDENT> self.penwidth = pen.width() <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> _parse(self.childItems(), pen=pen, width=width, color=color)
Item in the shape of an ellipse
6259905e99cbb53fe6832551
class SasDefinitionCreateParameters(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'parameters': {'required': True}, } <NEW_LINE> _attribute_map = { 'parameters': {'key': 'parameters', 'type': '{str}'}, 'sas_definition_attributes': {'key': 'attributes', 'type': 'SasDefinitionAttributes'}, 'tags': {'key': 'tags', 'type': '{str}'}, } <NEW_LINE> def __init__( self, *, parameters: Dict[str, str], sas_definition_attributes: Optional["SasDefinitionAttributes"] = None, tags: Optional[Dict[str, str]] = None, **kwargs ): <NEW_LINE> <INDENT> super(SasDefinitionCreateParameters, self).__init__(**kwargs) <NEW_LINE> self.parameters = parameters <NEW_LINE> self.sas_definition_attributes = sas_definition_attributes <NEW_LINE> self.tags = tags
The SAS definition create parameters. All required parameters must be populated in order to send to Azure. :ivar parameters: Required. Sas definition creation metadata in the form of key-value pairs. :vartype parameters: dict[str, str] :ivar sas_definition_attributes: The attributes of the SAS definition. :vartype sas_definition_attributes: ~azure.keyvault.v2016_10_01.models.SasDefinitionAttributes :ivar tags: A set of tags. Application specific metadata in the form of key-value pairs. :vartype tags: dict[str, str]
6259905e91af0d3eaad3b498
class ResouceSearch(MyUnitTestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.login_manage() <NEW_LINE> self.url = "http://10.16.3.26:8067/edu/resources" <NEW_LINE> self.center_url='http://10.16.3.26:8067/edu/user-center/home' <NEW_LINE> self.search_key_word="sss" <NEW_LINE> <DEDENT> def test_page_title(self): <NEW_LINE> <INDENT> resource_page = ResourcePage(self.driver, self.url, u"资源列表") <NEW_LINE> resource_page.open() <NEW_LINE> resource_page.on_page(u"资源列表") <NEW_LINE> <DEDENT> def test_search_string(self): <NEW_LINE> <INDENT> resource_page = ResourcePage(self.driver, self.url, u"资源列表") <NEW_LINE> resource_page.open() <NEW_LINE> resource_page.input_search_comment(self.search_key_word) <NEW_LINE> resource_page.click_submit() <NEW_LINE> resource_page.click_link_text_xiti()
教育网页-资源中心页面测试
6259905e379a373c97d9a695
class MabContainerExtendedInfo(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'last_refreshed_at': {'key': 'lastRefreshedAt', 'type': 'iso-8601'}, 'backup_item_type': {'key': 'backupItemType', 'type': 'str'}, 'backup_items': {'key': 'backupItems', 'type': '[str]'}, 'policy_name': {'key': 'policyName', 'type': 'str'}, 'last_backup_status': {'key': 'lastBackupStatus', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, last_refreshed_at: Optional[datetime.datetime] = None, backup_item_type: Optional[Union[str, "BackupItemType"]] = None, backup_items: Optional[List[str]] = None, policy_name: Optional[str] = None, last_backup_status: Optional[str] = None, **kwargs ): <NEW_LINE> <INDENT> super(MabContainerExtendedInfo, self).__init__(**kwargs) <NEW_LINE> self.last_refreshed_at = last_refreshed_at <NEW_LINE> self.backup_item_type = backup_item_type <NEW_LINE> self.backup_items = backup_items <NEW_LINE> self.policy_name = policy_name <NEW_LINE> self.last_backup_status = last_backup_status
Additional information of the container. :ivar last_refreshed_at: Time stamp when this container was refreshed. :vartype last_refreshed_at: ~datetime.datetime :ivar backup_item_type: Type of backup items associated with this container. Possible values include: "Invalid", "VM", "FileFolder", "AzureSqlDb", "SQLDB", "Exchange", "Sharepoint", "VMwareVM", "SystemState", "Client", "GenericDataSource", "SQLDataBase", "AzureFileShare", "SAPHanaDatabase", "SAPAseDatabase". :vartype backup_item_type: str or ~azure.mgmt.recoveryservicesbackup.activestamp.models.BackupItemType :ivar backup_items: List of backup items associated with this container. :vartype backup_items: list[str] :ivar policy_name: Backup policy associated with this container. :vartype policy_name: str :ivar last_backup_status: Latest backup status of this container. :vartype last_backup_status: str
6259905e7047854f46340a2d
class WeakBoundMethod(object): <NEW_LINE> <INDENT> def __init__(self, bound_method, ignore_emptiness=False): <NEW_LINE> <INDENT> self._free_method = bound_method.im_func <NEW_LINE> self._weak_instance = weakref.ref(bound_method.im_self) <NEW_LINE> self._ignore_emptiness = ignore_emptiness <NEW_LINE> <DEDENT> def __call__(self, *args, **kwargs): <NEW_LINE> <INDENT> instance = self._weak_instance() <NEW_LINE> if instance is None: <NEW_LINE> <INDENT> if self._ignore_emptiness: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> raise ReferenceError <NEW_LINE> <DEDENT> return self._free_method(instance, *args, **kwargs) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<%s wrapping %s and %s>" % (self.__class__, repr(self._weak_instance()), repr(self._free_method))
Used to create a proxy method of a bound method, which weakly references the method's binding instance. Assuming the following simple class: >>> class Example(object): ... def print_num(self, a_number): ... print "%d" % a_number We can create an example instance and create a weak reference to the bound print_num method: >>> e = Example() >>> wmeth = WeakBoundMethod(e.print_num) The proxy method works as expected: >>> wmeth(5) 5 It holds no strong reference to e, so deleting e will invalidate the proxy method: >>> del e >>> wmeth(5) Traceback (most recent call last): ... ReferenceError The exception can be suppressed by setting ignore_emptiness to True: >>> e = Example() >>> wmeth = WeakBoundMethod(e.print_num, ignore_emptiness=True) >>> wmeth(5) 5 >>> del e >>> wmeth(5)
6259905e498bea3a75a59136
class BaseFileModifier(object): <NEW_LINE> <INDENT> field = '' <NEW_LINE> implements(ISurfResourceModifier) <NEW_LINE> def __init__(self, context): <NEW_LINE> <INDENT> self.context = context <NEW_LINE> <DEDENT> def run(self, resource, *args, **kwds): <NEW_LINE> <INDENT> item = getattr(self.context, self.field) <NEW_LINE> if not item: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> setattr(resource, "dcterms_format", [item.contentType])
Adds dcterms:format
6259905e8e7ae83300eea6fe
class InstrumentedRequestHandler(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.calls = [] <NEW_LINE> self.finished_reading = False <NEW_LINE> <DEDENT> def no_body_received(self): <NEW_LINE> <INDENT> self.calls.append(('no_body_received',)) <NEW_LINE> <DEDENT> def end_received(self): <NEW_LINE> <INDENT> self.calls.append(('end_received',)) <NEW_LINE> self.finished_reading = True <NEW_LINE> <DEDENT> def args_received(self, args): <NEW_LINE> <INDENT> self.calls.append(('args_received', args)) <NEW_LINE> <DEDENT> def accept_body(self, bytes): <NEW_LINE> <INDENT> self.calls.append(('accept_body', bytes)) <NEW_LINE> <DEDENT> def end_of_body(self): <NEW_LINE> <INDENT> self.calls.append(('end_of_body',)) <NEW_LINE> self.finished_reading = True <NEW_LINE> <DEDENT> def post_body_error_received(self, error_args): <NEW_LINE> <INDENT> self.calls.append(('post_body_error_received', error_args))
Test Double of SmartServerRequestHandler.
6259905e4f6381625f199fdb
class SigningKeyResponse(object): <NEW_LINE> <INDENT> openapi_types = { 'data': 'SigningKey' } <NEW_LINE> attribute_map = { 'data': 'data' } <NEW_LINE> def __init__(self, data=None, local_vars_configuration=None): <NEW_LINE> <INDENT> if local_vars_configuration is None: <NEW_LINE> <INDENT> local_vars_configuration = Configuration.get_default_copy() <NEW_LINE> <DEDENT> self.local_vars_configuration = local_vars_configuration <NEW_LINE> self._data = None <NEW_LINE> self.discriminator = None <NEW_LINE> if data is not None: <NEW_LINE> <INDENT> self.data = data <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def data(self): <NEW_LINE> <INDENT> return self._data <NEW_LINE> <DEDENT> @data.setter <NEW_LINE> def data(self, data): <NEW_LINE> <INDENT> self._data = data <NEW_LINE> <DEDENT> def to_dict(self, serialize=False): <NEW_LINE> <INDENT> result = {} <NEW_LINE> def convert(x): <NEW_LINE> <INDENT> if hasattr(x, "to_dict"): <NEW_LINE> <INDENT> args = inspect.getargspec(x.to_dict).args <NEW_LINE> if len(args) == 1: <NEW_LINE> <INDENT> return x.to_dict() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return x.to_dict(serialize) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return x <NEW_LINE> <DEDENT> <DEDENT> for attr, _ in six.iteritems(self.openapi_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> attr = self.attribute_map.get(attr, attr) if serialize else attr <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: convert(x), value )) <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], convert(item[1])), value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = convert(value) <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, SigningKeyResponse): <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, SigningKeyResponse): <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.
6259905e460517430c432b8b
class OracleParam(object): <NEW_LINE> <INDENT> def __init__(self, param, cursor, strings_only=False): <NEW_LINE> <INDENT> if settings.USE_TZ and (isinstance(param, datetime.datetime) and not isinstance(param, Oracle_datetime)): <NEW_LINE> <INDENT> if timezone.is_aware(param): <NEW_LINE> <INDENT> warnings.warn( "The Oracle database adapter received an aware datetime (%s), " "probably from cursor.execute(). Update your code to pass a " "naive datetime in the database connection's time zone (UTC by " "default).", RemovedInDjango21Warning) <NEW_LINE> param = param.astimezone(timezone.utc).replace(tzinfo=None) <NEW_LINE> <DEDENT> param = Oracle_datetime.from_datetime(param) <NEW_LINE> <DEDENT> if isinstance(param, datetime.timedelta): <NEW_LINE> <INDENT> param = duration_string(param) <NEW_LINE> if ' ' not in param: <NEW_LINE> <INDENT> param = '0 ' + param <NEW_LINE> <DEDENT> <DEDENT> string_size = 0 <NEW_LINE> if param is True: <NEW_LINE> <INDENT> param = 1 <NEW_LINE> <DEDENT> elif param is False: <NEW_LINE> <INDENT> param = 0 <NEW_LINE> <DEDENT> if hasattr(param, 'bind_parameter'): <NEW_LINE> <INDENT> self.force_bytes = param.bind_parameter(cursor) <NEW_LINE> <DEDENT> elif isinstance(param, Database.Binary): <NEW_LINE> <INDENT> self.force_bytes = param <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.force_bytes = convert_unicode(param, cursor.charset, strings_only) <NEW_LINE> if isinstance(self.force_bytes, six.string_types): <NEW_LINE> <INDENT> string_size = len(force_bytes(param, cursor.charset, strings_only)) <NEW_LINE> <DEDENT> <DEDENT> if hasattr(param, 'input_size'): <NEW_LINE> <INDENT> self.input_size = param.input_size <NEW_LINE> <DEDENT> elif string_size > 4000: <NEW_LINE> <INDENT> self.input_size = Database.CLOB <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.input_size = None
Wrapper object for formatting parameters for Oracle. If the string representation of the value is large enough (greater than 4000 characters) the input size needs to be set as CLOB. Alternatively, if the parameter has an `input_size` attribute, then the value of the `input_size` attribute will be used instead. Otherwise, no input size will be set for the parameter when executing the query.
6259905e8da39b475be04858
class Club(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.name = '' <NEW_LINE> self.money = '' <NEW_LINE> self.league = ''
club
6259905ed6c5a102081e3794
class Mathopd(HTTPProcess): <NEW_LINE> <INDENT> protocol = 'HTTP' <NEW_LINE> subprotocol = 'HEADER' <NEW_LINE> re_expr = re.compile("^mathopd/?(?P<version>[\dp\.]+)?", re.IGNORECASE) <NEW_LINE> def process(self, data, metadata): <NEW_LINE> <INDENT> server = self.get_header_field(data, 'server') <NEW_LINE> if server: <NEW_LINE> <INDENT> match_obj = self.re_expr.search(server) <NEW_LINE> if match_obj: <NEW_LINE> <INDENT> metadata.service.product = 'Mathopd' <NEW_LINE> metadata.service.version = match_obj.group('version') <NEW_LINE> <DEDENT> <DEDENT> return metadata
http://www.mathopd.org/
6259905ee64d504609df9f07
class TestDefaultController(BaseTestCase): <NEW_LINE> <INDENT> def test_add_student(self): <NEW_LINE> <INDENT> body = Student(first_name=str(uuid.uuid4()), last_name='beratna', grades={"subject_example": 8}) <NEW_LINE> response = self.client.open( '/service-api/student', method='POST', data=json.dumps(body), content_type='application/json') <NEW_LINE> data = response.data.decode('utf-8') <NEW_LINE> self.assert200(response, 'Response body is : ' + data) <NEW_LINE> TestDefaultController.student_id = data <NEW_LINE> <DEDENT> def test_get_student_by_id(self): <NEW_LINE> <INDENT> query_string = [('subject', 'subject_example')] <NEW_LINE> response = self.client.open( '/service-api/student/{student_id}'.format(student_id=TestDefaultController.student_id), method='GET', query_string=query_string) <NEW_LINE> self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) <NEW_LINE> <DEDENT> def test_hdelete_student(self): <NEW_LINE> <INDENT> url ='/service-api/student/{student_id}'.format(student_id=TestDefaultController.student_id) <NEW_LINE> response = self.client.open( url, method='DELETE') <NEW_LINE> self.assert200(response, 'Response body is : ' + response.data.decode('utf-8'))
DefaultController integration test stubs
6259905e67a9b606de5475da
class TokenSchema(Schema): <NEW_LINE> <INDENT> email = fields.String( required=True, load_from='sub', validate=must_not_be_blank, error_messages={ 'invalid': 'atributo no válido.', 'required': 'Atributo obligatorio.' } ) <NEW_LINE> exp = fields.Integer( required=False, load_only=True, validate=must_not_be_blank, error_messages={ 'invalid': 'Atributo no válido debe ser de tipo entero.' } ) <NEW_LINE> type = fields.String( required=False, load_only=True, validate=must_not_be_blank, error_messages={ 'invalid': 'Atributo no válido.' } ) <NEW_LINE> password = fields.String( required=True, load_only=True, validate=must_not_be_blank, error_messages={ 'invalid': 'No es un string válido.', 'required': 'Atributo obligatorio.' } )
Estructura del Token del tipo Schema.
6259905e99cbb53fe6832552
class TagDetailView(SearchableViewMixin, DetailView): <NEW_LINE> <INDENT> model = Tag <NEW_LINE> paginate_by = 10 <NEW_LINE> paginate_orphans = 2 <NEW_LINE> template_name = "bdr/tags/detail.html"
This view displays the datasets, files and revisions associated with a given tag.
6259905efff4ab517ebcee97
class PaginationError(LastfmAPIError): <NEW_LINE> <INDENT> def __init__(self, msg): <NEW_LINE> <INDENT> self.msg = msg <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return repr(self.msg)
Exception class for issues with paginated requests.
6259905ea8370b77170f1a3f
@deconstructible <NEW_LINE> class FencedCodeExtension(Extension): <NEW_LINE> <INDENT> def extendMarkdown(self, md, md_globals): <NEW_LINE> <INDENT> md.registerExtension(self) <NEW_LINE> md.preprocessors.add('fenced_code_block', FencedBlockPreprocessor(md), ">normalize_whitespace")
Adds fenced code blocks E.g.: ```python class FencedCodeExtension(Extension): pass ```
6259905ebaa26c4b54d50912
class AttentionVRPCritic(object): <NEW_LINE> <INDENT> def __init__(self, dim, use_tanh=False, C=10,_name='Attention',_scope=''): <NEW_LINE> <INDENT> self.use_tanh = use_tanh <NEW_LINE> self._scope = _scope <NEW_LINE> with tf.variable_scope(_scope+_name): <NEW_LINE> <INDENT> self.v = tf.get_variable('v',[1,dim], initializer=tf.contrib.layers.xavier_initializer()) <NEW_LINE> self.v = tf.expand_dims(self.v,2) <NEW_LINE> <DEDENT> self.emb_d = tf.layers.Conv1D(dim,1,_scope=_scope+_name +'/emb_d') <NEW_LINE> self.project_d = tf.layers.Conv1D(dim,1,_scope=_scope+_name +'/proj_d') <NEW_LINE> self.project_query = tf.layers.Dense(dim,_scope=_scope+_name +'/proj_q') <NEW_LINE> self.project_ref = tf.layers.Conv1D(dim,1,_scope=_scope+_name +'/proj_e') <NEW_LINE> self.C = C <NEW_LINE> self.tanh = tf.nn.tanh <NEW_LINE> <DEDENT> def __call__(self, query, ref, env): <NEW_LINE> <INDENT> demand = env.input_data[:,:,-1] <NEW_LINE> max_time = tf.shape(demand)[1] <NEW_LINE> emb_d = self.emb_d(tf.expand_dims(demand,2)) <NEW_LINE> d = self.project_d(emb_d) <NEW_LINE> e = self.project_ref(ref) <NEW_LINE> q = self.project_query(query) <NEW_LINE> expanded_q = tf.tile(tf.expand_dims(q,1),[1,max_time,1]) <NEW_LINE> v_view = tf.tile( self.v, [tf.shape(e)[0],1,1]) <NEW_LINE> u = tf.squeeze(tf.matmul(self.tanh(expanded_q + e + d), v_view),2) <NEW_LINE> if self.use_tanh: <NEW_LINE> <INDENT> logits = self.C * self.tanh(u) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logits = u <NEW_LINE> <DEDENT> return e, logits
A generic attention module for the attention in vrp model
6259905e379a373c97d9a696
class Ner(): <NEW_LINE> <INDENT> def __init__(self, config): <NEW_LINE> <INDENT> self.config = config <NEW_LINE> self.home = self.config.get('General', 'home') <NEW_LINE> <DEDENT> def process(self, files): <NEW_LINE> <INDENT> print('process: NER') <NEW_LINE> logging.info('started NER: '+str(datetime.now())) <NEW_LINE> self.pre_process_ner(files) <NEW_LINE> self.StanfordNER(files) <NEW_LINE> logging.info('ended NER: '+str(datetime.now())) <NEW_LINE> <DEDENT> def pre_process_ner(self, files): <NEW_LINE> <INDENT> outdir = self.config.get('NER','pre_proc_out_dir') <NEW_LINE> indir = self.config.get('UDPipe','out_dir') <NEW_LINE> for f in files: <NEW_LINE> <INDENT> infile = self.home + '/' + indir + '/' + f <NEW_LINE> sentences = self.extract_sentences(infile) <NEW_LINE> outfilename = self.home + '/' + outdir + '/' + f <NEW_LINE> with open(outfilename, 'w') as outfile: <NEW_LINE> <INDENT> for sent in sentences: <NEW_LINE> <INDENT> for tok in sent: <NEW_LINE> <INDENT> outfile.write(tok+'\n') <NEW_LINE> <DEDENT> outfile.write('\n') <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def extract_sentences(self, filename): <NEW_LINE> <INDENT> with open(filename,'r') as f: <NEW_LINE> <INDENT> tokens = [] <NEW_LINE> skip_toks = [] <NEW_LINE> sentences = [] <NEW_LINE> with open(filename, 'r') as f: <NEW_LINE> <INDENT> for line in f: <NEW_LINE> <INDENT> if line[0] != '#': <NEW_LINE> <INDENT> if line == '\n': <NEW_LINE> <INDENT> if tokens != []: <NEW_LINE> <INDENT> sentences.append(tokens) <NEW_LINE> <DEDENT> tokens = [] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> elements = line.split('\t') <NEW_LINE> if '-' not in elements[0]: <NEW_LINE> <INDENT> tokens.append(elements[1]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return sentences <NEW_LINE> <DEDENT> <DEDENT> def StanfordNER(self, files): <NEW_LINE> <INDENT> ner_host = self.config.get('StanfordNER','host_name') <NEW_LINE> indir = self.config.get('NER','pre_proc_out_dir') <NEW_LINE> outdir = self.config.get('NER','out_dir') <NEW_LINE> st = sner.Ner(host=ner_host,port=9199) <NEW_LINE> for f in files: <NEW_LINE> <INDENT> fpath = self.home + '/' + indir + '/' + f <NEW_LINE> raw_sentences = [] <NEW_LINE> tagged_sentences = [] <NEW_LINE> with open(fpath, 'r') as infile: <NEW_LINE> <INDENT> tokens = [] <NEW_LINE> for line in infile: <NEW_LINE> <INDENT> if line == '\n': <NEW_LINE> <INDENT> raw_sentences.append(tokens) <NEW_LINE> tokens = [] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tokens.append(line.rstrip('\n')) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> for sent in raw_sentences: <NEW_LINE> <INDENT> s = ' '.join(sent) <NEW_LINE> tagged_sent = st.tag(s.decode('utf8')) <NEW_LINE> tagged_sentences.append(tagged_sent) <NEW_LINE> <DEDENT> outfilename = self.home + '/' + outdir + '/' + f <NEW_LINE> with codecs.open(outfilename, 'w', 'utf-8') as outfile: <NEW_LINE> <INDENT> for sent in tagged_sentences: <NEW_LINE> <INDENT> for tok in sent: <NEW_LINE> <INDENT> outfile.write(tok[0].lstrip('\n')+'\t'+tok[1]+'\n') <NEW_LINE> <DEDENT> outfile.write('\n')
Perform named entity recognition using Stanford NER Input: (word) tokenised sentences Output: named entity tagged sentences
6259905e1f037a2d8b9e53a4
class IntellectMoneyForm(_BasePaymentForm): <NEW_LINE> <INDENT> PREFERENCE_CHOICES = [ ('inner', 'IntellectMoney'), ('bankCard', 'Visa/MasterCard'), ('exchangers', u'Internet Exchangers'), ('terminals', u'Terminals'), ('transfers', u'Transfers'), ('sms', 'SMS'), ('bank', u'Bank'), ('yandex', u'Яндекс.Деньги'), ('inner,bankCard,exchangers,terminals,bank,transfers,sms', u'All'), ('bankCard,exchangers,terminals,bank,transfers,sms', u'All without inner'), ] <NEW_LINE> successUrl = forms.CharField( required=False, max_length=512, initial=settings.INTELLECTMONEY_SUCCESS_URL ) <NEW_LINE> failUrl = forms.CharField( required=False, max_length=512, initial=settings.INTELLECTMONEY_FAIL_URL ) <NEW_LINE> preference = forms.ChoiceField( label=u'Payment Method', choices=PREFERENCE_CHOICES, required=False ) <NEW_LINE> expireDate = forms.DateTimeField(required=False) <NEW_LINE> holdMode = forms.BooleanField(required=False) <NEW_LINE> hash = forms.CharField(required=False) <NEW_LINE> user_email = forms.EmailField(required=False) <NEW_LINE> def get_redirect_url(self): <NEW_LINE> <INDENT> def _initial(name, field): <NEW_LINE> <INDENT> val = self.initial.get(name, field.initial) <NEW_LINE> if not val: <NEW_LINE> <INDENT> return val <NEW_LINE> <DEDENT> return unicode(val).encode('1251') <NEW_LINE> <DEDENT> fields = [(name, _initial(name, field)) for name, field in self.fields.items() if _initial(name, field) ] <NEW_LINE> hash_field = getHashOnRequest(dict(fields)) <NEW_LINE> fields.append(('hash', hash_field)) <NEW_LINE> params = urlencode(fields) <NEW_LINE> return '{0:s}?{1:s}'.format(settings.INTELLECTMONEY_CLIENT_REDIRECT_URL,params)
Payment request form.
6259905e1f5feb6acb16425c
class Info(object): <NEW_LINE> <INDENT> results = dict() <NEW_LINE> def __init__(self, app, machine=False): <NEW_LINE> <INDENT> self.app = app <NEW_LINE> self.machine = machine <NEW_LINE> self._fetch_information() <NEW_LINE> <DEDENT> def _fetch_information(self): <NEW_LINE> <INDENT> self._get_bootloader_info() <NEW_LINE> self._get_layout() <NEW_LINE> <DEDENT> def _get_bootloader_info(self): <NEW_LINE> <INDENT> b = BootConfiguration() <NEW_LINE> bootinfo = dict() <NEW_LINE> bootinfo["default"] = b.get_default() <NEW_LINE> bootinfo["entries"] = dict() <NEW_LINE> for k, v in b.list().items(): <NEW_LINE> <INDENT> for entry in v: <NEW_LINE> <INDENT> bootinfo["entries"][entry.title] = entry.__dict__ <NEW_LINE> <DEDENT> <DEDENT> self.results["bootloader"] = bootinfo <NEW_LINE> <DEDENT> def _get_layout(self): <NEW_LINE> <INDENT> layout = LayoutParser(self.app.imgbase.layout()).parse() <NEW_LINE> self.results["layers"] = layout <NEW_LINE> self.results["current_layer"] = str(self.app.imgbase.current_layer()) <NEW_LINE> <DEDENT> def write(self): <NEW_LINE> <INDENT> def pretty_print(k, indent=0): <NEW_LINE> <INDENT> sys.stdout.write('{0}{1}: '.format(' ' * indent, k[0])) <NEW_LINE> if isinstance(k[1], string_types): <NEW_LINE> <INDENT> sys.stdout.write('{0}\n'.format(k[1])) <NEW_LINE> <DEDENT> elif isinstance(k[1], dict): <NEW_LINE> <INDENT> sys.stdout.write('\n') <NEW_LINE> items = list(k[1].items()) <NEW_LINE> if k[0] == "entries": <NEW_LINE> <INDENT> items.sort(key=lambda x: x[1]["index"]) <NEW_LINE> <DEDENT> for item in items: <NEW_LINE> <INDENT> pretty_print(item, indent+2) <NEW_LINE> <DEDENT> <DEDENT> elif isinstance(k[1], list): <NEW_LINE> <INDENT> sys.stdout.write('\n') <NEW_LINE> for item in k[1]: <NEW_LINE> <INDENT> print('{0}{1}'.format(' ' * (indent + 2), item)) <NEW_LINE> <DEDENT> <DEDENT> sys.stdout.flush() <NEW_LINE> <DEDENT> if self.machine: <NEW_LINE> <INDENT> print(json.dumps(self.results)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for k in self.results.items(): <NEW_LINE> <INDENT> pretty_print(k)
Fetches and displays some information about the running node: Bootloader information Layout information
6259905e97e22403b383c57f
class ConfigurationIdentity(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'principal_id': {'readonly': True}, 'tenant_id': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'principal_id': {'key': 'principalId', 'type': 'str'}, 'tenant_id': {'key': 'tenantId', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, type: Optional[Union[str, "ResourceIdentityType"]] = None, **kwargs ): <NEW_LINE> <INDENT> super(ConfigurationIdentity, self).__init__(**kwargs) <NEW_LINE> self.principal_id = None <NEW_LINE> self.tenant_id = None <NEW_LINE> self.type = type
Identity for the managed cluster. Variables are only populated by the server, and will be ignored when sending a request. :ivar principal_id: The principal id of the system assigned identity which is used by the configuration. :vartype principal_id: str :ivar tenant_id: The tenant id of the system assigned identity which is used by the configuration. :vartype tenant_id: str :param type: The type of identity used for the configuration. Type 'SystemAssigned' will use an implicitly created identity. Type 'None' will not use Managed Identity for the configuration. Possible values include: "SystemAssigned", "None". :type type: str or ~azure.mgmt.kubernetesconfiguration.v2020_07_01_preview.models.ResourceIdentityType
6259905f097d151d1a2c26e1
class GaussianWeightedDistanceCalculator(DistanceCalculator): <NEW_LINE> <INDENT> def __init__(self, centre=30, variance=20): <NEW_LINE> <INDENT> self.centre = centre <NEW_LINE> self.variance = variance <NEW_LINE> <DEDENT> def calculate_distance(self, sequence1, sequence2): <NEW_LINE> <INDENT> self._check_same_length(sequence1, sequence2) <NEW_LINE> distance = 0 <NEW_LINE> for i in xrange(len(sequence1)): <NEW_LINE> <INDENT> delta = 0 <NEW_LINE> if sequence1[i] == sequence2[i]: <NEW_LINE> <INDENT> delta = 1 <NEW_LINE> <DEDENT> distance += self._weight(i) * (1 - delta) <NEW_LINE> <DEDENT> return distance <NEW_LINE> <DEDENT> def _weight(self, index): <NEW_LINE> <INDENT> return math.exp( -math.pow(index - self.centre, 2) / self.variance)
Gives more weight to nucleotides around the boundary.
6259905f21bff66bcd7242d8
class PyRATTask(QgsTask): <NEW_LINE> <INDENT> def __init__(self, pyratTool, para_backup): <NEW_LINE> <INDENT> QgsTask.__init__(self) <NEW_LINE> self.pyratTool = pyratTool <NEW_LINE> self.para_backup = para_backup <NEW_LINE> self.failed = False <NEW_LINE> self.guionly = False <NEW_LINE> self.layer = None <NEW_LINE> self.existinglayers = list() <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> self.plugin = self.pyratTool() <NEW_LINE> self.plugin.crash_handler = self.crashHandler <NEW_LINE> self.existinglayers = pyrat.data.getLayerIDs() <NEW_LINE> self.layer = self.plugin.run() <NEW_LINE> setattr(self.pyratTool, 'para', self.para_backup) <NEW_LINE> return self.layer is not False <NEW_LINE> <DEDENT> def crashHandler(self, ex): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> raise ex <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> self.guionly = True <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> self.failed = True <NEW_LINE> raise ex <NEW_LINE> <DEDENT> <DEDENT> def finished(self, result): <NEW_LINE> <INDENT> if self.guionly: <NEW_LINE> <INDENT> self.pyratTool.guirun(iface.mainWindow()) <NEW_LINE> <DEDENT> if result and not self.failed: <NEW_LINE> <INDENT> iface.messageBar().pushMessage(self.pyratTool.name + " finished.", level=Qgis.Success) <NEW_LINE> for layer in [newlayer for newlayer in pyrat.data.getLayerIDs() if newlayer not in self.existinglayers]: <NEW_LINE> <INDENT> anno = pyrat.data.getAnnotation(layer=layer) <NEW_LINE> if 'info' not in anno: <NEW_LINE> <INDENT> anno['info'] = "Pyrat-Layer " + layer <NEW_LINE> <DEDENT> pyrat.data.setAnnotation({'info': anno['info'] + "-" + self.pyratTool.name}, layer=layer) <NEW_LINE> ViewerToQGISInterface.display[layer] = {'scaling': 'min->max', 'bwlayer': layer, 'colour': False} <NEW_LINE> PyRATBridge.pyratToLayer(self.layer) <NEW_LINE> <DEDENT> PyRATBridge.layerTreeWidget.redraw() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iface.messageBar().pushMessage(self.pyratTool.name + " failed. Look in the (system)" + " console for more information.", level=Qgis.Critical) <NEW_LINE> <DEDENT> del self.plugin
This class handles the async execution of a PyRAT-Tool
6259905fd6c5a102081e3796
class PandasModel(QtCore.QAbstractTableModel): <NEW_LINE> <INDENT> def __init__(self, data, parent=None, editable=False, editable_min_idx=-1): <NEW_LINE> <INDENT> QtCore.QAbstractTableModel.__init__(self, parent) <NEW_LINE> self.data = np.array(data.values) <NEW_LINE> self._cols = data.columns <NEW_LINE> self.index = data.index.values <NEW_LINE> self.editable = editable <NEW_LINE> self.editable_min_idx = editable_min_idx <NEW_LINE> self.r, self.c = np.shape(self.data) <NEW_LINE> self.isDate = False <NEW_LINE> if self.r > 0 and self.c > 0: <NEW_LINE> <INDENT> if isinstance(self.index[0], np.datetime64): <NEW_LINE> <INDENT> self.index = pd.to_datetime(self.index) <NEW_LINE> self.isDate = True <NEW_LINE> <DEDENT> <DEDENT> self.formatter = lambda x: "%.2f" % x <NEW_LINE> <DEDENT> def flags(self, index): <NEW_LINE> <INDENT> if self.editable and index.column() > self.editable_min_idx: <NEW_LINE> <INDENT> return QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return QtCore.Qt.ItemIsEnabled <NEW_LINE> <DEDENT> <DEDENT> def rowCount(self, parent=None): <NEW_LINE> <INDENT> return self.r <NEW_LINE> <DEDENT> def columnCount(self, parent=None): <NEW_LINE> <INDENT> return self.c <NEW_LINE> <DEDENT> def data(self, index, role=QtCore.Qt.DisplayRole): <NEW_LINE> <INDENT> if index.isValid(): <NEW_LINE> <INDENT> if role == QtCore.Qt.DisplayRole: <NEW_LINE> <INDENT> return str(self.data[index.row(), index.column()]) <NEW_LINE> <DEDENT> <DEDENT> return None <NEW_LINE> <DEDENT> def setData(self, index, value, role=QtCore.Qt.DisplayRole): <NEW_LINE> <INDENT> self.data[index.row(), index.column()] = value <NEW_LINE> <DEDENT> def headerData(self, p_int, orientation, role): <NEW_LINE> <INDENT> if role == QtCore.Qt.DisplayRole: <NEW_LINE> <INDENT> if orientation == QtCore.Qt.Horizontal: <NEW_LINE> <INDENT> return self._cols[p_int] <NEW_LINE> <DEDENT> elif orientation == QtCore.Qt.Vertical: <NEW_LINE> <INDENT> if self.index is None: <NEW_LINE> <INDENT> return p_int <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self.isDate: <NEW_LINE> <INDENT> return self.index[p_int].strftime('%Y/%m/%d %H:%M.%S') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return str(self.index[p_int]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return None <NEW_LINE> <DEDENT> def copy_to_column(self, row, col): <NEW_LINE> <INDENT> self.data[:, col] = self.data[row, col]
Class to populate a Qt table view with a pandas data frame
6259905f4e4d562566373a7a
class SortOptions(object): <NEW_LINE> <INDENT> def __init__(self, expressions=None, match_scorer=None, limit=1000): <NEW_LINE> <INDENT> self._match_scorer = match_scorer <NEW_LINE> self._expressions = _GetList(expressions) <NEW_LINE> for expression in self._expressions: <NEW_LINE> <INDENT> if not isinstance(expression, SortExpression): <NEW_LINE> <INDENT> raise TypeError('expression must be a SortExpression, got %s' % expression.__class__.__name__) <NEW_LINE> <DEDENT> <DEDENT> self._limit = _CheckSortLimit(limit) <NEW_LINE> <DEDENT> @property <NEW_LINE> def expressions(self): <NEW_LINE> <INDENT> return self._expressions <NEW_LINE> <DEDENT> @property <NEW_LINE> def match_scorer(self): <NEW_LINE> <INDENT> return self._match_scorer <NEW_LINE> <DEDENT> @property <NEW_LINE> def limit(self): <NEW_LINE> <INDENT> return self._limit <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return _Repr( self, [('match_scorer', self.match_scorer), ('expressions', self.expressions), ('limit', self.limit)])
Represents a mulit-dimensional sort of Documents. The following code shows how to sort documents based on product rating in descending order and then cheapest product within similarly rated products, sorting at most 1000 documents: SortOptions(expressions=[ SortExpression(expression='rating', direction=SortExpression.DESCENDING, default_value=0), SortExpression(expression='price + tax', direction=SortExpression.ASCENDING, default_value=999999.99)], limit=1000)
6259905f38b623060ffaa389
class PublicIPAddressSku(Model): <NEW_LINE> <INDENT> _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, } <NEW_LINE> def __init__(self, name=None): <NEW_LINE> <INDENT> self.name = name
SKU of a public IP address. :param name: Name of a public IP address SKU. Possible values include: 'Basic', 'Standard' :type name: str or ~azure.mgmt.network.v2017_09_01.models.PublicIPAddressSkuName
6259905f15baa72349463606
class WL13335(tests.MySQLConnectorTests): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.config = tests.get_mysql_config() <NEW_LINE> cnx = connection.MySQLConnection(**self.config) <NEW_LINE> self.user = "expired_pw_user" <NEW_LINE> self.passw = "i+QEqGkFr8h5" <NEW_LINE> self.hosts = ["localhost", "127.0.0.1"] <NEW_LINE> for host in self.hosts: <NEW_LINE> <INDENT> cnx.cmd_query("CREATE USER '{}'@'{}' IDENTIFIED BY " "'{}'".format(self.user, host, self.passw)) <NEW_LINE> cnx.cmd_query("GRANT ALL ON *.* TO '{}'@'{}'" "".format(self.user, host)) <NEW_LINE> cnx.cmd_query("ALTER USER '{}'@'{}' PASSWORD EXPIRE" "".format(self.user, host)) <NEW_LINE> <DEDENT> cnx.close() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> cnx = connection.MySQLConnection(**self.config) <NEW_LINE> for host in self.hosts: <NEW_LINE> <INDENT> cnx.cmd_query("DROP USER '{}'@'{}'".format(self.user, host)) <NEW_LINE> <DEDENT> cnx.close() <NEW_LINE> <DEDENT> @tests.foreach_cnx() <NEW_LINE> def test_connect_with_can_handle_expired_pw_flag(self): <NEW_LINE> <INDENT> cnx_config = self.config.copy() <NEW_LINE> cnx_config['user'] = self.user <NEW_LINE> cnx_config['password'] = self.passw <NEW_LINE> flags = constants.ClientFlag.get_default() <NEW_LINE> flags |= constants.ClientFlag.CAN_HANDLE_EXPIRED_PASSWORDS <NEW_LINE> cnx_config['client_flags'] =flags <NEW_LINE> _ = self.cnx.__class__(**cnx_config)
WL#13335: Avoid set config values with flag CAN_HANDLE_EXPIRED_PASSWORDS
6259905f442bda511e95d893
class GenericData(object): <NEW_LINE> <INDENT> def __init__(self, label='', data=None, uncertainty=None, species=None, reaction=None, units=None, index=None): <NEW_LINE> <INDENT> self.label = str(label) if label else None <NEW_LINE> if isinstance(data, list): <NEW_LINE> <INDENT> self.data = np.array(data) <NEW_LINE> <DEDENT> elif isinstance(data, np.ndarray): <NEW_LINE> <INDENT> self.data = data <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception('Data for GenericData object must be initialized as a list or numpy.array of values.') <NEW_LINE> <DEDENT> self.uncertainty = uncertainty <NEW_LINE> self.species = species <NEW_LINE> self.reaction = reaction <NEW_LINE> self.units = str(units) if units else None <NEW_LINE> self.index = int(index) if index else None
A generic data class for the purpose of plotting. ======================= ============================================================================================ Attribute Description ======================= ============================================================================================ `label` A string label describing the data, can be used in a plot legend or in an axis label `data` A numpy array of the data `uncertainty` An uncertainty value associated with the data. Either a scalar or a numpy array with same length as `data` `species` Contains species associated with the data, often used with a Species object `reaction` Contains reaction associated with the data, often used with a Reaction object `units` Contains a string describing the units associated with the data `index` An integer containing the index associated with the data ======================= ============================================================================================
6259905f3539df3088ecd90f
class EulerMaruyama(OverDampedLangevinIntegrator): <NEW_LINE> <INDENT> def __init__(self,model, stepsize, inverse_temperature): <NEW_LINE> <INDENT> if model.p is not None: <NEW_LINE> <INDENT> raise ValueError('EulerMaruyama is only first Order Dynamics!') <NEW_LINE> <DEDENT> super(EulerMaruyama, self).__init__(model, stepsize, inverse_temperature) <NEW_LINE> self._zeta = np.sqrt(2. * self._stepsize / self._inverse_temperature) <NEW_LINE> <DEDENT> def integrate(self): <NEW_LINE> <INDENT> self._model.q += self._stepsize * self._model.f + self._zeta * np.random.normal(0., 1., self._model._dim) <NEW_LINE> self._model.apply_boundary_conditions() <NEW_LINE> self._model.update_force()
Class which implements the Euler-Maruyama method which is a first order dynamics integrator
6259905f009cb60464d02baa
class StatEntry(structs.RDFProtoStruct): <NEW_LINE> <INDENT> protobuf = jobs_pb2.StatEntry
Represent an extended stat response.
6259905fcb5e8a47e493ccbf
class ProjectModel(db.Model): <NEW_LINE> <INDENT> __tablename__ = 'projects' <NEW_LINE> pid = db.Column(db.Integer, primary_key=True) <NEW_LINE> pname = db.Column(db.String()) <NEW_LINE> owner_id = db.Column(db.Integer, db.ForeignKey('users.id')) <NEW_LINE> description = db.Column(db.String()) <NEW_LINE> owner = db.relationship('UserModel', back_populates='owned_projects') <NEW_LINE> members = db.relationship('UserJoinedProjectAssociation', back_populates='project') <NEW_LINE> roles = db.relationship('ProjectRoleAssociation', back_populates='project') <NEW_LINE> def __init__(self, pname, description, owner_id, roles=[]): <NEW_LINE> <INDENT> self.pname = pname <NEW_LINE> self.description = description <NEW_LINE> self.owner_id = owner_id <NEW_LINE> self.roleList = [] <NEW_LINE> for role in roles: <NEW_LINE> <INDENT> role = eval(role) <NEW_LINE> r = RoleModel(role['title'], role['description'], role['skills']) <NEW_LINE> self.roleList += [r] <NEW_LINE> <DEDENT> <DEDENT> def json(self): <NEW_LINE> <INDENT> return { 'pid': self.pid, 'pname': self.pname, 'description': self.description, 'owner_id': self.owner_id, } <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def find_by_name(cls, pname, owner_id): <NEW_LINE> <INDENT> return cls.query.filter_by(pname=pname, owner_id=owner_id).first() <NEW_LINE> <DEDENT> def save_to_db(self): <NEW_LINE> <INDENT> for role in self.roleList: <NEW_LINE> <INDENT> a = ProjectRoleAssociation() <NEW_LINE> a.role = role <NEW_LINE> self.roles.append(a) <NEW_LINE> <DEDENT> db.session.add(self) <NEW_LINE> db.session.commit() <NEW_LINE> <DEDENT> def delete_from_db(self): <NEW_LINE> <INDENT> db.session.delete(self) <NEW_LINE> db.session.commit()
docstring for ProjectModel
6259905f435de62698e9d479
class DownloadBceGLONASS(DownloadBCE): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> DownloadBCE.__init__(self, 'g')
download GPS broadcast ephemeris from CDDIS FTP
6259905f23e79379d538db6f
class CapitalDatabase(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> file_path = os.path.dirname(__file__) <NEW_LINE> if file_path != "": <NEW_LINE> <INDENT> os.chdir(file_path) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.Towers = self.loadDict("gameconfig/towers.csv") <NEW_LINE> self.Radios = self.loadDict("gameconfig/radios.csv") <NEW_LINE> self.Wired = self.loadDict("gameconfig/wired.csv") <NEW_LINE> self.Routers = self.loadDict("gameconfig/routers.csv") <NEW_LINE> self.Buildings = self.loadDict("gameconfig/buildings.csv") <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> print("Failed to initialize capital database.") <NEW_LINE> quit() <NEW_LINE> <DEDENT> <DEDENT> def loadDict(self,filename): <NEW_LINE> <INDENT> inFile = open(filename,'r') <NEW_LINE> returnDict = { } <NEW_LINE> id = 0 <NEW_LINE> for line in inFile: <NEW_LINE> <INDENT> line = line.rstrip() <NEW_LINE> fields = line.split(",") <NEW_LINE> if '#' in fields[0]: continue <NEW_LINE> tempList = [] <NEW_LINE> for field in fields: <NEW_LINE> <INDENT> tempList.append(field) <NEW_LINE> <DEDENT> returnDict[id] = tempList <NEW_LINE> id = id + 1 <NEW_LINE> <DEDENT> return returnDict <NEW_LINE> <DEDENT> def GetTower(self,id): <NEW_LINE> <INDENT> return Tower(self.Towers[id]) <NEW_LINE> <DEDENT> def GetRadio(self,id): <NEW_LINE> <INDENT> return Radio(self.Radios[id]) <NEW_LINE> <DEDENT> def GetWired(self,id): <NEW_LINE> <INDENT> return Wired(self.Wired[id]) <NEW_LINE> <DEDENT> def GetRouter(self,id): <NEW_LINE> <INDENT> return Router(self.Routers[id]) <NEW_LINE> <DEDENT> def GetBuilding(self,id): <NEW_LINE> <INDENT> return Building(self.Buildings[id])
Tests: >>> Data = CapitalDatabase() >>> a = Data.GetTower(0) >>> a.name 'Titan T200' >>> not Data.Towers == None True >>> not Data.Radios == None True
6259905ffff4ab517ebcee99
class QParamInspector(QtGui.QWidget): <NEW_LINE> <INDENT> def __init__(self, v1Name='', v2Name='', parent=None, f=QtCore.Qt.WindowFlags()): <NEW_LINE> <INDENT> QtGui.QWidget.__init__(self, parent, f | QtCore.Qt.Tool) <NEW_LINE> self.setWindowTitle('Parameter Inspector - None') <NEW_LINE> self.firstTime = True <NEW_LINE> self.boxLayout = QtGui.QVBoxLayout() <NEW_LINE> self.boxLayout.setMargin(0) <NEW_LINE> self.boxLayout.setSpacing(0) <NEW_LINE> self.tabWidget = QtGui.QTabWidget() <NEW_LINE> self.tabWidget.setTabPosition(QtGui.QTabWidget.North) <NEW_LINE> self.tabWidget.setTabShape(QtGui.QTabWidget.Triangular) <NEW_LINE> self.functionsTab = QParamTable(v1Name, v2Name) <NEW_LINE> self.tabWidget.addTab(self.functionsTab, 'Functions') <NEW_LINE> self.boxLayout.addWidget(self.tabWidget) <NEW_LINE> sizeGrip = QtGui.QSizeGrip(self) <NEW_LINE> self.boxLayout.addWidget(sizeGrip) <NEW_LINE> self.boxLayout.setAlignment(sizeGrip, QtCore.Qt.AlignRight) <NEW_LINE> self.setLayout(self.boxLayout) <NEW_LINE> <DEDENT> def closeEvent(self, e): <NEW_LINE> <INDENT> e.ignore() <NEW_LINE> self.parent().showInspectorAction.setChecked(False)
QParamInspector is a widget acting as an inspector vistrail modules in diff mode. It consists of a function inspector and annotation inspector
6259905f45492302aabfdb4d
class OrderAdminTest(AdminTestMixin, TestCase): <NEW_LINE> <INDENT> fixtures = ['dump.json'] <NEW_LINE> model = Order <NEW_LINE> object_id = 1
Tests for Order admin.
6259905fac7a0e7691f73b57
class Activity(EmbeddedDocument): <NEW_LINE> <INDENT> activity_uid = fields.StringField() <NEW_LINE> content = fields.StringField() <NEW_LINE> author = fields.StringField() <NEW_LINE> created_at = fields.DateTimeField()
Activity model with following attribute activity_uid = String content = String author = String created_at = DateTime
6259905f32920d7e50bc76bb
class _ZList: <NEW_LINE> <INDENT> def _zlistCirc(self, time): <NEW_LINE> <INDENT> self._zlist = numpy.empty(len(time)) <NEW_LINE> self._zlist[:] = numpy.NAN <NEW_LINE> w = 2.0 * numpy.pi / self["per"] <NEW_LINE> alpha = (90.0 - self["i"]) / 180.0 * numpy.pi <NEW_LINE> phase = time / self["per"] <NEW_LINE> phase -= numpy.floor(phase) <NEW_LINE> self._intrans = numpy.where( numpy.logical_or(phase > 0.75, phase < 0.25))[0] <NEW_LINE> self._zlist[self._intrans] = self["a"] * numpy.sqrt(numpy.sin(w * time[self._intrans])**2 + numpy.sin(alpha)**2 * numpy.cos(w * time[self._intrans])**2) <NEW_LINE> <DEDENT> def _zlistKep(self, time): <NEW_LINE> <INDENT> self._ke.a = self["a"] <NEW_LINE> self._ke.e = self["e"] <NEW_LINE> self._ke.i = self["i"] <NEW_LINE> self._ke.Omega = self["Omega"] <NEW_LINE> self._ke.per = self["per"] <NEW_LINE> self._ke.tau = self["tau"] <NEW_LINE> self._ke.w = self["w"] <NEW_LINE> self._zlist = numpy.empty(len(time)) <NEW_LINE> self._zlist[:] = numpy.NAN <NEW_LINE> pos = self._ke.xyzPos(time) <NEW_LINE> z = numpy.sqrt(pos[::, 0]**2 + pos[::, 1]**2) <NEW_LINE> if self._collisionCheck: <NEW_LINE> <INDENT> r = numpy.sqrt(pos[::, 0]**2 + pos[::, 1]**2 + pos[::, 2]**2) <NEW_LINE> indi = numpy.where(r < 1. + self["p"])[0] <NEW_LINE> if len(indi) > 0: <NEW_LINE> <INDENT> raise(PE.PyAValError("There is a body collision on this orbit.", where="_ZList")) <NEW_LINE> <DEDENT> <DEDENT> self._intrans = numpy.where(numpy.logical_and( z <= (1. + self["p"]), pos[::, 2] < 0.0))[0] <NEW_LINE> self._zlist[self._intrans] = z[self._intrans] <NEW_LINE> <DEDENT> def __init__(self, orbit, cc=True): <NEW_LINE> <INDENT> if orbit == "circular": <NEW_LINE> <INDENT> self._calcZList = self._zlistCirc <NEW_LINE> <DEDENT> elif orbit == "keplerian": <NEW_LINE> <INDENT> self._collisionCheck = cc <NEW_LINE> self._ke = pyasl.KeplerEllipse(1., 1.) <NEW_LINE> self._calcZList = self._zlistKep
Calculate the projected distance between the centers of star and planet. The resulting values will be stored in the `_zlist` attribute. Additionally, the indices belonging to in-transit points will be saved in the `_intrans` attribute. These can be used as input to calculate the transit light-curve. Parameters ---------- orbit : string Either "circular" or "keplerian".
6259905fd7e4931a7ef3d6be
class ArticleViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = Article.objects.all() <NEW_LINE> queryset = queryset.annotate(total_votes=Count('votes__vote')) <NEW_LINE> queryset = queryset.prefetch_related("author") <NEW_LINE> queryset = queryset.prefetch_related("category") <NEW_LINE> queryset = queryset.prefetch_related('tags') <NEW_LINE> filter_backends = (filters.SearchFilter, filters.OrderingFilter,) <NEW_LINE> search_fields = ('title', 'content', 'description', 'category__title') <NEW_LINE> ordering_fields = ('created', 'modified', 'total_votes') <NEW_LINE> ordering = ('-created') <NEW_LINE> def get_serializer_class(self): <NEW_LINE> <INDENT> if self.action == 'list': <NEW_LINE> <INDENT> return ArticleDetailSerializer <NEW_LINE> <DEDENT> if self.action == 'retrieve': <NEW_LINE> <INDENT> return ArticleDetailSerializer <NEW_LINE> <DEDENT> return ArticleCreateSerializer <NEW_LINE> <DEDENT> def perform_create(self, serializer): <NEW_LINE> <INDENT> serializer.save(author=self.request.user)
API endpoint that allows Articles to be viewed or edited.
6259905f004d5f362081fb29
class Table(Element): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(Table, self).__init__() <NEW_LINE> self.rows = [] <NEW_LINE> <DEDENT> def value(self): <NEW_LINE> <INDENT> return self.rows
Represents table element.
6259905f1f037a2d8b9e53a5
class ClipTimer(wx.Timer): <NEW_LINE> <INDENT> def Notify(self): <NEW_LINE> <INDENT> if wx.TheClipboard.Open(): <NEW_LINE> <INDENT> wx.TheClipboard.Clear() <NEW_LINE> wx.TheClipboard.Close()
Description: Clip Board timer that clears the content copied to clip board
6259905f379a373c97d9a699
class ServiceGuarantee(Document): <NEW_LINE> <INDENT> def __init__(self, automaticPay=False, payAmount=0.0, serviceRequirement='', applicationPeriod=None, *args, **kw_args): <NEW_LINE> <INDENT> self.automaticPay = automaticPay <NEW_LINE> self.payAmount = payAmount <NEW_LINE> self.serviceRequirement = serviceRequirement <NEW_LINE> self.applicationPeriod = applicationPeriod <NEW_LINE> super(ServiceGuarantee, self).__init__(*args, **kw_args) <NEW_LINE> <DEDENT> _attrs = ["automaticPay", "payAmount", "serviceRequirement"] <NEW_LINE> _attr_types = {"automaticPay": bool, "payAmount": float, "serviceRequirement": str} <NEW_LINE> _defaults = {"automaticPay": False, "payAmount": 0.0, "serviceRequirement": ''} <NEW_LINE> _enums = {} <NEW_LINE> _refs = ["applicationPeriod"] <NEW_LINE> _many_refs = [] <NEW_LINE> applicationPeriod = None
A service guarantee, often imposed by a regulator, defines conditions that, if not satisfied, will result in the utility making a monetary payment to the customer. Note that guarantee's identifier is in the 'name' attribute and the status of the guarantee is in the 'Status.status' attribute. Example service requirements include: 1) If power is not restored within 24 hours, customers can claim $50 for residential customers or $100 for commercial and industrial customers. In addition for each extra period of 12 hours the customer's supply has not been activated, the customer can claim $25. 2) If a customer has a question about their electricity bill, the utility will investigate and respond to the inquiry within 15 working days. If utility fails to meet its guarantee, utility will automatically pay the customer $50.A service guarantee, often imposed by a regulator, defines conditions that, if not satisfied, will result in the utility making a monetary payment to the customer. Note that guarantee's identifier is in the 'name' attribute and the status of the guarantee is in the 'Status.status' attribute. Example service requirements include: 1) If power is not restored within 24 hours, customers can claim $50 for residential customers or $100 for commercial and industrial customers. In addition for each extra period of 12 hours the customer's supply has not been activated, the customer can claim $25. 2) If a customer has a question about their electricity bill, the utility will investigate and respond to the inquiry within 15 working days. If utility fails to meet its guarantee, utility will automatically pay the customer $50.
6259905f63d6d428bbee3dc2
class TestBatch(unittest.TestCase): <NEW_LINE> <INDENT> def test_batch(self): <NEW_LINE> <INDENT> self.assertListEqual( list(batch(tuple(range(10)))), [(0, 1, 2), (3, 4, 5), (6, 7, 8), (9,)]) <NEW_LINE> self.assertListEqual( list(batch(tuple(range(10)), 5)), [(0, 1, 2, 3, 4), (5, 6, 7, 8, 9)]) <NEW_LINE> self.assertListEqual( list(batch(tuple(range(10)), 1)), [(0,), (1,), (2,), (3,), (4,), (5,), (6,), (7,), (8,), (9,)])
Defines :func:`colour.utilities.common.batch` definition unit tests methods.
6259905f498bea3a75a59138
class OrderDetail(APIView): <NEW_LINE> <INDENT> def get(self, request, pk): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> snippet = Order.objects.get(pk=pk) <NEW_LINE> <DEDENT> except Order.DoesNotExist: <NEW_LINE> <INDENT> return HttpResponse(status=404) <NEW_LINE> <DEDENT> serializer = OrderSerializer(snippet) <NEW_LINE> return Response(serializer.data)
Retrieve, update or delete a code snippet.
6259905f76e4537e8c3f0c01
class RadioButton(Field): <NEW_LINE> <INDENT> def __init__(self, id, value): <NEW_LINE> <INDENT> super(RadioButton, self).__init__(id, value) <NEW_LINE> <DEDENT> def set_value(self, value, **kw): <NEW_LINE> <INDENT> self.html_selected = value and value.lower() == 'true' and 'checked' or '' <NEW_LINE> self.html_class = 'radio' <NEW_LINE> self.html_name = self.subgroup <NEW_LINE> self.default_tag = 'radiobutton' <NEW_LINE> self.tags = IsIE() and ('nobr', 'radiobutton', 'label', 'content', 'endlabel', 'endnobr',) or ('label', 'radiobutton', 'content-div', 'endlabel',) <NEW_LINE> self.inline = True <NEW_LINE> <DEDENT> def get_content(self, tag): <NEW_LINE> <INDENT> if tag in ('subtitle',) or tag.startswith('title'): <NEW_LINE> <INDENT> return self.get_title() or '&nbsp;' <NEW_LINE> <DEDENT> elif tag.startswith('content'): <NEW_LINE> <INDENT> return self.get_label() or '&nbsp;' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> <DEDENT> def html(self, tag=None): <NEW_LINE> <INDENT> tag_mapping = { 'radiobutton' : 'radiobutton', 'title' : 'title-div', 'content' : None, } <NEW_LINE> return super(RadioButton, self).html(tag_mapping[tag])
Радиокнопка: input type="radio"
6259905fbe8e80087fbc06fa
class CarliniWagnerLoss(nn.Module): <NEW_LINE> <INDENT> def __init__(self, conf=50., reduction="sum"): <NEW_LINE> <INDENT> super(CarliniWagnerLoss, self).__init__() <NEW_LINE> self.conf = conf <NEW_LINE> self.reduction = reduction <NEW_LINE> <DEDENT> def forward(self, input, target): <NEW_LINE> <INDENT> num_classes = input.size(1) <NEW_LINE> label_mask = to_one_hot(target, num_classes=num_classes).float() <NEW_LINE> correct_logit = torch.sum(label_mask * input, dim=1) <NEW_LINE> wrong_logit = torch.max((1. - label_mask) * input, dim=1)[0] <NEW_LINE> loss = -F.relu(correct_logit - wrong_logit + self.conf) <NEW_LINE> if self.reduction == "mean": <NEW_LINE> <INDENT> return torch.mean(loss) <NEW_LINE> <DEDENT> elif self.reduction == "sum": <NEW_LINE> <INDENT> return torch.sum(loss) <NEW_LINE> <DEDENT> elif self.reduction == "none": <NEW_LINE> <INDENT> return loss <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("Reduction type '{:s}' is not supported!".format(self.reduction))
Carlini-Wagner Loss: objective function #6. Paper: https://arxiv.org/pdf/1608.04644.pdf
6259905fd268445f2663a697
class StubMetadata: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.information = [1, 2, 3]
stub metadata class to test serialization of hiding technique metadata
6259905f0fa83653e46f655c
class CompleteMultipartUploadTask(Task): <NEW_LINE> <INDENT> def _main(self, client, bucket, key, upload_id, parts): <NEW_LINE> <INDENT> client.complete_multipart_upload( Bucket=bucket, Key=key, UploadId=upload_id, MultipartUpload={'Parts': parts})
Task to complete a multipart upload
6259905fd53ae8145f919ad7
class ptGameCliPlayerJoinedMsg(ptGameCliMsg): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def getGameCli(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def getType(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def playerID(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def upcastToFinalGameCliMsg(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def upcastToGameMsg(self): <NEW_LINE> <INDENT> pass
Game client message when a player joined message is received
6259905f3d592f4c4edbc551
class Images(models.Model): <NEW_LINE> <INDENT> title = models.CharField(max_length=50) <NEW_LINE> caption = models.CharField(max_length=150,blank=True) <NEW_LINE> image = models.ImageField(upload_to='uploads') <NEW_LINE> content_type = models.ForeignKey(ContentType) <NEW_LINE> object_id = models.PositiveIntegerField() <NEW_LINE> content_object = generic.GenericForeignKey('content_type','object_id') <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.title
Stores images used in all parts of the application. Depends on generic foreign key relations https://docs.djangoproject.com/en/1.3/ref/contrib/contenttypes/#generic-relations
6259905f8e7ae83300eea703
class LikePostHandler(BaseHandler): <NEW_LINE> <INDENT> def get(self, post_id): <NEW_LINE> <INDENT> Post.add_like(int(post_id), self.user.get_id()) <NEW_LINE> self.redirect('/blog')
Responsible for adding a like to a single post.
6259905fa8ecb0332587288d
class Request: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.headers = {} <NEW_LINE> self.method = None <NEW_LINE> self.protocol = None <NEW_LINE> self.resource = None <NEW_LINE> self.path = None <NEW_LINE> self.params = {} <NEW_LINE> self.origin = None <NEW_LINE> <DEDENT> def parse(self, conn): <NEW_LINE> <INDENT> self.headers = {} <NEW_LINE> request_line = conn.readline().decode('utf-8').strip() <NEW_LINE> log(1, "Request-Line: %s" % request_line) <NEW_LINE> if not request_line: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.method, self.resource, self.protocol = request_line.split(" ") <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise StopProcessing(400, "Bad request-line: %s\n" % request_line) <NEW_LINE> <DEDENT> from urllib.parse import urlparse, parse_qs <NEW_LINE> requrl = urlparse(self.resource) <NEW_LINE> self.path = requrl.path <NEW_LINE> self.params.update(parse_qs(requrl.query)) <NEW_LINE> while True: <NEW_LINE> <INDENT> header_line = conn.readline().decode('utf-8').strip() <NEW_LINE> if not header_line: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> log(2, "Header-Line: " + header_line) <NEW_LINE> (headerfield, headervalue) = header_line.split(":", 1) <NEW_LINE> self.headers[headerfield.strip()] = headervalue.strip() <NEW_LINE> <DEDENT> if 'Cookie' in self.headers: <NEW_LINE> <INDENT> log(2, "Cookie ist: %s" % self.headers['Cookie']) <NEW_LINE> self.cookies = Cookie.parse(self.headers['Cookie']) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.cookies = {} <NEW_LINE> <DEDENT> log(1,"Methode %s" % self.method) <NEW_LINE> if self.method == 'POST' or self.method == 'post': <NEW_LINE> <INDENT> postbody = conn.read(int(self.headers['Content-Length'])).decode('utf-8') <NEW_LINE> self.params.update(parse_qs(postbody)) <NEW_LINE> <DEDENT> for key in self.params: <NEW_LINE> <INDENT> if len(self.params[key])==1: <NEW_LINE> <INDENT> self.params[key] = self.params[key][0] <NEW_LINE> <DEDENT> <DEDENT> return self.headers
http request data.
6259905fa17c0f6771d5d6de
class ObservationEncoder(object): <NEW_LINE> <INDENT> def __init__(self, game, enc_type=ObservationEncoderType.CANONICAL): <NEW_LINE> <INDENT> self._game = game.c_game <NEW_LINE> self._encoder = ffi.new("pyhanabi_observation_encoder_t*") <NEW_LINE> lib.NewObservationEncoder(self._encoder, self._game, enc_type) <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> if self._encoder is not None: <NEW_LINE> <INDENT> lib.DeleteObservationEncoder(self._encoder) <NEW_LINE> self._encoder = None <NEW_LINE> self._game = None <NEW_LINE> <DEDENT> del self <NEW_LINE> <DEDENT> def shape(self): <NEW_LINE> <INDENT> c_shape_str = lib.ObservationShape(self._encoder) <NEW_LINE> shape_string = encode_ffi_string(c_shape_str) <NEW_LINE> lib.DeleteString(c_shape_str) <NEW_LINE> shape = [int(x) for x in shape_string.split(",")] <NEW_LINE> return shape <NEW_LINE> <DEDENT> def ownhandshape(self): <NEW_LINE> <INDENT> c_shape_str = lib.OwnHandShape(self._encoder) <NEW_LINE> shape_string = encode_ffi_string(c_shape_str) <NEW_LINE> lib.DeleteString(c_shape_str) <NEW_LINE> shape = [int(x) for x in shape_string.split(",")] <NEW_LINE> return shape <NEW_LINE> <DEDENT> def encode(self, observation): <NEW_LINE> <INDENT> c_encoding_str = lib.EncodeObservation(self._encoder, observation.observation()) <NEW_LINE> encoding_string = encode_ffi_string(c_encoding_str) <NEW_LINE> lib.DeleteString(c_encoding_str) <NEW_LINE> encoding = [int(x) for x in encoding_string.split(",")] <NEW_LINE> return encoding <NEW_LINE> <DEDENT> def encodeownhand(self, observation): <NEW_LINE> <INDENT> c_encoding_str = lib.EncodeOwnHandObservation(self._encoder, observation.observation()) <NEW_LINE> encoding_string = encode_ffi_string(c_encoding_str) <NEW_LINE> lib.DeleteString(c_encoding_str) <NEW_LINE> encoding = [int(x) for x in encoding_string.split(",")] <NEW_LINE> return encoding
ObservationEncoder class. The canonical observations wrap an underlying C++ class. To make custom observation encoders, create a subclass of this base class and override the shape and encode methods.
6259905ffff4ab517ebcee9c
class UnsafeSessionAuthentication(BaseAuthentication): <NEW_LINE> <INDENT> def authenticate(self, request): <NEW_LINE> <INDENT> request = request._request <NEW_LINE> user = getattr(request, 'user', None) <NEW_LINE> if not user or not user.is_active: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return (user, None)
Use Django's session framework for authentication.
6259905fac7a0e7691f73b59
class MeanReducer(LambdaReducer): <NEW_LINE> <INDENT> def __init__(self, name: str, *, value: str = "output", size: str = "size",) -> None: <NEW_LINE> <INDENT> super().__init__(name, lambda x, y: x + y, value=value) <NEW_LINE> self._size = size <NEW_LINE> <DEDENT> @property <NEW_LINE> def _total_size(self) -> str: <NEW_LINE> <INDENT> return f"_{self.name}_reducer_total_size" <NEW_LINE> <DEDENT> def _reset(self, state: dict) -> None: <NEW_LINE> <INDENT> super()._reset(state) <NEW_LINE> state[self._total_size] = 0 <NEW_LINE> <DEDENT> def _update(self, state: dict) -> None: <NEW_LINE> <INDENT> super()._update(state) <NEW_LINE> state[self._total_size] += state.get(self._size, 1) <NEW_LINE> <DEDENT> def _compute(self, state: dict) -> None: <NEW_LINE> <INDENT> super()._compute(state) <NEW_LINE> state[self.name] /= state.pop(self._total_size)
An attachment to compute a mean over batch statistics. This attachment gets the value from each batch and compute their mean at the end of every epoch. Example: >>> from rnnr import Event, Runner >>> from rnnr.attachments import MeanReducer >>> runner = Runner() >>> MeanReducer('mean').attach_on(runner) >>> @runner.on(Event.BATCH) ... def on_batch(state): ... state['output'] = state['batch'] ... >>> runner.run([1, 2, 3]) >>> runner.state['mean'] 2.0 Args: name: Name of this attachment to be used as the key in the runner's state dict to store the mean value. value: Get the value of a batch from ``state[value]``. size: Get the size of a batch from ``state[size]``. If the state has no such key, the size defaults to 1. The sum of all these batch sizes is the divisor when computing the mean.
6259905f4e4d562566373a7d
class TestAutoContentTypeAndAcceptHeaders: <NEW_LINE> <INDENT> def test_GET_no_data_no_auto_headers(self, httpbin): <NEW_LINE> <INDENT> r = http('GET', httpbin.url + '/headers') <NEW_LINE> assert HTTP_OK in r <NEW_LINE> assert r.json['headers']['Accept'] == '*/*' <NEW_LINE> assert 'Content-Type' not in r.json['headers'] <NEW_LINE> <DEDENT> def test_POST_no_data_no_auto_headers(self, httpbin): <NEW_LINE> <INDENT> r = http('POST', httpbin.url + '/post') <NEW_LINE> assert HTTP_OK in r <NEW_LINE> assert '"Accept": "*/*"' in r <NEW_LINE> assert '"Content-Type": "application/json' not in r <NEW_LINE> <DEDENT> def test_POST_with_data_auto_JSON_headers(self, httpbin): <NEW_LINE> <INDENT> r = http('POST', httpbin.url + '/post', 'a=b') <NEW_LINE> assert HTTP_OK in r <NEW_LINE> assert r.json['headers']['Accept'] == JSON_ACCEPT <NEW_LINE> assert r.json['headers']['Content-Type'] == 'application/json' <NEW_LINE> <DEDENT> def test_GET_with_data_auto_JSON_headers(self, httpbin): <NEW_LINE> <INDENT> r = http('POST', httpbin.url + '/post', 'a=b') <NEW_LINE> assert HTTP_OK in r <NEW_LINE> assert r.json['headers']['Accept'] == JSON_ACCEPT <NEW_LINE> assert r.json['headers']['Content-Type'] == 'application/json' <NEW_LINE> <DEDENT> def test_POST_explicit_JSON_auto_JSON_accept(self, httpbin): <NEW_LINE> <INDENT> r = http('--json', 'POST', httpbin.url + '/post') <NEW_LINE> assert HTTP_OK in r <NEW_LINE> assert r.json['headers']['Accept'] == JSON_ACCEPT <NEW_LINE> assert 'application/json' in r.json['headers']['Content-Type'] <NEW_LINE> <DEDENT> def test_GET_explicit_JSON_explicit_headers(self, httpbin): <NEW_LINE> <INDENT> r = http('--json', 'GET', httpbin.url + '/headers', 'Accept:application/xml', 'Content-Type:application/xml') <NEW_LINE> assert HTTP_OK in r <NEW_LINE> assert '"Accept": "application/xml"' in r <NEW_LINE> assert '"Content-Type": "application/xml"' in r <NEW_LINE> <DEDENT> def test_POST_form_auto_Content_Type(self, httpbin): <NEW_LINE> <INDENT> r = http('--form', 'POST', httpbin.url + '/post') <NEW_LINE> assert HTTP_OK in r <NEW_LINE> assert '"Content-Type": "application/x-www-form-urlencoded' in r <NEW_LINE> <DEDENT> def test_POST_form_Content_Type_override(self, httpbin): <NEW_LINE> <INDENT> r = http('--form', 'POST', httpbin.url + '/post', 'Content-Type:application/xml') <NEW_LINE> assert HTTP_OK in r <NEW_LINE> assert '"Content-Type": "application/xml"' in r <NEW_LINE> <DEDENT> def test_print_only_body_when_stdout_redirected_by_default(self, httpbin): <NEW_LINE> <INDENT> env = TestEnvironment(stdin_isatty=True, stdout_isatty=False) <NEW_LINE> r = http('GET', httpbin.url + '/get', env=env) <NEW_LINE> assert 'HTTP/' not in r <NEW_LINE> <DEDENT> def test_print_overridable_when_stdout_redirected(self, httpbin): <NEW_LINE> <INDENT> env = TestEnvironment(stdin_isatty=True, stdout_isatty=False) <NEW_LINE> r = http('--print=h', 'GET', httpbin.url + '/get', env=env) <NEW_LINE> assert HTTP_OK in r
Test that Accept and Content-Type correctly defaults to JSON, but can still be overridden. The same with Content-Type when --form -f is used.
6259905f99cbb53fe6832557
class ServerAndClientSSHTransportBaseCase: <NEW_LINE> <INDENT> def checkDisconnected(self, kind=None): <NEW_LINE> <INDENT> if kind is None: <NEW_LINE> <INDENT> kind = transport.DISCONNECT_PROTOCOL_ERROR <NEW_LINE> <DEDENT> self.assertEqual(self.packets[-1][0], transport.MSG_DISCONNECT) <NEW_LINE> self.assertEqual(self.packets[-1][1][3], chr(kind)) <NEW_LINE> <DEDENT> def connectModifiedProtocol(self, protoModification, kind=None): <NEW_LINE> <INDENT> if kind is None: <NEW_LINE> <INDENT> kind = transport.DISCONNECT_KEY_EXCHANGE_FAILED <NEW_LINE> <DEDENT> proto2 = self.klass() <NEW_LINE> protoModification(proto2) <NEW_LINE> proto2.makeConnection(proto_helpers.StringTransport()) <NEW_LINE> self.proto.dataReceived(proto2.transport.value()) <NEW_LINE> if kind: <NEW_LINE> <INDENT> self.checkDisconnected(kind) <NEW_LINE> <DEDENT> return proto2 <NEW_LINE> <DEDENT> def test_disconnectIfCantMatchKex(self): <NEW_LINE> <INDENT> def blankKeyExchanges(proto2): <NEW_LINE> <INDENT> proto2.supportedKeyExchanges = [] <NEW_LINE> <DEDENT> self.connectModifiedProtocol(blankKeyExchanges) <NEW_LINE> <DEDENT> def test_disconnectIfCantMatchKeyAlg(self): <NEW_LINE> <INDENT> def blankPublicKeys(proto2): <NEW_LINE> <INDENT> proto2.supportedPublicKeys = [] <NEW_LINE> <DEDENT> self.connectModifiedProtocol(blankPublicKeys) <NEW_LINE> <DEDENT> def test_disconnectIfCantMatchCompression(self): <NEW_LINE> <INDENT> def blankCompressions(proto2): <NEW_LINE> <INDENT> proto2.supportedCompressions = [] <NEW_LINE> <DEDENT> self.connectModifiedProtocol(blankCompressions) <NEW_LINE> <DEDENT> def test_disconnectIfCantMatchCipher(self): <NEW_LINE> <INDENT> def blankCiphers(proto2): <NEW_LINE> <INDENT> proto2.supportedCiphers = [] <NEW_LINE> <DEDENT> self.connectModifiedProtocol(blankCiphers) <NEW_LINE> <DEDENT> def test_disconnectIfCantMatchMAC(self): <NEW_LINE> <INDENT> def blankMACs(proto2): <NEW_LINE> <INDENT> proto2.supportedMACs = [] <NEW_LINE> <DEDENT> self.connectModifiedProtocol(blankMACs) <NEW_LINE> <DEDENT> def test_getPeer(self): <NEW_LINE> <INDENT> self.assertEqual(self.proto.getPeer(), address.SSHTransportAddress( self.proto.transport.getPeer())) <NEW_LINE> <DEDENT> def test_getHost(self): <NEW_LINE> <INDENT> self.assertEqual(self.proto.getHost(), address.SSHTransportAddress( self.proto.transport.getHost()))
Tests that need to be run on both the server and the client.
6259905f1b99ca4002290071
class Collisive(PerformanceScenario): <NEW_LINE> <INDENT> def __init__(self, kernel, factors, time_step=0.01, integrator=None, reaction_scheduler=None): <NEW_LINE> <INDENT> super(Collisive, self).__init__(kernel, time_step, integrator, reaction_scheduler) <NEW_LINE> box_length = 7. * factors["box_length"] <NEW_LINE> self.sim.box_size = api.Vec(box_length, box_length, box_length) <NEW_LINE> self.sim.periodic_boundary = [True, True, True] <NEW_LINE> diffusion_coeff = 1. * factors["diff"] <NEW_LINE> self.sim.register_particle_type("A", diffusion_coeff, 0.5) <NEW_LINE> interaction_distance = 1. <NEW_LINE> self.sim.register_potential_harmonic_repulsion("A", "A", 10.) <NEW_LINE> self.system_vars["n_particles"] = int(100 * factors["n_particles"]) <NEW_LINE> self.system_vars["system_size"] = box_length ** 3 / interaction_distance ** 3 <NEW_LINE> self.system_vars["displacement"] = np.sqrt(2. * diffusion_coeff * self.time_step) / interaction_distance <NEW_LINE> self.system_vars["reactivity"] = 0. <NEW_LINE> self.system_vars["density"] = self.system_vars["n_particles"] / self.system_vars["system_size"] <NEW_LINE> for i in range(self.system_vars["n_particles"]): <NEW_LINE> <INDENT> pos = np.random.uniform(size=3) * box_length - 0.5 * box_length <NEW_LINE> self.sim.add_particle("A", api.Vec(*pos)) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def describe(cls): <NEW_LINE> <INDENT> return "Collisive"
Scenario with uniformly distributed particles that repulse each other
6259905f379a373c97d9a69b
class FancyArgumentParser(argparse.ArgumentParser): <NEW_LINE> <INDENT> def __init__(self, **kwargs) -> None: <NEW_LINE> <INDENT> formatter_class = kwargs.pop("formatter_class", WideHelpFormatter) <NEW_LINE> fromfile_prefix_chars = kwargs.pop("fromfile_prefix_chars", "@") <NEW_LINE> super().__init__( formatter_class=formatter_class, fromfile_prefix_chars=fromfile_prefix_chars, **kwargs ) <NEW_LINE> <DEDENT> def convert_arg_line_to_args(self, arg_line: str) -> List[str]: <NEW_LINE> <INDENT> args = shlex.split(arg_line, comments=True) <NEW_LINE> if len(args) > 1: <NEW_LINE> <INDENT> raise ValueError("unrecognizable argument value in line: {}".format(arg_line.strip())) <NEW_LINE> <DEDENT> return args
Fancier version of the argument parser supporting `@file` to fetch additional arguments. Add feature to read command line arguments from files and support: - One argument per line (whitespace is trimmed) - Comments or empty lines (either are ignored) This enables direct use of output from show_downstream_dependents and show_upstream_dependencies. Example: To use this feature, add an argument with "@" and have values ready inside of it, one per line:: cat > tables <<EOF www.users www.user_comments EOF arthur.py load @tables
6259905f7d847024c075da49
class LatexConfig(Configurable): <NEW_LINE> <INDENT> latex_command = Unicode('xelatex', config=True, help='The LaTeX command to use when compiling ".tex" files.') <NEW_LINE> bib_command = Unicode('bibtex', config=True, help='The BibTeX command to use when compiling ".tex" files.') <NEW_LINE> synctex_command = Unicode('synctex', config=True, help='The synctex command to use when syncronizing between .tex and .pdf files.') <NEW_LINE> shell_escape = CaselessStrEnum(['restricted', 'allow', 'disallow'], default_value='restricted', config=True, help='Whether to allow shell escapes '+ '(and by extension, arbitrary code execution). '+ 'Can be "restricted", for restricted shell escapes, '+ '"allow", to allow all shell escapes, or "disallow", '+ 'to disallow all shell escapes') <NEW_LINE> run_times = Integer(default_value=1, config=True, help='How many times to compile the ".tex" files.') <NEW_LINE> cleanup = Bool(default_value=True, config=True, help='Whether to clean up ".out/.aux" files or not.')
A Configurable that declares the configuration options for the LatexHandler.
6259905f3c8af77a43b68a7c
class BaseRecognizer(nn.Module,metaclass=ABCMeta): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(BaseRecognizer,self).__init__() <NEW_LINE> <DEDENT> def init_weights(self, pretrained=None): <NEW_LINE> <INDENT> if pretrained is not None: <NEW_LINE> <INDENT> print_log('load model from: {}'.format(pretrained), logger='root') <NEW_LINE> <DEDENT> <DEDENT> @abstractmethod <NEW_LINE> def extract_feat(self, data): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def postprocess(self,data): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def forward_train(self, data): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def forward_test(self,data): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def init_weights(self, pretrained=None): <NEW_LINE> <INDENT> pass
Base class for text Recognizer
6259905f24f1403a92686409
class MirroredVariable(DistributedVariable, Mirrored): <NEW_LINE> <INDENT> def _update_replica(self, update_fn, value, **kwargs): <NEW_LINE> <INDENT> return _on_write_update_replica(self, update_fn, value, **kwargs) <NEW_LINE> <DEDENT> def scatter_min(self, *args, **kwargs): <NEW_LINE> <INDENT> if values_util.is_saving_non_distributed(): <NEW_LINE> <INDENT> return self._primary.scatter_min(*args, **kwargs) <NEW_LINE> <DEDENT> if (self._aggregation != vs.VariableAggregation.ONLY_FIRST_REPLICA and self._aggregation != vs.VariableAggregation.NONE): <NEW_LINE> <INDENT> raise NotImplementedError(values_util.scatter_error_msg.format( op_name="scatter_min", aggregation=self._aggregation)) <NEW_LINE> <DEDENT> return super(MirroredVariable, self).scatter_min(*args, **kwargs) <NEW_LINE> <DEDENT> def scatter_max(self, *args, **kwargs): <NEW_LINE> <INDENT> if values_util.is_saving_non_distributed(): <NEW_LINE> <INDENT> return self._primary.scatter_max(*args, **kwargs) <NEW_LINE> <DEDENT> if (self._aggregation != vs.VariableAggregation.ONLY_FIRST_REPLICA and self._aggregation != vs.VariableAggregation.NONE): <NEW_LINE> <INDENT> raise NotImplementedError(values_util.scatter_error_msg.format( op_name="scatter_max", aggregation=self._aggregation)) <NEW_LINE> <DEDENT> return super(MirroredVariable, self).scatter_max(*args, **kwargs) <NEW_LINE> <DEDENT> def scatter_update(self, *args, **kwargs): <NEW_LINE> <INDENT> if values_util.is_saving_non_distributed(): <NEW_LINE> <INDENT> return self._primary.scatter_update(*args, **kwargs) <NEW_LINE> <DEDENT> if (self._aggregation != vs.VariableAggregation.ONLY_FIRST_REPLICA and self._aggregation != vs.VariableAggregation.NONE): <NEW_LINE> <INDENT> raise NotImplementedError(values_util.scatter_error_msg.format( op_name="scatter_update", aggregation=self._aggregation)) <NEW_LINE> <DEDENT> return super(MirroredVariable, self).scatter_update(*args, **kwargs) <NEW_LINE> <DEDENT> def _get_cross_replica(self): <NEW_LINE> <INDENT> return array_ops.identity(Mirrored._get_cross_replica(self)) <NEW_LINE> <DEDENT> def _as_graph_element(self): <NEW_LINE> <INDENT> return self._get_on_device_or_primary()._as_graph_element() <NEW_LINE> <DEDENT> def _gather_saveables_for_checkpoint(self): <NEW_LINE> <INDENT> def _saveable_factory(name=self._common_name): <NEW_LINE> <INDENT> return _MirroredSaveable(self, self._primary, name) <NEW_LINE> <DEDENT> return {trackable.VARIABLE_VALUE_KEY: _saveable_factory} <NEW_LINE> <DEDENT> def _write_object_proto(self, proto, options): <NEW_LINE> <INDENT> if options.experimental_variable_policy._expand_distributed_variables( ): <NEW_LINE> <INDENT> for var in self.values: <NEW_LINE> <INDENT> var_proto = ( proto.variable.experimental_distributed_variable_components.add()) <NEW_LINE> var_proto.name = var.name.split(":")[0] <NEW_LINE> var_proto.device = var.device <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _dense_var_to_tensor(self, dtype=None, name=None, as_ref=False): <NEW_LINE> <INDENT> if as_ref: <NEW_LINE> <INDENT> raise ValueError( "You may be using variable created under distribute strategy in TF " "1.x control flows. Try explicitly converting the variable to Tensor " "using variable.read_value(), or switch to TF 2.x.") <NEW_LINE> <DEDENT> return ops.convert_to_tensor( self._get(), dtype=dtype, name=name, as_ref=as_ref)
Holds a map from replica to variables whose values are kept in sync.
6259905f63d6d428bbee3dc3
class FilterMixin(object): <NEW_LINE> <INDENT> @verbose <NEW_LINE> def savgol_filter(self, h_freq, verbose=None): <NEW_LINE> <INDENT> _check_preload(self, 'inst.savgol_filter') <NEW_LINE> h_freq = float(h_freq) <NEW_LINE> if h_freq >= self.info['sfreq'] / 2.: <NEW_LINE> <INDENT> raise ValueError('h_freq must be less than half the sample rate') <NEW_LINE> <DEDENT> if not check_version('scipy', '0.14'): <NEW_LINE> <INDENT> raise RuntimeError('scipy >= 0.14 must be installed for savgol') <NEW_LINE> <DEDENT> from scipy.signal import savgol_filter <NEW_LINE> window_length = (int(np.round(self.info['sfreq'] / h_freq)) // 2) * 2 + 1 <NEW_LINE> logger.info('Using savgol length %d' % window_length) <NEW_LINE> self._data[:] = savgol_filter(self._data, axis=-1, polyorder=5, window_length=window_length) <NEW_LINE> return self <NEW_LINE> <DEDENT> @verbose <NEW_LINE> def filter(self, l_freq, h_freq, picks=None, filter_length='auto', l_trans_bandwidth='auto', h_trans_bandwidth='auto', n_jobs=1, method='fir', iir_params=None, phase='zero', fir_window='hamming', fir_design='firwin', pad='edge', verbose=None): <NEW_LINE> <INDENT> _check_preload(self, 'inst.filter') <NEW_LINE> if pad is None and method != 'iir': <NEW_LINE> <INDENT> pad = 'edge' <NEW_LINE> <DEDENT> update_info, picks = _filt_check_picks(self.info, picks, l_freq, h_freq) <NEW_LINE> filter_data(self._data, self.info['sfreq'], l_freq, h_freq, picks, filter_length, l_trans_bandwidth, h_trans_bandwidth, n_jobs, method, iir_params, copy=False, phase=phase, fir_window=fir_window, fir_design=fir_design, pad=pad) <NEW_LINE> _filt_update_info(self.info, update_info, l_freq, h_freq) <NEW_LINE> return self <NEW_LINE> <DEDENT> @verbose <NEW_LINE> def resample(self, sfreq, npad='auto', window='boxcar', n_jobs=1, pad='edge', verbose=None): <NEW_LINE> <INDENT> from .epochs import BaseEpochs <NEW_LINE> _check_preload(self, 'inst.resample') <NEW_LINE> sfreq = float(sfreq) <NEW_LINE> o_sfreq = self.info['sfreq'] <NEW_LINE> self._data = resample(self._data, sfreq, o_sfreq, npad, window=window, n_jobs=n_jobs, pad=pad) <NEW_LINE> self.info['sfreq'] = float(sfreq) <NEW_LINE> self.times = (np.arange(self._data.shape[-1], dtype=np.float) / sfreq + self.times[0]) <NEW_LINE> if isinstance(self, BaseEpochs): <NEW_LINE> <INDENT> self._raw_times = self.times <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.first = int(self.times[0] * self.info['sfreq']) <NEW_LINE> self.last = len(self.times) + self.first - 1 <NEW_LINE> <DEDENT> return self
Object for Epoch/Evoked filtering.
6259905f8a43f66fc4bf3805
class BroadcastServerProtocol(WebSocketServerProtocol): <NEW_LINE> <INDENT> def onOpen(self): <NEW_LINE> <INDENT> super(BroadcastServerProtocol, self).onOpen() <NEW_LINE> self.factory.register(self) <NEW_LINE> <DEDENT> def connectionLost(self, reason): <NEW_LINE> <INDENT> super(BroadcastServerProtocol, self).connectionLost(reason) <NEW_LINE> self.factory.unregister(self)
"Protocol for a Websocket server which broadcasts messages to clients
6259905f097d151d1a2c26e6
class TestUVIS20Single(BaseWFC3): <NEW_LINE> <INDENT> detector = 'uvis' <NEW_LINE> def _single_raw_calib(self, rootname): <NEW_LINE> <INDENT> raw_file = '{}_raw.fits'.format(rootname) <NEW_LINE> self.get_input_file(raw_file) <NEW_LINE> subprocess.call(['calwf3.e', raw_file, '-vt']) <NEW_LINE> outputs = [('{}_flt.fits'.format(rootname), '{}_flt_ref.fits'.format(rootname))] <NEW_LINE> self.compare_outputs(outputs) <NEW_LINE> <DEDENT> @pytest.mark.parametrize( 'rootname', ['ib6w62toq']) <NEW_LINE> def test_uvis_20single(self, rootname): <NEW_LINE> <INDENT> self._single_raw_calib(rootname)
Test pos UVIS2 Messier-83 data
6259905f8da39b475be0485e
class OrcBasicApi(Resource): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> Resource.__init__(self) <NEW_LINE> self._resource = None <NEW_LINE> proc_name = OrcNameStr().from_module_name(self.__class__.__name__).process_name() <NEW_LINE> try: <NEW_LINE> <INDENT> self._resource = __import__("process.%s" % proc_name, {}, {}, ["modules"]).__getattribute__(proc_name)() <NEW_LINE> <DEDENT> except (AttributeError, ImportError): <NEW_LINE> <INDENT> application.logger.warning("Import process %s failed!" % proc_name) <NEW_LINE> <DEDENT> <DEDENT> @Orc.api <NEW_LINE> def dispatch_request(self, *args, **kwargs): <NEW_LINE> <INDENT> application.logger.info("Received request %s -> %s" % (request.method, request.args)) <NEW_LINE> if "POST" != request.method: <NEW_LINE> <INDENT> raise OrcFrameworkApiException(0x2, "Unsupported method: %s" % request.method) <NEW_LINE> <DEDENT> if "method" not in request.args: <NEW_LINE> <INDENT> raise OrcFrameworkApiException(0x3, "Args 'method' is not found") <NEW_LINE> <DEDENT> func = getattr(self, request.args["method"], None) <NEW_LINE> if func is None: <NEW_LINE> <INDENT> raise OrcFrameworkApiException(0x4, "Function %s is not supported" % request.args["method"]) <NEW_LINE> <DEDENT> return func(*args, **kwargs) <NEW_LINE> <DEDENT> def help(self): <NEW_LINE> <INDENT> return "Service is empty" if self._funcs is None else "Support functions: %s" % " ".join(self._funcs) <NEW_LINE> <DEDENT> def post(self): <NEW_LINE> <INDENT> pass
Support Post Using parameter func as function
6259905fd486a94d0ba2d63f
@attr_add_asblack <NEW_LINE> @attr_class_pickle <NEW_LINE> @attr_class_to_from_dict_no_recurse <NEW_LINE> @attr.s( kw_only=True, frozen=True, auto_attribs=True, repr_ns="fwdpy11.demographic_models" ) <NEW_LINE> class DemographicModelDetails(object): <NEW_LINE> <INDENT> model: object <NEW_LINE> name: str <NEW_LINE> source: typing.Dict <NEW_LINE> parameters: object <NEW_LINE> citation: typing.Optional[typing.Union[DemographicModelCitation, typing.Dict]] <NEW_LINE> metadata: typing.Optional[object] = None
Stores rich information about a demographic model. Instances of this class get returned by functions generating pre-calculated models. This class has the following attributes, whose names are also ``kwargs`` for intitialization. The attribute names also determine the order of positional arguments: :param model: The demographic model parameters :type model: object :param name: The name of the model :type name: str :param source: The source of the model :type source: dict :param parameters: The parameters used to generate ``model`` :type parameters: object :param citation: Citation information :type citation: dict or fwdpy11.demographic_models.DemographicModelCitation or None :param metadata: Optional field for additional info :type metadata: object .. versionadded:: 0.8.0
6259905f2c8b7c6e89bd4e66
class DeveloperprojectsV1SetIamPolicyRequest(messages.Message): <NEW_LINE> <INDENT> resource = messages.StringField(1, required=True) <NEW_LINE> setPolicyRequest = messages.MessageField('SetPolicyRequest', 2)
A DeveloperprojectsV1SetIamPolicyRequest object. Fields: resource: REQUIRED: The resource for which policy is being specified. Usually some path like projects/{$project}/zones/{$zone}/disks/{$disk}. setPolicyRequest: A SetPolicyRequest resource to be passed as the request body.
6259905f15baa7234946360a
class Std13KeypointProfile3D(KeypointProfile3D): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(Std13KeypointProfile3D, self).__init__( name='3DSTD13', keypoint_names=[('HEAD', LeftRightType.CENTRAL), ('LEFT_SHOULDER', LeftRightType.LEFT), ('RIGHT_SHOULDER', LeftRightType.RIGHT), ('LEFT_ELBOW', LeftRightType.LEFT), ('RIGHT_ELBOW', LeftRightType.RIGHT), ('LEFT_WRIST', LeftRightType.LEFT), ('RIGHT_WRIST', LeftRightType.RIGHT), ('LEFT_HIP', LeftRightType.LEFT), ('RIGHT_HIP', LeftRightType.RIGHT), ('LEFT_KNEE', LeftRightType.LEFT), ('RIGHT_KNEE', LeftRightType.RIGHT), ('LEFT_ANKLE', LeftRightType.LEFT), ('RIGHT_ANKLE', LeftRightType.RIGHT)], offset_keypoint_names=['LEFT_HIP', 'RIGHT_HIP'], scale_keypoint_name_pairs=[(['LEFT_SHOULDER', 'RIGHT_SHOULDER'], ['LEFT_HIP', 'RIGHT_HIP'])], segment_name_pairs=[ (['HEAD'], ['LEFT_SHOULDER', 'RIGHT_SHOULDER']), (['LEFT_SHOULDER', 'RIGHT_SHOULDER'], ['LEFT_SHOULDER']), (['LEFT_SHOULDER', 'RIGHT_SHOULDER'], ['RIGHT_SHOULDER']), (['LEFT_SHOULDER', 'RIGHT_SHOULDER'], ['LEFT_SHOULDER', 'RIGHT_SHOULDER', 'LEFT_HIP', 'RIGHT_HIP']), (['LEFT_SHOULDER'], ['LEFT_ELBOW']), (['RIGHT_SHOULDER'], ['RIGHT_ELBOW']), (['LEFT_ELBOW'], ['LEFT_WRIST']), (['RIGHT_ELBOW'], ['RIGHT_WRIST']), (['LEFT_SHOULDER', 'RIGHT_SHOULDER', 'LEFT_HIP', 'RIGHT_HIP'], ['LEFT_HIP', 'RIGHT_HIP']), (['LEFT_HIP', 'RIGHT_HIP'], ['LEFT_HIP']), (['LEFT_HIP', 'RIGHT_HIP'], ['RIGHT_HIP']), (['LEFT_HIP'], ['LEFT_KNEE']), (['RIGHT_HIP'], ['RIGHT_KNEE']), (['LEFT_KNEE'], ['LEFT_ANKLE']), (['RIGHT_KNEE'], ['RIGHT_ANKLE']) ], head_keypoint_name=['HEAD'], neck_keypoint_name=['LEFT_SHOULDER', 'RIGHT_SHOULDER'], left_shoulder_keypoint_name=['LEFT_SHOULDER'], right_shoulder_keypoint_name=['RIGHT_SHOULDER'], left_elbow_keypoint_name=['LEFT_ELBOW'], right_elbow_keypoint_name=['RIGHT_ELBOW'], left_wrist_keypoint_name=['LEFT_WRIST'], right_wrist_keypoint_name=['RIGHT_WRIST'], spine_keypoint_name=[ 'LEFT_SHOULDER', 'RIGHT_SHOULDER', 'LEFT_HIP', 'RIGHT_HIP' ], pelvis_keypoint_name=['LEFT_HIP', 'RIGHT_HIP'], left_hip_keypoint_name=['LEFT_HIP'], right_hip_keypoint_name=['RIGHT_HIP'], left_knee_keypoint_name=['LEFT_KNEE'], right_knee_keypoint_name=['RIGHT_KNEE'], left_ankle_keypoint_name=['LEFT_ANKLE'], right_ankle_keypoint_name=['RIGHT_ANKLE'])
Standard 3D 13-keypoint profile.
6259905f0fa83653e46f655e
class VideoList: <NEW_LINE> <INDENT> def __init__(self, path_response, list_id=None): <NEW_LINE> <INDENT> self.perpetual_range_selector = path_response.get('_perpetual_range_selector') <NEW_LINE> self.data = path_response <NEW_LINE> has_data = bool(path_response.get('lists')) <NEW_LINE> self.videos = OrderedDict() <NEW_LINE> self.artitem = None <NEW_LINE> self.contained_titles = None <NEW_LINE> self.videoids = None <NEW_LINE> if has_data: <NEW_LINE> <INDENT> self.id = common.VideoId( videoid=(list_id if list_id else next(iter(self.data['lists'])))) <NEW_LINE> self.videos = OrderedDict(resolve_refs(self.data['lists'][self.id.value], self.data)) <NEW_LINE> if self.videos: <NEW_LINE> <INDENT> self.artitem = list(self.videos.values())[0] <NEW_LINE> self.contained_titles = _get_titles(self.videos) <NEW_LINE> try: <NEW_LINE> <INDENT> self.videoids = _get_videoids(self.videos) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> self.videoids = None <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> return _check_sentinel(self.data['lists'][self.id.value][key]) <NEW_LINE> <DEDENT> def get(self, key, default=None): <NEW_LINE> <INDENT> return _check_sentinel(self.data['lists'][self.id.value].get(key, default))
A video list
6259905f8e7ae83300eea705
class Job(Document): <NEW_LINE> <INDENT> def __init__(self, job): <NEW_LINE> <INDENT> super(Job, self).__init__( data=job, base={ 'type': 'job', 'hostname': '', 'start': 0, 'done': 0, 'queue': 0, 'method': '', 'archive': 0, }) <NEW_LINE> if self.id is None: <NEW_LINE> <INDENT> raise ValueError('Job ID must be set') <NEW_LINE> <DEDENT> <DEDENT> def queue(self, method, host=None): <NEW_LINE> <INDENT> self['method'] = method <NEW_LINE> if host is not None: <NEW_LINE> <INDENT> self['hostname'] = host <NEW_LINE> <DEDENT> self['queue'] = seconds() <NEW_LINE> return self <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> self['start'] = seconds() <NEW_LINE> self['done'] = 0 <NEW_LINE> self['archive'] = 0 <NEW_LINE> return self._update_hostname() <NEW_LINE> <DEDENT> def finish(self): <NEW_LINE> <INDENT> self['done'] = seconds() <NEW_LINE> return self <NEW_LINE> <DEDENT> def archive(self): <NEW_LINE> <INDENT> if self['done'] <= 0: <NEW_LINE> <INDENT> self['done'] = seconds() <NEW_LINE> <DEDENT> self['archive'] = seconds() <NEW_LINE> return self <NEW_LINE> <DEDENT> def is_done(self): <NEW_LINE> <INDENT> return self['done'] != 0
Class to manage a CouchDB job entry.
6259905fcb5e8a47e493ccc1
class CODepartmentSelect(Select): <NEW_LINE> <INDENT> def __init__(self, attrs=None): <NEW_LINE> <INDENT> super(CODepartmentSelect, self).__init__(attrs, choices=DEPARTMENT_CHOICES)
A Select widget that uses a list of Colombian states as its choices.
6259905f55399d3f05627b97
class SyncEvent: <NEW_LINE> <INDENT> def __init__(self, initial: bool = False): <NEW_LINE> <INDENT> self.lock = Condition() <NEW_LINE> self.future = CFuture() <NEW_LINE> if initial: self.future.set_result(True) <NEW_LINE> <DEDENT> def clear(self): <NEW_LINE> <INDENT> with self.lock: <NEW_LINE> <INDENT> self.future = CFuture() <NEW_LINE> <DEDENT> <DEDENT> def set(self): <NEW_LINE> <INDENT> if not self.is_set(): <NEW_LINE> <INDENT> with self.lock: <NEW_LINE> <INDENT> if not self.is_set(): <NEW_LINE> <INDENT> self.future.set_result(True) <NEW_LINE> self.lock.notify_all() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def is_set(self) -> bool: <NEW_LINE> <INDENT> return self.future.done() <NEW_LINE> <DEDENT> def wait(self, timeout: Optional[float] = None): <NEW_LINE> <INDENT> if not self.future.done(): <NEW_LINE> <INDENT> with self.lock: <NEW_LINE> <INDENT> self.lock.wait_for(lambda: self.future.done(), timeout=timeout) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __await__(self): <NEW_LINE> <INDENT> yield from asyncio.wrap_future(self.future).__await__()
A union of `threading.Event` and `asyncio.Event` using `concurrent.futures.Future` and `asyncio.wrap_future`. Waiting for the event in threadland uses the `wait([timeout])` method while waiting for the event in asyncio-land uses `await event`. Note that the extra overhead of thread synchronization is likely less efficient than a pure `asyncio.Event`. Hence, this class should be avoided where possible.
6259905f23e79379d538db73
class Post(models.Model): <NEW_LINE> <INDENT> title = models.CharField( verbose_name = (u'Title'), help_text = (u' '), max_length = 255 ) <NEW_LINE> slug = models.SlugField( verbose_name = (u'Slug'), help_text = (u'Uri identifier.'), max_length = 255, unique = True ) <NEW_LINE> content_markdown = models.TextField( verbose_name = (u'Content (Markdown)'), help_text = (u'') ) <NEW_LINE> content_markup = models.TextField( verbose_name = (u'Content (Markup)'), help_text = (u' ') ) <NEW_LINE> categories = models.ManyToManyField( Category, verbose_name = (u'Categories'), help_text = (u' '), null = True, blank = True ) <NEW_LINE> date_publish = models.DateTimeField( verbose_name = (u'Publish Date'), help_text = (u' '), auto_now=True ) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> app_label = (u'blog') <NEW_LINE> verbose_name = (u'Post') <NEW_LINE> verbose_name_plural = (u'Posts') <NEW_LINE> ordering = ['-date_publish'] <NEW_LINE> <DEDENT> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> self.content_markup = markdown(self.content_markdown, ['codehilite']) <NEW_LINE> super(Post, self).save(*args, **kwargs) <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return "%s" % (self.title,)
Post Model
6259905f9c8ee82313040cc6
class Admin(User): <NEW_LINE> <INDENT> def __init__(self,first_name, last_name, age, gender): <NEW_LINE> <INDENT> super().__init__(first_name, last_name, age, gender) <NEW_LINE> self.privileges1 = Privileges()
Inherited class of User
6259905f004d5f362081fb2b
class SignAugmenter(BA.BaseAugmenter): <NEW_LINE> <INDENT> def __init__(self, image, label, class_id, placement_id=None): <NEW_LINE> <INDENT> self.rows, self.cols, _ = image.shape <NEW_LINE> self.horizon_line = int(self.rows * 0.4) <NEW_LINE> self.max_height = int(self.rows * 0.4) <NEW_LINE> super(SignAugmenter, self).__init__(image, label, class_id, placement_id) <NEW_LINE> <DEDENT> def place_extra_class(self, x, y, scaled_class_img): <NEW_LINE> <INDENT> scaled_class_height, scaled_class_width, _ = scaled_class_img.shape <NEW_LINE> all_poles = os.listdir('./Poles') <NEW_LINE> pole = cv2.imread(os.path.join('./Poles', random.choice(all_poles))) <NEW_LINE> init_height = random.uniform(1.3, 1.7) <NEW_LINE> init_width = random.uniform(0.08, 0.13) <NEW_LINE> pole_height = int(init_height * scaled_class_height) <NEW_LINE> pole_width = int(init_width * scaled_class_width) <NEW_LINE> pole_width -= 1 if pole_width % 2 == 0 else 0 <NEW_LINE> pole_width = 1 if pole_width <= 0 else pole_width <NEW_LINE> scaled_pole = cv2.resize(pole, (pole_width, pole_height), interpolation=cv2.INTER_CUBIC) <NEW_LINE> sign_err_code = self.create_roi(x, y-pole_height, scaled_class_img, pole_height) <NEW_LINE> if class_err_code: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> pole_err_code = self.create_roi(x, y, scaled_pole, 0, [154, 154, 154], 1) <NEW_LINE> if pole_err_code: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> return 0
Test class for augmentation
6259905f379a373c97d9a69d
class S3FKWrappersTests(unittest.TestCase): <NEW_LINE> <INDENT> def testHasForeignKey(self): <NEW_LINE> <INDENT> ptable = current.s3db.pr_person <NEW_LINE> self.assertFalse(s3_has_foreign_key(ptable.first_name)) <NEW_LINE> self.assertTrue(s3_has_foreign_key(ptable.pe_id)) <NEW_LINE> htable = current.s3db.hrm_human_resource <NEW_LINE> self.assertFalse(s3_has_foreign_key(htable.start_date)) <NEW_LINE> self.assertTrue(s3_has_foreign_key(htable.person_id)) <NEW_LINE> <DEDENT> def testGetForeignKey(self): <NEW_LINE> <INDENT> ptable = current.s3db.pr_person <NEW_LINE> ktablename, key, multiple = s3_get_foreign_key(ptable.pe_id) <NEW_LINE> self.assertEqual(ktablename, "pr_pentity") <NEW_LINE> self.assertEqual(key, "pe_id") <NEW_LINE> self.assertFalse(multiple)
Test has_foreign_key and get_foreign_key
6259905f24f1403a9268640a
class New(EndPoint): <NEW_LINE> <INDENT> argparse_noflag = "name" <NEW_LINE> schema = { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "name": { "type": "string", "description": "proto文件名,也是package名" }, "pb_include": { "type": "string", "title": "t", "description": "protobufer文件存放的地方", "default": "pbschema" }, "parent_package": { "type": "string", "title": "p", "description": "package父package" }, "cwd": { "type": "string", "description": "", "default": "." } } }
创建Grpc定义文件.
6259905f63b5f9789fe867eb
class GamepadAxis(IntEnum): <NEW_LINE> <INDENT> AXIS_UNKNOWN = 0 <NEW_LINE> AXIS_LEFT_X = auto() <NEW_LINE> AXIS_LEFT_Y = auto() <NEW_LINE> AXIS_RIGHT_X = auto() <NEW_LINE> AXIS_RIGHT_Y = auto() <NEW_LINE> AXIS_LEFT_TRIGGER = auto() <NEW_LINE> AXIS_RIGHT_TRIGGER = auto()
Gamepad Buttons
6259905ff548e778e596cc01
class HttpsUrl (httpurl.HttpUrl): <NEW_LINE> <INDENT> def local_check (self): <NEW_LINE> <INDENT> if httpurl.supportHttps: <NEW_LINE> <INDENT> super(HttpsUrl, self).local_check() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.add_info(_("%s URL ignored.") % self.scheme.capitalize()) <NEW_LINE> <DEDENT> <DEDENT> def get_http_object (self, scheme, host, port): <NEW_LINE> <INDENT> super(HttpsUrl, self).get_http_object(scheme, host, port) <NEW_LINE> self.check_ssl_certificate(self.url_connection.sock, host) <NEW_LINE> <DEDENT> def check_ssl_certificate(self, ssl_sock, host): <NEW_LINE> <INDENT> if not hasattr(ssl_sock, "getpeercert"): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> cert = ssl_sock.getpeercert() <NEW_LINE> log.debug(LOG_CHECK, "Got SSL certificate %s", cert) <NEW_LINE> if not cert: <NEW_LINE> <INDENT> msg = _('empty or no certificate found') <NEW_LINE> self.add_ssl_warning(ssl_sock, msg) <NEW_LINE> return <NEW_LINE> <DEDENT> if 'subject' in cert: <NEW_LINE> <INDENT> self.check_ssl_hostname(ssl_sock, cert, host) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> msg = _('certificate did not include "subject" information') <NEW_LINE> self.add_ssl_warning(ssl_sock, msg) <NEW_LINE> <DEDENT> if 'notAfter' in cert: <NEW_LINE> <INDENT> self.check_ssl_valid_date(ssl_sock, cert) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> msg = _('certificate did not include "notAfter" information') <NEW_LINE> self.add_ssl_warning(ssl_sock, msg) <NEW_LINE> <DEDENT> <DEDENT> def check_ssl_hostname(self, ssl_sock, cert, host): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> match_hostname(cert, host) <NEW_LINE> <DEDENT> except CertificateError as msg: <NEW_LINE> <INDENT> self.add_ssl_warning(ssl_sock, msg) <NEW_LINE> <DEDENT> <DEDENT> def check_ssl_valid_date(self, ssl_sock, cert): <NEW_LINE> <INDENT> import ssl <NEW_LINE> checkDaysValid = self.aggregate.config["warnsslcertdaysvalid"] <NEW_LINE> try: <NEW_LINE> <INDENT> notAfter = ssl.cert_time_to_seconds(cert['notAfter']) <NEW_LINE> <DEDENT> except ValueError as msg: <NEW_LINE> <INDENT> msg = _('invalid certficate "notAfter" value %r') % cert['notAfter'] <NEW_LINE> self.add_ssl_warning(ssl_sock, msg) <NEW_LINE> return <NEW_LINE> <DEDENT> curTime = time.time() <NEW_LINE> secondsValid = notAfter - curTime <NEW_LINE> if secondsValid < 0: <NEW_LINE> <INDENT> msg = _('certficate is expired on %s') % cert['notAfter'] <NEW_LINE> self.add_ssl_warning(ssl_sock, msg) <NEW_LINE> <DEDENT> elif checkDaysValid > 0 and secondsValid < (checkDaysValid * strformat.SECONDS_PER_DAY): <NEW_LINE> <INDENT> strSecondsValid = strformat.strduration_long(secondsValid) <NEW_LINE> msg = _('certificate is only %s valid') % strSecondsValid <NEW_LINE> self.add_ssl_warning(ssl_sock, msg) <NEW_LINE> <DEDENT> <DEDENT> def add_ssl_warning(self, ssl_sock, msg): <NEW_LINE> <INDENT> cipher_name, ssl_protocol, secret_bits = ssl_sock.cipher() <NEW_LINE> err = _(u"SSL warning: %(msg)s. Cipher %(cipher)s, %(protocol)s.") <NEW_LINE> attrs = dict(msg=msg, cipher=cipher_name, protocol=ssl_protocol) <NEW_LINE> self.add_warning(err % attrs, tag=WARN_HTTPS_CERTIFICATE)
Url link with https scheme.
6259905fd99f1b3c44d06d1b
class ICommentsListUtility(Interface): <NEW_LINE> <INDENT> pass
A marker interface for comments Utility
6259905f4f6381625f199fdf
class CORT_Event_Location(folder.ATFolder): <NEW_LINE> <INDENT> implements(ICORT_Event_Location) <NEW_LINE> meta_type = "CORT_Event_Location" <NEW_LINE> schema = CORT_Event_LocationSchema <NEW_LINE> title = atapi.ATFieldProperty('title') <NEW_LINE> description = atapi.ATFieldProperty('description')
Description of the Example Type
6259905ff7d966606f7493f5
class MockConnection(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.received = [] <NEW_LINE> self.to_be_sent = [] <NEW_LINE> self.closed = False <NEW_LINE> <DEDENT> def send(self, message): <NEW_LINE> <INDENT> if self.closed: <NEW_LINE> <INDENT> raise SelenolWebSocketClosedException() <NEW_LINE> <DEDENT> self.received.append(message) <NEW_LINE> <DEDENT> def recv(self): <NEW_LINE> <INDENT> if self.closed: <NEW_LINE> <INDENT> raise SelenolWebSocketClosedException() <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> return self.to_be_sent.pop() <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> raise SelenolWebSocketClosedException() <NEW_LINE> <DEDENT> <DEDENT> def close(self): <NEW_LINE> <INDENT> self.closed = True
mock backend connection for logging messages.
6259905f7d847024c075da4c
class SysFont(Font): <NEW_LINE> <INDENT> def __init__(self, name, size, bold=False, italic=False): <NEW_LINE> <INDENT> self._style = JFont.PLAIN <NEW_LINE> if bold: <NEW_LINE> <INDENT> self._style |= JFont.BOLD <NEW_LINE> <DEDENT> if italic: <NEW_LINE> <INDENT> self._style |= JFont.ITALIC <NEW_LINE> <DEDENT> Font.__init__(self,name,size) <NEW_LINE> <DEDENT> def set_bold(self, setting=True): <NEW_LINE> <INDENT> if setting: <NEW_LINE> <INDENT> if self.font.isItalic(): <NEW_LINE> <INDENT> self.font = self.deriveFont(JFont.BOLD | JFont.ITALIC) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.font = self.deriveFont(JFont.BOLD) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if self.font.isItalic(): <NEW_LINE> <INDENT> self.font = self.deriveFont(JFont.ITALIC) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self._style: <NEW_LINE> <INDENT> self.font = self.deriveFont(JFont.PLAIN) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.font = self <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def set_italic(self, setting=True): <NEW_LINE> <INDENT> if setting: <NEW_LINE> <INDENT> if self.font.isBold(): <NEW_LINE> <INDENT> self.font = self.deriveFont(JFont.BOLD | JFont.ITALIC) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.font = self.deriveFont(JFont.ITALIC) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if self.font.isBold(): <NEW_LINE> <INDENT> self.font = self.deriveFont(JFont.BOLD) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self._style: <NEW_LINE> <INDENT> self.font = self.deriveFont(JFont.PLAIN) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.font = self
**pyj2d.font.SysFont** * Font subclass
6259905f462c4b4f79dbd07e
class LRwPRObjetiveType4Mixin(LRwPR): <NEW_LINE> <INDENT> def loss(self, coef_, X, y, s): <NEW_LINE> <INDENT> coef = coef_.reshape(self.n_sfv_, self.n_features_) <NEW_LINE> p = np.array([sigmoid(X[i, :], coef[s[i], :]) for i in xrange(self.n_samples_)]) <NEW_LINE> q = np.array([np.sum(p[s == si]) for si in xrange(self.n_sfv_)]) / self.c_s_ <NEW_LINE> r = np.sum(p) / self.n_samples_ <NEW_LINE> l = np.sum(y * np.log(p) + (1.0 - y) * np.log(1.0 - p)) <NEW_LINE> f = np.sum(p * (np.log(q[s]) - np.log(r)) + (1.0 - p) * (np.log(1.0 - q[s]) - np.log(1.0 - r))) <NEW_LINE> reg = np.sum(coef * coef) <NEW_LINE> l = -l + self.eta * f + 0.5 * self.C * reg <NEW_LINE> return l <NEW_LINE> <DEDENT> def grad_loss(self, coef_, X, y, s): <NEW_LINE> <INDENT> coef = coef_.reshape(self.n_sfv_, self.n_features_) <NEW_LINE> l_ = np.empty(self.n_sfv_ * self.n_features_) <NEW_LINE> l = l_.reshape(self.n_sfv_, self.n_features_) <NEW_LINE> p = np.array([sigmoid(X[i, :], coef[s[i], :]) for i in xrange(self.n_samples_)]) <NEW_LINE> dp = (p * (1.0 - p))[:, np.newaxis] * X <NEW_LINE> q = np.array([np.sum(p[s == si]) for si in xrange(self.n_sfv_)]) / self.c_s_ <NEW_LINE> dq = np.array([np.sum(dp[s == si, :], axis=0) for si in xrange(self.n_sfv_)]) / self.c_s_[:, np.newaxis] <NEW_LINE> r = np.sum(p) / self.n_samples_ <NEW_LINE> dr = np.sum(dp, axis=0) / self.n_samples_ <NEW_LINE> for si in xrange(self.n_sfv_): <NEW_LINE> <INDENT> l[si, :] = np.sum((y - p)[s == si][:, np.newaxis] * X[s == si, :], axis=0) <NEW_LINE> <DEDENT> f1 = (np.log(q[s]) - np.log(r)) - (np.log(1.0 - q[s]) - np.log(1.0 - r)) <NEW_LINE> f2 = (p - q[s]) / (q[s] * (1.0 - q[s])) <NEW_LINE> f3 = (p - r) / (r * (1.0 - r)) <NEW_LINE> f4 = f1[:, np.newaxis] * dp + f2[:, np.newaxis] * dq[s, :] - np.outer(f3, dr) <NEW_LINE> f = np.array([np.sum(f4[s == si, :], axis=0) for si in xrange(self.n_sfv_)]) <NEW_LINE> reg = coef <NEW_LINE> l[:, :] = -l + self.eta * f + self.C * reg <NEW_LINE> return l_
objective function of logistic regression with prejudice remover Loss Function type 4: Weights for logistic regression are prepared for each value of S. Penalty for enhancing is defined as mutual information between Y and S.
6259905fd486a94d0ba2d641
class SleepIQSensor(Entity): <NEW_LINE> <INDENT> def __init__(self, sleepiq_data, bed_id, side): <NEW_LINE> <INDENT> self._bed_id = bed_id <NEW_LINE> self._side = side <NEW_LINE> self.sleepiq_data = sleepiq_data <NEW_LINE> self.side = None <NEW_LINE> self.bed = None <NEW_LINE> self._name = None <NEW_LINE> self.type = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return 'SleepNumber {} {} {}'.format( self.bed.name, self.side.sleeper.first_name, self._name) <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.sleepiq_data.update() <NEW_LINE> self.bed = self.sleepiq_data.beds[self._bed_id] <NEW_LINE> _LOGGER.error('IQ Bed: ' + str(self.bed.__dict__)) <NEW_LINE> self.side = getattr(self.bed, self._side) <NEW_LINE> _LOGGER.error('IQ Side :: ' + str(self.side.__dict__)) <NEW_LINE> _LOGGER.error('IQ Sleeper :: ' + str(self.side.sleeper.__dict__))
Implementation of a SleepIQ sensor.
6259905f56ac1b37e6303823
class DataConfigManager(object): <NEW_LINE> <INDENT> CONFIG_FILE_PATH = os.path.join(os.getcwd(), ".chdata") <NEW_LINE> @classmethod <NEW_LINE> def set_config(cls, data_config): <NEW_LINE> <INDENT> logger.debug("Setting {} in the file {}".format(data_config.to_dict(), cls.CONFIG_FILE_PATH)) <NEW_LINE> with open(cls.CONFIG_FILE_PATH, "w") as config_file: <NEW_LINE> <INDENT> config_file.write(json.dumps(data_config.to_dict())) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def get_config(cls): <NEW_LINE> <INDENT> if not os.path.isfile(cls.CONFIG_FILE_PATH): <NEW_LINE> <INDENT> raise ClException("Missing .cldata file, run ch data init first") <NEW_LINE> <DEDENT> with open(cls.CONFIG_FILE_PATH, "r") as config_file: <NEW_LINE> <INDENT> data_config_str = config_file.read() <NEW_LINE> <DEDENT> return json.loads(data_config_str)
Manages .russelldata file in the current directory
6259905fd53ae8145f919adb
class Solution: <NEW_LINE> <INDENT> def findMedianSortedArrays(self, nums1, nums2): <NEW_LINE> <INDENT> total_len = len(nums1) + len(nums2) <NEW_LINE> mid_ind = total_len / 2 <NEW_LINE> ind_1 = ind_2 = 0 <NEW_LINE> if len(nums1) == 0 and len(nums2) == 1: <NEW_LINE> <INDENT> return nums2[0] <NEW_LINE> <DEDENT> elif len(nums1) == 1 and len(nums2) == 0: <NEW_LINE> <INDENT> return nums1[0] <NEW_LINE> <DEDENT> if len(nums1) == 0: <NEW_LINE> <INDENT> previous_num = nums2[len(nums2)/2-1] <NEW_LINE> median = nums2[len(nums2)/2] <NEW_LINE> if len(nums2) % 2 == 0: <NEW_LINE> <INDENT> median = (previous_num + median)/2.0 <NEW_LINE> <DEDENT> return median <NEW_LINE> <DEDENT> elif len(nums2) == 0: <NEW_LINE> <INDENT> previous_num = nums1[len(nums1)/2-1] <NEW_LINE> median = nums1[len(nums1)/2] <NEW_LINE> if len(nums1) % 2 == 0: <NEW_LINE> <INDENT> median = (previous_num + median)/2.0 <NEW_LINE> <DEDENT> return median <NEW_LINE> <DEDENT> curr_ind = 0 <NEW_LINE> while curr_ind <= mid_ind: <NEW_LINE> <INDENT> if ind_2 >= len(nums2) or (ind_1 < len(nums1) and nums1[ind_1] <= nums2[ind_2]): <NEW_LINE> <INDENT> if curr_ind + 1 == mid_ind: <NEW_LINE> <INDENT> previous_num = nums1[ind_1] <NEW_LINE> <DEDENT> if curr_ind == mid_ind: <NEW_LINE> <INDENT> median = nums1[ind_1] <NEW_LINE> <DEDENT> ind_1 += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if curr_ind + 1 == mid_ind: <NEW_LINE> <INDENT> previous_num = nums2[ind_2] <NEW_LINE> <DEDENT> if curr_ind == mid_ind: <NEW_LINE> <INDENT> median = nums2[ind_2] <NEW_LINE> <DEDENT> ind_2 += 1 <NEW_LINE> <DEDENT> curr_ind += 1 <NEW_LINE> <DEDENT> if total_len % 2 == 0: <NEW_LINE> <INDENT> median = (previous_num + median) / 2.0 <NEW_LINE> <DEDENT> return median
Idea: - merge sort idea, compare both curr_ind for nums1 & nums2 and iterate
6259905fac7a0e7691f73b5d
class FileImportError(LoRaException): <NEW_LINE> <INDENT> pass
Error during file import
6259905f99cbb53fe683255b
class AzureAttestationRestClient(object): <NEW_LINE> <INDENT> def __init__( self, credential: "AsyncTokenCredential", instance_url: str, **kwargs: Any ) -> None: <NEW_LINE> <INDENT> base_url = '{instanceUrl}' <NEW_LINE> self._config = AzureAttestationRestClientConfiguration(credential, instance_url, **kwargs) <NEW_LINE> self._client = AsyncPipelineClient(base_url=base_url, config=self._config, **kwargs) <NEW_LINE> client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} <NEW_LINE> self._serialize = Serializer(client_models) <NEW_LINE> self._serialize.client_side_validation = False <NEW_LINE> self._deserialize = Deserializer(client_models) <NEW_LINE> self.policy = PolicyOperations( self._client, self._config, self._serialize, self._deserialize) <NEW_LINE> self.policy_certificates = PolicyCertificatesOperations( self._client, self._config, self._serialize, self._deserialize) <NEW_LINE> self.attestation = AttestationOperations( self._client, self._config, self._serialize, self._deserialize) <NEW_LINE> self.signing_certificates = SigningCertificatesOperations( self._client, self._config, self._serialize, self._deserialize) <NEW_LINE> self.metadata_configuration = MetadataConfigurationOperations( self._client, self._config, self._serialize, self._deserialize) <NEW_LINE> <DEDENT> async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: <NEW_LINE> <INDENT> path_format_arguments = { 'instanceUrl': self._serialize.url("self._config.instance_url", self._config.instance_url, 'str', skip_quote=True), } <NEW_LINE> http_request.url = self._client.format_url(http_request.url, **path_format_arguments) <NEW_LINE> stream = kwargs.pop("stream", True) <NEW_LINE> pipeline_response = await self._client._pipeline.run(http_request, stream=stream, **kwargs) <NEW_LINE> return pipeline_response.http_response <NEW_LINE> <DEDENT> async def close(self) -> None: <NEW_LINE> <INDENT> await self._client.close() <NEW_LINE> <DEDENT> async def __aenter__(self) -> "AzureAttestationRestClient": <NEW_LINE> <INDENT> await self._client.__aenter__() <NEW_LINE> return self <NEW_LINE> <DEDENT> async def __aexit__(self, *exc_details) -> None: <NEW_LINE> <INDENT> await self._client.__aexit__(*exc_details)
Describes the interface for the per-tenant enclave service. :ivar policy: PolicyOperations operations :vartype policy: azure.security.attestation._generated.aio.operations.PolicyOperations :ivar policy_certificates: PolicyCertificatesOperations operations :vartype policy_certificates: azure.security.attestation._generated.aio.operations.PolicyCertificatesOperations :ivar attestation: AttestationOperations operations :vartype attestation: azure.security.attestation._generated.aio.operations.AttestationOperations :ivar signing_certificates: SigningCertificatesOperations operations :vartype signing_certificates: azure.security.attestation._generated.aio.operations.SigningCertificatesOperations :ivar metadata_configuration: MetadataConfigurationOperations operations :vartype metadata_configuration: azure.security.attestation._generated.aio.operations.MetadataConfigurationOperations :param credential: Credential needed for the client to connect to Azure. :type credential: ~azure.core.credentials_async.AsyncTokenCredential :param instance_url: The attestation instance base URI, for example https://mytenant.attest.azure.net. :type instance_url: str
6259905f29b78933be26ac01
class MonitorProtocol(RedisProtocol): <NEW_LINE> <INDENT> def messageReceived(self, message): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def replyReceived(self, reply): <NEW_LINE> <INDENT> self.messageReceived(reply) <NEW_LINE> <DEDENT> def monitor(self): <NEW_LINE> <INDENT> return self.execute_command("MONITOR") <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> self.transport.loseConnection()
monitor has the same behavior as subscribe: hold the connection until something happens. take care with the performance impact: http://redis.io/commands/monitor
6259905f379a373c97d9a69e
class PfizerFragmenter(FragmenterBase): <NEW_LINE> <INDENT> type: Literal["PfizerFragmenter"] = "PfizerFragmenter" <NEW_LINE> @classmethod <NEW_LINE> def description(cls) -> str: <NEW_LINE> <INDENT> return "Fragment a molecule across all rotatable bonds using the Pfizer fragmentation scheme." <NEW_LINE> <DEDENT> def _apply( self, molecules: List[Molecule], toolkit_registry: ToolkitRegistry ) -> ComponentResult: <NEW_LINE> <INDENT> from openff.fragmenter.fragment import PfizerFragmenter <NEW_LINE> result = self._create_result(toolkit_registry=toolkit_registry) <NEW_LINE> for molecule in molecules: <NEW_LINE> <INDENT> fragment_factory = PfizerFragmenter() <NEW_LINE> try: <NEW_LINE> <INDENT> fragment_result = fragment_factory.fragment( molecule=molecule, toolkit_registry=toolkit_registry, target_bond_smarts=self.target_torsion_smarts, ) <NEW_LINE> self._process_fragments( fragments=fragment_result, component_result=result ) <NEW_LINE> <DEDENT> except (RuntimeError, ValueError): <NEW_LINE> <INDENT> result.filter_molecule(molecule) <NEW_LINE> <DEDENT> <DEDENT> return result
The openff.fragmenter implementation of the Pfizer fragmenation method as described here (doi: 10.1021/acs.jcim.9b00373)
6259905f1f037a2d8b9e53a8
@implementer(ICredentialsChecker) <NEW_LINE> class InMemoryUsernamePasswordDatabaseDontUse(object): <NEW_LINE> <INDENT> credentialInterfaces = (credentials.IUsernamePassword, credentials.IUsernameHashedPassword) <NEW_LINE> def __init__(self, **users): <NEW_LINE> <INDENT> self.users = users <NEW_LINE> <DEDENT> def addUser(self, username, password): <NEW_LINE> <INDENT> self.users[username] = password <NEW_LINE> <DEDENT> def _cbPasswordMatch(self, matched, username): <NEW_LINE> <INDENT> if matched: <NEW_LINE> <INDENT> return username <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return failure.Failure(error.UnauthorizedLogin()) <NEW_LINE> <DEDENT> <DEDENT> def requestAvatarId(self, credentials): <NEW_LINE> <INDENT> if credentials.username in self.users: <NEW_LINE> <INDENT> return defer.maybeDeferred( credentials.checkPassword, self.users[credentials.username]).addCallback( self._cbPasswordMatch, bytes(credentials.username)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return defer.fail(error.UnauthorizedLogin())
An extremely simple credentials checker. This is only of use in one-off test programs or examples which don't want to focus too much on how credentials are verified. You really don't want to use this for anything else. It is, at best, a toy. If you need a simple credentials checker for a real application, see L{FilePasswordDB}.
6259905f1f5feb6acb164264
class ApiTeamDetails(MainApiHandler): <NEW_LINE> <INDENT> def get(self): <NEW_LINE> <INDENT> team_key = self.request.get('team') <NEW_LINE> year = self.request.get('year') <NEW_LINE> response_json = dict() <NEW_LINE> try: <NEW_LINE> <INDENT> response_json = ApiHelper.getTeamInfo(team_key) <NEW_LINE> if self.request.get('events'): <NEW_LINE> <INDENT> reponse_json = ApiHelper.addTeamEvents(response_json, year) <NEW_LINE> <DEDENT> self.response.out.write(json.dumps(response_json)) <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> response_json = { "Property Error": "No team found for the key given" } <NEW_LINE> self.response.out.write(json.dumps(response_json))
Information about a Team in a particular year, including full Event and Match objects
6259905fd99f1b3c44d06d1d
class Post(Base): <NEW_LINE> <INDENT> __tablename__ = 'posts' <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> title = Column(Unicode(150), nullable=False) <NEW_LINE> timestamp = Column(DateTime, default=datetime.utcnow) <NEW_LINE> body = Column(UnicodeText, nullable=False) <NEW_LINE> view_count = Column(Integer, default=0) <NEW_LINE> comments_allowed = Column(Boolean, default=True) <NEW_LINE> user_id = Column(Unicode(100), ForeignKey(User.user_id)) <NEW_LINE> category_id = Column(Integer, ForeignKey(Category.id)) <NEW_LINE> category = relationship(Category, backref=backref('blog_posts'))
Holds blog posts
6259905f3cc13d1c6d466dbc
class APIv2(image_v1.APIv1): <NEW_LINE> <INDENT> _endpoint_suffix = '/v2' <NEW_LINE> def _munge_url(self): <NEW_LINE> <INDENT> if not self.endpoint.endswith(self._endpoint_suffix): <NEW_LINE> <INDENT> self.endpoint = self.endpoint + self._endpoint_suffix <NEW_LINE> <DEDENT> <DEDENT> def image_list( self, detailed=False, public=False, private=False, community=False, shared=False, **filter ): <NEW_LINE> <INDENT> if not public and not private and not community and not shared: <NEW_LINE> <INDENT> filter.pop('visibility', None) <NEW_LINE> <DEDENT> elif public: <NEW_LINE> <INDENT> filter['visibility'] = 'public' <NEW_LINE> <DEDENT> elif private: <NEW_LINE> <INDENT> filter['visibility'] = 'private' <NEW_LINE> <DEDENT> elif community: <NEW_LINE> <INDENT> filter['visibility'] = 'community' <NEW_LINE> <DEDENT> elif shared: <NEW_LINE> <INDENT> filter['visibility'] = 'shared' <NEW_LINE> <DEDENT> url = "/images" <NEW_LINE> if detailed: <NEW_LINE> <INDENT> url += "/detail" <NEW_LINE> <DEDENT> return self.list(url, **filter)['images']
Image v2 API
6259905f4f6381625f199fe0