code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class Shape(object): <NEW_LINE> <INDENT> def __init__(self, type_, data=None): <NEW_LINE> <INDENT> self._type = type_ <NEW_LINE> if type_ == "polygon": <NEW_LINE> <INDENT> if isinstance(data, list): <NEW_LINE> <INDENT> data = tuple(data) <NEW_LINE> <DEDENT> <DEDENT> elif type_ == "image": <NEW_LINE> <INDENT> if isinstance(data, str): <NEW_LINE> <INDENT> if data.lower().endswith(".gif") and isfile(data): <NEW_LINE> <INDENT> data = TurtleScreen._image(data) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> elif type_ == "compound": <NEW_LINE> <INDENT> data = [] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TurtleGraphicsError("There is no shape type %s" % type_) <NEW_LINE> <DEDENT> self._data = data <NEW_LINE> <DEDENT> def addcomponent(self, poly, fill, outline=None): <NEW_LINE> <INDENT> if self._type != "compound": <NEW_LINE> <INDENT> raise TurtleGraphicsError("Cannot add component to %s Shape" % self._type) <NEW_LINE> <DEDENT> if outline is None: <NEW_LINE> <INDENT> outline = fill <NEW_LINE> <DEDENT> self._data.append([poly, fill, outline])
Data structure modeling shapes. attribute _type is one of "polygon", "image", "compound" attribute _data is - depending on _type a poygon-tuple, an image or a list constructed using the addcomponent method.
62598fabd268445f26639b4f
class SecurityGroupsTestIPv4(SecurityGroupsTest): <NEW_LINE> <INDENT> PING_COMMAND = 'ping -c 3 {}' <NEW_LINE> SSH_COMMAND = ('ssh -o UserKnownHostsFile=/dev/null ' '-o StrictHostKeyChecking=no -o ConnectTimeout=60 ' '-i {private_key_path} root@{ip_address} {command}') <NEW_LINE> NAMES_PREFIX = 'security_groups_IPv4' <NEW_LINE> ETHERTYPE = 'IPv4' <NEW_LINE> NETCAT = 'nc' <NEW_LINE> OPEN_TCP_PORTS = [91, 92, 93, ] <NEW_LINE> CLOSED_TCP_PORTS = [94, 95, 96, ] <NEW_LINE> OPEN_UDP_PORT = 97 <NEW_LINE> CLOSED_UPD_PORT = 98 <NEW_LINE> ANY_UPD_OPEN = 99 <NEW_LINE> ANY_UDP_CLOSED = 100 <NEW_LINE> UDP_PORT_BASE_FOR_MAX = 201 <NEW_LINE> MAX_UDP_OPEN = 220 <NEW_LINE> MAX_UDP_CLOSED = 221 <NEW_LINE> @classmethod <NEW_LINE> def setUpClass(cls): <NEW_LINE> <INDENT> super(SecurityGroupsTestIPv4, cls).setUpClass() <NEW_LINE> cls.listener_port_ip = cls.listener.entity.addresses.public.ipv4 <NEW_LINE> <DEDENT> @tags(type='negative', net='yes') <NEW_LINE> def test_no_access_ssh_ping_ipv4(self): <NEW_LINE> <INDENT> self._test_no_access_ssh_ping() <NEW_LINE> <DEDENT> @tags(type='positive', net='yes') <NEW_LINE> def test_ssh_ping_from_specific_address_ipv4(self): <NEW_LINE> <INDENT> remote_ip_prefix = IP_FMT.format( self.sender.entity.addresses.public.ipv4, '32') <NEW_LINE> self._test_ssh_ping_from_specific_address(remote_ip_prefix) <NEW_LINE> <DEDENT> @tags(type='positive', net='yes') <NEW_LINE> def test_ssh_ping_from_cidr_ipv4(self): <NEW_LINE> <INDENT> cidr_str = IP_FMT.format( self.sender.entity.addresses.public.ipv4, '30') <NEW_LINE> other_sender_addr = self.other_sender.entity.addresses.public.ipv4 <NEW_LINE> self._test_ssh_ping_from_cidr(cidr_str, other_sender_addr) <NEW_LINE> <DEDENT> @tags(type='positive', net='yes') <NEW_LINE> def test_tcp_with_ports_range_ipv4(self): <NEW_LINE> <INDENT> self._test_tcp_with_ports_range() <NEW_LINE> <DEDENT> @tags(type='positive', net='yes') <NEW_LINE> def test_udp_with_specific_port_ipv4(self): <NEW_LINE> <INDENT> self._test_udp_with_specific_port() <NEW_LINE> <DEDENT> @tags(type='positive', net='yes') <NEW_LINE> def test_any_protocol_ipv4(self): <NEW_LINE> <INDENT> remote_ip_prefix = IP_FMT.format( self.sender.entity.addresses.public.ipv4, '32') <NEW_LINE> self._test_any_protocol(remote_ip_prefix) <NEW_LINE> <DEDENT> @tags(type='positive', net='yes') <NEW_LINE> def test_max_number_secgroups_per_port_ipv4(self): <NEW_LINE> <INDENT> remote_ip_prefix = IP_FMT.format( self.sender.entity.addresses.public.ipv4, '32') <NEW_LINE> self._test_max_number_secgroups_per_port(remote_ip_prefix)
This class executes the test cases in SecurityGroupsTest for public net IPv4
62598fab3539df3088ecc24b
class Gesture(peewee.Model): <NEW_LINE> <INDENT> id = peewee.PrimaryKeyField() <NEW_LINE> description = peewee.TextField() <NEW_LINE> @staticmethod <NEW_LINE> def fetch(code): <NEW_LINE> <INDENT> if type(code) == str: <NEW_LINE> <INDENT> if code[0] != 'G': <NEW_LINE> <INDENT> raise AttributeError('Incorrect gesture code, must start with G, eg.: "G11".') <NEW_LINE> <DEDENT> code = int(code[1:]) <NEW_LINE> <DEDENT> return Gesture.get(Gesture.id == code)
This table contains the ID and description of a known gesture used in the transcript.
62598faba17c0f6771d5c1cd
class TestMinRationCount(unittest.TestCase): <NEW_LINE> <INDENT> def test_basic(self): <NEW_LINE> <INDENT> self.assertEqual(get_min_ration_count(5, [2, 3, 4, 5, 6]), 4) <NEW_LINE> self.assertEqual(get_min_ration_count(2, [1, 2]), "NO")
Test.
62598fab5fc7496912d4824e
class RDdiffLattice(Lattice): <NEW_LINE> <INDENT> _beta_RD = 1./2. <NEW_LINE> def __init__(self, length, ht=0.1, seed=None): <NEW_LINE> <INDENT> Lattice.__init__(self, length, seed=seed, heighttype=float) <NEW_LINE> self._ht = ht <NEW_LINE> self.beta = RDLattice._beta_RD <NEW_LINE> <DEDENT> def evolve(self, nprtcls): <NEW_LINE> <INDENT> nsteps = int((float(nprtcls)/self.length)/self._ht) <NEW_LINE> self._heights = c_evolve.evolveRDdiff(self._heights, self._ht, nsteps, self._pbc) <NEW_LINE> return
Lattice with evolution following the random deposition model.
62598fab3d592f4c4edbae64
class AbstractSoundRelatedFilter(AbstractFilter): <NEW_LINE> <INDENT> pass
Базовый класс для всех фильтров, связанных со звуком.
62598fab4e4d5625663723be
class FormFieldBlockMixin(object, metaclass=DeclarativeSubBlocksMetaclass): <NEW_LINE> <INDENT> label = CharBlock() <NEW_LINE> required = BooleanBlock(default=False, required=False) <NEW_LINE> help_text = CharBlock(required=False) <NEW_LINE> def get_field_options(self, field): <NEW_LINE> <INDENT> options = {} <NEW_LINE> options['label'] = field['label'] <NEW_LINE> options['help_text'] = field['help_text'] <NEW_LINE> options['required'] = field['required'] <NEW_LINE> return options <NEW_LINE> <DEDENT> def create_field(self, field): <NEW_LINE> <INDENT> options = self.get_field_options(field) <NEW_LINE> return django.forms.CharField(**options) <NEW_LINE> <DEDENT> def clean_name(self, value): <NEW_LINE> <INDENT> return create_field_id(value['label']) <NEW_LINE> <DEDENT> def render_basic(self, value, context=None): <NEW_LINE> <INDENT> if context: <NEW_LINE> <INDENT> form = context['form'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> form = { self.clean_name(value): self.create_field(value) } <NEW_LINE> <DEDENT> return format_html('<div class="{}">{}{}</div>', self.__class__.__name__.lower(), form[self.clean_name(value)].label_tag(), form[self.clean_name(value)]) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> icon = 'form'
Every Block that can be a form field in a StreamField must use this mixin. Inheriting from this class allows for the block to be identified and for the block to generate the needed information for the form.
62598fab45492302aabfc469
class StatusIconHelper(BaseWebElementHelper): <NEW_LINE> <INDENT> @property <NEW_LINE> def value(self): <NEW_LINE> <INDENT> icon_class = self.get_attribute('class') <NEW_LINE> if 'pficon-error-circle-o' in icon_class: <NEW_LINE> <INDENT> return 'failed' <NEW_LINE> <DEDENT> elif 'pficon-ok' in icon_class: <NEW_LINE> <INDENT> return 'finished' <NEW_LINE> <DEDENT> elif 'pficon-warning-triangle-o' in icon_class: <NEW_LINE> <INDENT> return 'warning' <NEW_LINE> <DEDENT> elif 'fa-spinner' in icon_class: <NEW_LINE> <INDENT> return 'new or processing' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception('Unknown icon state')
StatusIcon helper (Selenium webelement wrapper). Provides basic methods for manipulation with a task status icon.
62598fabf548e778e596b53c
class problem(object): <NEW_LINE> <INDENT> def __init__(self, dims, Pdata, Pindices, Pindptr, q, Adata, Aindices, Aindptr, l, u): <NEW_LINE> <INDENT> (self.n, self.m) = dims <NEW_LINE> self.P = spspa.csc_matrix((Pdata, Pindices, Pindptr), shape=(self.n, self.n)) <NEW_LINE> self.q = q <NEW_LINE> self.A = spspa.csc_matrix((Adata, Aindices, Aindptr), shape=(self.m, self.n)) <NEW_LINE> self.l = l if l is not None else -np.inf*np.ones(self.m) <NEW_LINE> self.u = u if u is not None else np.inf*np.ones(self.m) <NEW_LINE> <DEDENT> def objval(self, x): <NEW_LINE> <INDENT> return .5 * np.dot(x, self.P.dot(x)) + np.dot(self.q, x)
QP problem of the form minimize 1/2 x' P x + q' x subject to l <= A x <= u Attributes ---------- P, q A, l, u
62598fabf7d966606f747f7d
class pdf_xref(pdf_match): <NEW_LINE> <INDENT> def trailer(self): <NEW_LINE> <INDENT> return pdf_dict(next(self.find('dicts')), origin=self) <NEW_LINE> <DEDENT> def blocks(self): <NEW_LINE> <INDENT> return (pdf_xblock(x, origin=self) for x in self.finditer(P['xblock']))
A class to represent a single xref Initialized from a re.match object
62598fab10dbd63aa1c70b4c
class AppServerError(Exception): <NEW_LINE> <INDENT> pass
Base OpenROAD AppServer Exception
62598fab460517430c432029
class clean_args(object): <NEW_LINE> <INDENT> def __init__(self, log_context=None,): <NEW_LINE> <INDENT> self.log_context = log_context <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: <NEW_LINE> <INDENT> iprot._fast_decode(self, iprot, [self.__class__, self.thrift_spec]) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRING: <NEW_LINE> <INDENT> self.log_context = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot._fast_encode is not None and self.thrift_spec is not None: <NEW_LINE> <INDENT> oprot.trans.write(oprot._fast_encode(self, [self.__class__, self.thrift_spec])) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('clean_args') <NEW_LINE> if self.log_context is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('log_context', TType.STRING, 1) <NEW_LINE> oprot.writeString(self.log_context.encode('utf-8') if sys.version_info[0] == 2 else self.log_context) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.items()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other)
Attributes: - log_context
62598fab3cc13d1c6d465704
class CorniceSchema(object): <NEW_LINE> <INDENT> def __init__(self, _colander_schema): <NEW_LINE> <INDENT> self._c_schema = _colander_schema <NEW_LINE> <DEDENT> def bind_attributes(self, request=None): <NEW_LINE> <INDENT> if request: <NEW_LINE> <INDENT> self._attributes = self._c_schema().bind(request=request).children <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._attributes = self._c_schema().children <NEW_LINE> <DEDENT> <DEDENT> def get_attributes(self, location=("body", "headers", "querystring"), required=(True, False), request=None): <NEW_LINE> <INDENT> if not hasattr(self, '_attributes'): <NEW_LINE> <INDENT> self.bind_attributes(request) <NEW_LINE> <DEDENT> def _filter(attr): <NEW_LINE> <INDENT> if not hasattr(attr, "location"): <NEW_LINE> <INDENT> valid_location = 'body' in location <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> valid_location = attr.location in to_list(location) <NEW_LINE> <DEDENT> return valid_location and attr.required in to_list(required) <NEW_LINE> <DEDENT> return list(filter(_filter, self._attributes)) <NEW_LINE> <DEDENT> def as_dict(self): <NEW_LINE> <INDENT> if not hasattr(self, '_attributes'): <NEW_LINE> <INDENT> self.bind_attributes() <NEW_LINE> <DEDENT> schema = {} <NEW_LINE> for attr in self._attributes: <NEW_LINE> <INDENT> schema[attr.name] = { 'type': getattr(attr, 'type', attr.typ), 'name': attr.name, 'description': getattr(attr, 'description', ''), 'required': getattr(attr, 'required', False), } <NEW_LINE> <DEDENT> return schema <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_colander(klass, colander_schema): <NEW_LINE> <INDENT> return CorniceSchema(colander_schema)
Defines a cornice schema
62598fab7b25080760ed7446
class GetItemTable(Index, synode.Node): <NEW_LINE> <INDENT> name = 'Get Item Table' <NEW_LINE> nodeid = "org.sysess.sympathy.list.getitemtable" <NEW_LINE> icon = 'list_get_item.svg' <NEW_LINE> inputs = Ports([Port.Tables('Input Tables', name='port1')]) <NEW_LINE> outputs = Ports([Port.Table('Output selected Table', name='port3')]) <NEW_LINE> def adjust_parameters(self, node_context): <NEW_LINE> <INDENT> input_list = node_context.input['port1'] <NEW_LINE> if input_list.is_valid(): <NEW_LINE> <INDENT> node_context.parameters['combo'].list = ( [u'{index}\t{name}'.format( index=i, name=(item.get_name() or '')) for i, item in enumerate(input_list)]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> node_context.parameters['combo'].list = ( node_context.parameters['combo'].value_names) <NEW_LINE> <DEDENT> return node_context <NEW_LINE> <DEDENT> def execute(self, node_context): <NEW_LINE> <INDENT> index_execute(node_context)
Get one Table in list of Tables. The Table is selected by index in the list. :Inputs: **List** : Tables Incoming list of Tables. :Outputs: **Item** : Table The Table at the selected index of the incoming list. :Configuration: **Index** Select index in the incoming list to extract the outgoing Table from. :Opposite node: :ref:`Table to Tables` :Ref. nodes:
62598fabfff4ab517ebcd77d
class ProjectFloorAreaSection(models.Model): <NEW_LINE> <INDENT> project_subtype = models.ForeignKey( ProjectSubtype, verbose_name=_("project subtype"), on_delete=models.CASCADE, related_name="floor_area_sections", ) <NEW_LINE> name = models.CharField(max_length=255, verbose_name=_("name")) <NEW_LINE> index = models.PositiveIntegerField(verbose_name=_("index"), default=0) <NEW_LINE> attributes = models.ManyToManyField( Attribute, verbose_name=_("attributes"), related_name="floor_area_sections", through="ProjectFloorAreaSectionAttribute", ) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = _("project floor area section") <NEW_LINE> verbose_name_plural = _("project floor area sections") <NEW_LINE> ordering = ("index",) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return f"{self.name} ({self.project_subtype.name})" <NEW_LINE> <DEDENT> def get_attribute_identifiers(self): <NEW_LINE> <INDENT> return [a.identifier for a in self.attributes.all()]
Defines a floor area data section.
62598fab627d3e7fe0e06e45
class Error(Exception): <NEW_LINE> <INDENT> pass
Base class for exceptions in the numina package.
62598fabcc0a2c111447afa9
class CPEViewSet(PDCModelViewSet): <NEW_LINE> <INDENT> queryset = models.CPE.objects.all() <NEW_LINE> serializer_class = CPESerializer <NEW_LINE> filter_class = filters.CPEFilter <NEW_LINE> permission_classes = (APIPermission,)
Common Platform Enumeration (CPE) for linking CPE with variants ($LINK:variantcpe-list$). CPE is a standardized method of describing and identifying classes of operating systems. Common Vulnerabilities and Exposures (CVE) contain list of affected CPEs. For more information about CPE see [cpe.mitre.org](https://cpe.mitre.org/).
62598fab38b623060ffa9032
class Material(models.Model): <NEW_LINE> <INDENT> nome = models.CharField(max_length=200) <NEW_LINE> unidade = models.CharField(max_length=20) <NEW_LINE> valor_unitario = models.DecimalField( max_digits=10, decimal_places=2, default=0.0) <NEW_LINE> quantidade = models.DecimalField( max_digits=10, decimal_places=2, default=0.0) <NEW_LINE> cronograma = models.ForeignKey(Cronograma, on_delete=models.PROTECT) <NEW_LINE> deposito = models.ForeignKey(Deposito, on_delete=models.PROTECT) <NEW_LINE> categoria = models.ForeignKey(Categoria, on_delete=models.PROTECT) <NEW_LINE> date_added = models.DateTimeField( verbose_name='Data de criação', auto_now_add=True) <NEW_LINE> date_update = models.DateTimeField( verbose_name='Data de atualização', auto_now=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = 'Material' <NEW_LINE> verbose_name_plural = 'Materiais' <NEW_LINE> ordering = ['date_added'] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return f'{self.nome} - {self.cronograma.cliente}'
Materiais de determinado 'Deposito'
62598fab66656f66f7d5a389
class JSONResponseMixin(object): <NEW_LINE> <INDENT> content_type = 'application/json' <NEW_LINE> def render_to_response(self, context): <NEW_LINE> <INDENT> return self.get_json_response(self.convert_context_to_json(context)) <NEW_LINE> <DEDENT> def get_json_response(self, content, **httpresponse_kwargs): <NEW_LINE> <INDENT> return HttpResponse(content, content_type=self.content_type, **httpresponse_kwargs) <NEW_LINE> <DEDENT> def convert_context_to_json(self, context): <NEW_LINE> <INDENT> return JsonResponse(context)
Mixin to use with class-based views that provides an extra render_json_response function.
62598fab7d847024c075c35c
class LogPublisher: <NEW_LINE> <INDENT> synchronized = ["msg"] <NEW_LINE> def __init__( self, observerPublisher=None, publishPublisher=None, logBeginner=None, warningsModule=warnings, ): <NEW_LINE> <INDENT> if publishPublisher is None: <NEW_LINE> <INDENT> publishPublisher = NewPublisher() <NEW_LINE> if observerPublisher is None: <NEW_LINE> <INDENT> observerPublisher = publishPublisher <NEW_LINE> <DEDENT> <DEDENT> if observerPublisher is None: <NEW_LINE> <INDENT> observerPublisher = NewPublisher() <NEW_LINE> <DEDENT> self._observerPublisher = observerPublisher <NEW_LINE> self._publishPublisher = publishPublisher <NEW_LINE> self._legacyObservers = [] <NEW_LINE> if logBeginner is None: <NEW_LINE> <INDENT> beginnerPublisher = NewPublisher() <NEW_LINE> beginnerPublisher.addObserver(observerPublisher) <NEW_LINE> logBeginner = LogBeginner( beginnerPublisher, cast(BinaryIO, NullFile()), sys, warnings ) <NEW_LINE> <DEDENT> self._logBeginner = logBeginner <NEW_LINE> self._warningsModule = warningsModule <NEW_LINE> self._oldshowwarning = warningsModule.showwarning <NEW_LINE> self.showwarning = self._logBeginner.showwarning <NEW_LINE> <DEDENT> @property <NEW_LINE> def observers(self): <NEW_LINE> <INDENT> return [x.legacyObserver for x in self._legacyObservers] <NEW_LINE> <DEDENT> def _startLogging(self, other, setStdout): <NEW_LINE> <INDENT> wrapped = LegacyLogObserverWrapper(other) <NEW_LINE> self._legacyObservers.append(wrapped) <NEW_LINE> self._logBeginner.beginLoggingTo([wrapped], True, setStdout) <NEW_LINE> <DEDENT> def _stopLogging(self): <NEW_LINE> <INDENT> if self._warningsModule.showwarning == self.showwarning: <NEW_LINE> <INDENT> self._warningsModule.showwarning = self._oldshowwarning <NEW_LINE> <DEDENT> <DEDENT> def addObserver(self, other): <NEW_LINE> <INDENT> wrapped = LegacyLogObserverWrapper(other) <NEW_LINE> self._legacyObservers.append(wrapped) <NEW_LINE> self._observerPublisher.addObserver(wrapped) <NEW_LINE> <DEDENT> def removeObserver(self, other): <NEW_LINE> <INDENT> for observer in self._legacyObservers: <NEW_LINE> <INDENT> if observer.legacyObserver == other: <NEW_LINE> <INDENT> self._legacyObservers.remove(observer) <NEW_LINE> self._observerPublisher.removeObserver(observer) <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def msg(self, *message, **kw): <NEW_LINE> <INDENT> actualEventDict = cast(EventDict, (context.get(ILogContext) or {}).copy()) <NEW_LINE> actualEventDict.update(kw) <NEW_LINE> actualEventDict["message"] = message <NEW_LINE> actualEventDict["time"] = time.time() <NEW_LINE> if "isError" not in actualEventDict: <NEW_LINE> <INDENT> actualEventDict["isError"] = 0 <NEW_LINE> <DEDENT> _publishNew(self._publishPublisher, actualEventDict, textFromEventDict)
Class for singleton log message publishing.
62598fab3317a56b869be517
class KeyboardFeature(hid_gadget.HidFeature): <NEW_LINE> <INDENT> REPORT_DESC = hid_descriptors.ReportDescriptor( hid_descriptors.UsagePage(0x01), hid_descriptors.Usage(0x06), hid_descriptors.Collection( hid_constants.CollectionType.APPLICATION, hid_descriptors.UsagePage(0x07), hid_descriptors.UsageMinimum(224), hid_descriptors.UsageMaximum(231), hid_descriptors.LogicalMinimum(0, force_length=1), hid_descriptors.LogicalMaximum(1), hid_descriptors.ReportSize(1), hid_descriptors.ReportCount(8), hid_descriptors.Input(hid_descriptors.Data, hid_descriptors.Variable, hid_descriptors.Absolute), hid_descriptors.ReportCount(1), hid_descriptors.ReportSize(8), hid_descriptors.Input(hid_descriptors.Constant), hid_descriptors.ReportCount(5), hid_descriptors.ReportSize(1), hid_descriptors.UsagePage(0x08), hid_descriptors.UsageMinimum(1), hid_descriptors.UsageMaximum(5), hid_descriptors.Output(hid_descriptors.Data, hid_descriptors.Variable, hid_descriptors.Absolute), hid_descriptors.ReportCount(1), hid_descriptors.ReportSize(3), hid_descriptors.Output(hid_descriptors.Constant), hid_descriptors.ReportCount(6), hid_descriptors.ReportSize(8), hid_descriptors.LogicalMinimum(0, force_length=1), hid_descriptors.LogicalMaximum(101), hid_descriptors.UsagePage(0x07), hid_descriptors.UsageMinimum(0, force_length=1), hid_descriptors.UsageMaximum(101), hid_descriptors.Input(hid_descriptors.Data, hid_descriptors.Array) ) ) <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super(KeyboardFeature, self).__init__() <NEW_LINE> self._modifiers = 0 <NEW_LINE> self._keys = [0, 0, 0, 0, 0, 0] <NEW_LINE> self._leds = 0 <NEW_LINE> <DEDENT> def ModifierDown(self, modifier): <NEW_LINE> <INDENT> self._modifiers |= modifier <NEW_LINE> if self.IsConnected(): <NEW_LINE> <INDENT> self.SendReport(self.GetInputReport()) <NEW_LINE> <DEDENT> <DEDENT> def ModifierUp(self, modifier): <NEW_LINE> <INDENT> self._modifiers &= ~modifier <NEW_LINE> if self.IsConnected(): <NEW_LINE> <INDENT> self.SendReport(self.GetInputReport()) <NEW_LINE> <DEDENT> <DEDENT> def KeyDown(self, keycode): <NEW_LINE> <INDENT> free = self._keys.index(0) <NEW_LINE> self._keys[free] = keycode <NEW_LINE> if self.IsConnected(): <NEW_LINE> <INDENT> self.SendReport(self.GetInputReport()) <NEW_LINE> <DEDENT> <DEDENT> def KeyUp(self, keycode): <NEW_LINE> <INDENT> free = self._keys.index(keycode) <NEW_LINE> self._keys[free] = 0 <NEW_LINE> if self.IsConnected(): <NEW_LINE> <INDENT> self.SendReport(self.GetInputReport()) <NEW_LINE> <DEDENT> <DEDENT> def GetInputReport(self): <NEW_LINE> <INDENT> return struct.pack('BBBBBBBB', self._modifiers, 0, *self._keys) <NEW_LINE> <DEDENT> def GetOutputReport(self): <NEW_LINE> <INDENT> return struct.pack('B', self._leds) <NEW_LINE> <DEDENT> def SetOutputReport(self, data): <NEW_LINE> <INDENT> if len(data) >= 1: <NEW_LINE> <INDENT> self._leds, = struct.unpack('B', data) <NEW_LINE> <DEDENT> return True
HID feature implementation for a keyboard. REPORT_DESC provides an example HID report descriptor for a device including this functionality.
62598fab1f037a2d8b9e4087
class DigikamParser(AbstractParser): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.actions_dict['KEY_KP0'] = lambda key : os.system('xdotool key ctrl+0') <NEW_LINE> self.actions_dict['KEY_KP1'] = lambda key : os.system('xdotool key ctrl+1') <NEW_LINE> self.actions_dict['KEY_KP2'] = lambda key : os.system('xdotool key ctrl+2') <NEW_LINE> self.actions_dict['KEY_KP3'] = lambda key : os.system('xdotool key ctrl+3') <NEW_LINE> self.actions_dict['KEY_KP4'] = lambda key : os.system('xdotool key ctrl+4') <NEW_LINE> self.actions_dict['KEY_KP5'] = lambda key : os.system('xdotool key ctrl+5') <NEW_LINE> self.actions_dict['KEY_KP7'] = lambda key : os.system('xdotool key alt+0') <NEW_LINE> self.actions_dict['KEY_KP8'] = lambda key : os.system('xdotool key alt+1') <NEW_LINE> self.actions_dict['KEY_KP9'] = lambda key : os.system('xdotool key alt+2') <NEW_LINE> self.actions_dict['KEY_KPMINUS'] = lambda key : os.system('xdotool key alt+3') <NEW_LINE> self.actions_dict['KEY_KPPLUS'] = lambda key : os.system('xdotool key Left') <NEW_LINE> self.actions_dict['KEY_ENTER'] = lambda key : os.system('xdotool key Right')
0-5 : giving stars to photos 7,8,9,- : giving flags to photos + : arrow left Enter : arrow right Args: AbstractParser ([type]): [description]
62598fab4f6381625f19948b
class Merge(Abstraction): <NEW_LINE> <INDENT> GROUP_SIZE = 16 <NEW_LINE> Counter = itertools.count() <NEW_LINE> def __init__(self, inputs, outputs, function=None, includes=None, native=False, group=None, collect=False, local=True): <NEW_LINE> <INDENT> Abstraction.__init__(self, function or 'cat {IN} > {OUT}', inputs, outputs, includes, native, group or Merge.GROUP_SIZE, collect, local) <NEW_LINE> <DEDENT> @cache_generation <NEW_LINE> def _generate(self): <NEW_LINE> <INDENT> with self: <NEW_LINE> <INDENT> debug(D_ABSTRACTION, 'Generating Abstraction {0}'.format(self)) <NEW_LINE> function = parse_function(self.function) <NEW_LINE> inputs = parse_input_list(self.inputs) <NEW_LINE> includes = parse_input_list(self.includes) <NEW_LINE> output = self.outputs <NEW_LINE> nest = CurrentNest() <NEW_LINE> if not os.path.isabs(output): <NEW_LINE> <INDENT> output = os.path.join(nest.work_dir, output) <NEW_LINE> <DEDENT> while len(inputs) > self.group: <NEW_LINE> <INDENT> next_inputs = [] <NEW_LINE> for group in groups(inputs, self.group): <NEW_LINE> <INDENT> output_file = next(nest.stash) <NEW_LINE> next_inputs.append(output_file) <NEW_LINE> with Options(local=self.options.local, collect=group if self.collect else None): <NEW_LINE> <INDENT> yield function(group, output_file, None, includes) <NEW_LINE> <DEDENT> <DEDENT> inputs = next_inputs <NEW_LINE> <DEDENT> with Options(local=self.options.local, collect=inputs if self.collect else None): <NEW_LINE> <INDENT> yield function(inputs, output, None, includes)
Weaver Merge Abstraction.
62598fab1f5feb6acb162bb9
class CertValidatingHTTPSConnection(http_client.HTTPConnection): <NEW_LINE> <INDENT> default_port = http_client.HTTPS_PORT <NEW_LINE> def __init__(self, host, port=default_port, key_file=None, cert_file=None, ca_certs=None, strict=None, **kwargs): <NEW_LINE> <INDENT> if six.PY2: <NEW_LINE> <INDENT> kwargs['strict'] = strict <NEW_LINE> <DEDENT> http_client.HTTPConnection.__init__(self, host=host, port=port, **kwargs) <NEW_LINE> self.key_file = key_file <NEW_LINE> self.cert_file = cert_file <NEW_LINE> self.ca_certs = ca_certs <NEW_LINE> <DEDENT> def connect(self): <NEW_LINE> <INDENT> if hasattr(self, "timeout"): <NEW_LINE> <INDENT> sock = socket.create_connection((self.host, self.port), self.timeout) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sock = socket.create_connection((self.host, self.port)) <NEW_LINE> <DEDENT> msg = "wrapping ssl socket; " <NEW_LINE> if self.ca_certs: <NEW_LINE> <INDENT> msg += "CA certificate file=%s" % self.ca_certs <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> msg += "using system provided SSL certs" <NEW_LINE> <DEDENT> mssapi.log.debug(msg) <NEW_LINE> self.sock = ssl.wrap_socket(sock, keyfile=self.key_file, certfile=self.cert_file, cert_reqs=ssl.CERT_REQUIRED, ca_certs=self.ca_certs) <NEW_LINE> cert = self.sock.getpeercert() <NEW_LINE> hostname = self.host.split(':', 0)[0] <NEW_LINE> if not ValidateCertificateHostname(cert, hostname): <NEW_LINE> <INDENT> raise InvalidCertificateException(hostname, cert, 'remote hostname "%s" does not match ' 'certificate' % hostname)
An HTTPConnection that connects over SSL and validates certificates.
62598fab56ac1b37e6302185
@typehints.with_input_types(Union[pd.DataFrame, pd.Series]) <NEW_LINE> class UnbatchPandas(beam.PTransform): <NEW_LINE> <INDENT> def __init__(self, proxy, include_indexes=False): <NEW_LINE> <INDENT> self._proxy = proxy <NEW_LINE> self._include_indexes = include_indexes <NEW_LINE> <DEDENT> def expand(self, pcoll): <NEW_LINE> <INDENT> return pcoll | _unbatch_transform(self._proxy, self._include_indexes)
A transform that explodes a PCollection of DataFrame or Series. DataFrame is converterd to a schema-aware PCollection, while Series is converted to its underlying type. Args: include_indexes: (optional, default: False) When unbatching a DataFrame if include_indexes=True, attempt to include index columns in the output schema for expanded DataFrames. Raises an error if any of the index levels are unnamed (name=None), or if any of the names are not unique among all column and index names.
62598fab6e29344779b005f6
class LinearSoftmaxlayer(object): <NEW_LINE> <INDENT> def __init__(self,numin,numout,params): <NEW_LINE> <INDENT> self.numin = numin <NEW_LINE> self.numout = numout <NEW_LINE> self.params = params <NEW_LINE> self.linearlayer = Linearlayer(self.numin,self.numout,self.params) <NEW_LINE> self.softmax = Softmax(self.numout) <NEW_LINE> <DEDENT> def fprop(self,input): <NEW_LINE> <INDENT> self.activities = self.linearlayer.fprop(input) <NEW_LINE> return self.softmax.fprop(self.activities) <NEW_LINE> <DEDENT> def bprop(self,d_output,input): <NEW_LINE> <INDENT> self.d_activities = self.softmax.bprop(d_output,self.activities) <NEW_LINE> return self.linearlayer.bprop(self.d_activities,input) <NEW_LINE> <DEDENT> def grad(self,d_output,input): <NEW_LINE> <INDENT> grad2 = self.softmax.grad(d_output,self.activities) <NEW_LINE> grad1 = self.linearlayer.grad(self.d_activities,input) <NEW_LINE> return concatenate((grad1,grad2))
Linear layer followed by a softmax. (AKA multinomial logit model).
62598fab4527f215b58e9e7b
class ContainerProjectsLocationsClustersNodePoolsListRequest(_messages.Message): <NEW_LINE> <INDENT> clusterId = _messages.StringField(1) <NEW_LINE> parent = _messages.StringField(2, required=True) <NEW_LINE> projectId = _messages.StringField(3) <NEW_LINE> version = _messages.StringField(4) <NEW_LINE> zone = _messages.StringField(5)
A ContainerProjectsLocationsClustersNodePoolsListRequest object. Fields: clusterId: Deprecated. The name of the cluster. This field has been deprecated and replaced by the parent field. parent: The parent (project, location, cluster id) where the node pools will be listed. Specified in the format 'projects/*/locations/*/clusters/*'. projectId: Deprecated. The Google Developers Console [project ID or project number](https://developers.google.com/console/help/new/#projectnumber). This field has been deprecated and replaced by the parent field. version: API request version that initiates this operation. zone: Deprecated. The name of the Google Compute Engine [zone](/compute/docs/zones#available) in which the cluster resides. This field has been deprecated and replaced by the parent field.
62598fab435de62698e9bd90
class Database: <NEW_LINE> <INDENT> def __init__(self, config, token=None): <NEW_LINE> <INDENT> self._config = config <NEW_LINE> self._token = token <NEW_LINE> <DEDENT> @property <NEW_LINE> def config(self): <NEW_LINE> <INDENT> return self._config <NEW_LINE> <DEDENT> def submit(self, data, verbose=False): <NEW_LINE> <INDENT> raise NotImplementedError("Database.submit() must be implemented") <NEW_LINE> <DEDENT> def submit_build(self, meta, verbose=False): <NEW_LINE> <INDENT> raise NotImplementedError("Database.submit_build() not implemented") <NEW_LINE> <DEDENT> def submit_test(self, results, verbose=False): <NEW_LINE> <INDENT> raise NotImplementedError("Database.submit_test() not implemented") <NEW_LINE> <DEDENT> def _print_http_error(self, http_error, verbose=False): <NEW_LINE> <INDENT> print(http_error) <NEW_LINE> if verbose: <NEW_LINE> <INDENT> errors = json.loads(http_error.response.content).get("errors", []) <NEW_LINE> for err in errors: <NEW_LINE> <INDENT> print(err)
KernelCI database interface
62598fabbe383301e0253793
class App(pyacc.AccCommandLineApp): <NEW_LINE> <INDENT> def build_arg_parser(self): <NEW_LINE> <INDENT> super(App, self).build_arg_parser() <NEW_LINE> self.parser.add_argument('filenames', metavar='FILE', nargs='+', type=str, help='path to file to push') <NEW_LINE> <DEDENT> def main(self): <NEW_LINE> <INDENT> for filename in self.args.filenames: <NEW_LINE> <INDENT> result = self.acc.upload_file(filename) <NEW_LINE> print("\t".join([str(result["id"]), result["name"], result["modified"], str(result["size"])]))
Upload files to config server. Note that the file upload option needs to be enabled on the Config Server (agent.file.management.enabled=true in APMCommandCenterServer/config/apmccsrv.properties)
62598fabb7558d58954635c3
class parser(): <NEW_LINE> <INDENT> def __init__(self, animeName="", action='d', siteParser=bestanime, hostParser='trollvideo'): <NEW_LINE> <INDENT> self.animeName = animeName <NEW_LINE> self.episodes = None <NEW_LINE> self.episodeUrls = None <NEW_LINE> self.currentEpisode = None <NEW_LINE> self.prevEpisode = None <NEW_LINE> self.nextEpisode = None <NEW_LINE> self.mirrors = None <NEW_LINE> self.mirrorUrls = None <NEW_LINE> self.host = None <NEW_LINE> self.siteParser = siteParser <NEW_LINE> <DEDENT> def __setEpisodes(self): <NEW_LINE> <INDENT> self.episodes = self.siteParser.get_episodes( self.siteParser.search_page(self.animeName)) <NEW_LINE> <DEDENT> def __setEpisodeUrls(self): <NEW_LINE> <INDENT> self.episodeUrls = self.siteParser.get_episode_url( self.siteParser.search_page(self.animeName)) <NEW_LINE> <DEDENT> def __setMirrors(self, episodeChoice): <NEW_LINE> <INDENT> if type(episodeChoice) is int: <NEW_LINE> <INDENT> self.mirrors = self.siteParser.getMirrors(self.episodeUrls[episodeChoice]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.mirrors = self.siteParser.getMirrors(episodeChoice) <NEW_LINE> <DEDENT> <DEDENT> def __setMirrorUrls(self, episodeChoice): <NEW_LINE> <INDENT> if type(episodeChoice) is int: <NEW_LINE> <INDENT> self.mirrorUrls = self.siteParser.getMirrorUrls(self.episodeUrls[episodeChoice]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.mirrorUrls = self.siteParser.getMirrorUrls(episodeChoice) <NEW_LINE> <DEDENT> <DEDENT> def __setHost(self, mirrorChoice): <NEW_LINE> <INDENT> self.host = self.siteParser.getHostingSite(self.mirrorUrls[mirrorChoice]) <NEW_LINE> <DEDENT> def __setNextPrev(self, episodeChoice): <NEW_LINE> <INDENT> if type(episodeChoice) is int: <NEW_LINE> <INDENT> self.prevEpisode, self.nextEpisode = self.siteParser.getNextPrev( self.episodeUrls[episodeChoice]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.prevEpisode, self.nextEpisode = self.siteParser.getNextPrev( episodeChoice) <NEW_LINE> <DEDENT> <DEDENT> def setAnime(self, animeName): <NEW_LINE> <INDENT> self.animeName = self.siteParser.searchable_string(animeName) <NEW_LINE> self.__setEpisodes() <NEW_LINE> self.__setEpisodeUrls() <NEW_LINE> <DEDENT> def getEpisodes(self): <NEW_LINE> <INDENT> li = [] <NEW_LINE> selector = 0 <NEW_LINE> for episode in self.episodes: <NEW_LINE> <INDENT> li.append((selector, episode)) <NEW_LINE> selector = selector + 1 <NEW_LINE> <DEDENT> return li <NEW_LINE> <DEDENT> def getMirrors(self): <NEW_LINE> <INDENT> li = [] <NEW_LINE> selector = 0 <NEW_LINE> for mirror in self.mirrors: <NEW_LINE> <INDENT> li.append((selector, mirror)) <NEW_LINE> selector = selector + 1 <NEW_LINE> <DEDENT> return li <NEW_LINE> <DEDENT> def playEpisode(self, episodeChoice, selection='', mirrorChoice=0): <NEW_LINE> <INDENT> self.__setNextPrev(episodeChoice) <NEW_LINE> self.__setMirrors(episodeChoice) <NEW_LINE> self.__setMirrorUrls(episodeChoice) <NEW_LINE> self.__setHost(mirrorChoice) <NEW_LINE> return hostParser.hostParser(self.host)
Wrapper around the actual site parser plugins. This is the class that you'll be interacting with instead of the actual parsers. This makes it easy to to use any plugins while still using the same class and methods.
62598fab7b180e01f3e4901e
class CompositeBuilder(SCons.Util.Proxy): <NEW_LINE> <INDENT> def __init__(self, builder, cmdgen): <NEW_LINE> <INDENT> if __debug__: logInstanceCreation(self, 'Builder.CompositeBuilder') <NEW_LINE> SCons.Util.Proxy.__init__(self, builder) <NEW_LINE> self.cmdgen = cmdgen <NEW_LINE> self.builder = builder <NEW_LINE> <DEDENT> def add_action(self, suffix, action): <NEW_LINE> <INDENT> self.cmdgen.add_action(suffix, action) <NEW_LINE> self.set_src_suffix(self.cmdgen.src_suffixes())
A Builder Proxy whose main purpose is to always have a DictCmdGenerator as its action, and to provide access to the DictCmdGenerator's add_action() method.
62598fab92d797404e388b31
class NoDoubleSlashes(MiddlewareMixin): <NEW_LINE> <INDENT> def process_request(self, request): <NEW_LINE> <INDENT> if '//' in request.path: <NEW_LINE> <INDENT> new_path = multislash_re.sub('/', request.path) <NEW_LINE> return redirect(new_path) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None
123-reg redirects djangopeople.com/blah to djangopeople.net//blah - this middleware eliminates multiple slashes from incoming requests.
62598fab01c39578d7f12d19
class Getter(AccessorBase): <NEW_LINE> <INDENT> __slots__ = add_to_slots('parent_xpath', 'tag_name') <NEW_LINE> def __call__(self): <NEW_LINE> <INDENT> element = self.element_by_parent(self.parent_xpath, self.tag_name, create=False) <NEW_LINE> return int(element.text)
Retrieve text on element and convert to int
62598fab097d151d1a2c0fc3
class FeatureNet: <NEW_LINE> <INDENT> def __init__(self, space, extension=None): <NEW_LINE> <INDENT> self.space = space <NEW_LINE> self.extension = extension <NEW_LINE> <DEDENT> def prepare(self, xs): <NEW_LINE> <INDENT> return np.asarray(xs) <NEW_LINE> <DEDENT> def build(self): <NEW_LINE> <INDENT> input_placeholder, feature = self._build() <NEW_LINE> if self.extension: <NEW_LINE> <INDENT> feature = self.extension(feature) <NEW_LINE> <DEDENT> return input_placeholder, feature <NEW_LINE> <DEDENT> def _build(self): <NEW_LINE> <INDENT> raise NotImplementedError
Feature vector generation network for `gym.Space` samples.
62598fab63b5f9789fe85100
class AstroFCModel(astro_model.AstroModel): <NEW_LINE> <INDENT> def _build_local_fc_layers(self, inputs, hparams, scope): <NEW_LINE> <INDENT> if hparams.num_local_layers == 0: <NEW_LINE> <INDENT> return inputs <NEW_LINE> <DEDENT> net = inputs <NEW_LINE> with tf.variable_scope(scope): <NEW_LINE> <INDENT> if hparams.translation_delta > 0: <NEW_LINE> <INDENT> kernel_size = inputs.shape.as_list()[1] - 2 * hparams.translation_delta <NEW_LINE> net = tf.expand_dims(net, -1) <NEW_LINE> net = tf.layers.conv1d( inputs=net, filters=hparams.local_layer_size, kernel_size=kernel_size, padding="valid", activation=tf.nn.relu, name="conv1d") <NEW_LINE> if hparams.pooling_type == "max": <NEW_LINE> <INDENT> net = tf.reduce_max(net, axis=1, name="max_pool") <NEW_LINE> <DEDENT> elif hparams.pooling_type == "avg": <NEW_LINE> <INDENT> net = tf.reduce_mean(net, axis=1, name="avg_pool") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("Unrecognized pooling_type: {}".format( hparams.pooling_type)) <NEW_LINE> <DEDENT> remaining_layers = hparams.num_local_layers - 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> remaining_layers = hparams.num_local_layers <NEW_LINE> <DEDENT> for i in range(remaining_layers): <NEW_LINE> <INDENT> net = tf.contrib.layers.fully_connected( inputs=net, num_outputs=hparams.local_layer_size, activation_fn=tf.nn.relu, scope="fully_connected_{}".format(i + 1)) <NEW_LINE> if hparams.dropout_rate > 0: <NEW_LINE> <INDENT> net = tf.layers.dropout( net, hparams.dropout_rate, training=self.is_training) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return net <NEW_LINE> <DEDENT> def build_time_series_hidden_layers(self): <NEW_LINE> <INDENT> time_series_hidden_layers = {} <NEW_LINE> for name, time_series in self.time_series_features.items(): <NEW_LINE> <INDENT> time_series_hidden_layers[name] = self._build_local_fc_layers( inputs=time_series, hparams=self.hparams.time_series_hidden[name], scope=name + "_hidden") <NEW_LINE> <DEDENT> self.time_series_hidden_layers = time_series_hidden_layers
A model for classifying light curves using fully connected layers.
62598fabd486a94d0ba2bf68
class IPMAWeather(WeatherEntity): <NEW_LINE> <INDENT> def __init__(self, station, config): <NEW_LINE> <INDENT> self._station_name = config.get(CONF_NAME, station.local) <NEW_LINE> self._station = station <NEW_LINE> self._condition = None <NEW_LINE> self._forecast = None <NEW_LINE> self._description = None <NEW_LINE> <DEDENT> @Throttle(MIN_TIME_BETWEEN_UPDATES) <NEW_LINE> async def async_update(self): <NEW_LINE> <INDENT> with async_timeout.timeout(10, loop=self.hass.loop): <NEW_LINE> <INDENT> self._condition = await self._station.observation() <NEW_LINE> _LOGGER.debug("Updating station %s, condition %s", self._station.local, self._condition) <NEW_LINE> self._forecast = await self._station.forecast() <NEW_LINE> self._description = self._forecast[0].description <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def attribution(self): <NEW_LINE> <INDENT> return ATTRIBUTION <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._station_name <NEW_LINE> <DEDENT> @property <NEW_LINE> def condition(self): <NEW_LINE> <INDENT> return next((k for k, v in CONDITION_CLASSES.items() if self._forecast[0].idWeatherType in v), None) <NEW_LINE> <DEDENT> @property <NEW_LINE> def temperature(self): <NEW_LINE> <INDENT> return self._condition.temperature <NEW_LINE> <DEDENT> @property <NEW_LINE> def pressure(self): <NEW_LINE> <INDENT> return self._condition.pressure <NEW_LINE> <DEDENT> @property <NEW_LINE> def humidity(self): <NEW_LINE> <INDENT> return self._condition.humidity <NEW_LINE> <DEDENT> @property <NEW_LINE> def wind_speed(self): <NEW_LINE> <INDENT> return self._condition.windspeed <NEW_LINE> <DEDENT> @property <NEW_LINE> def wind_bearing(self): <NEW_LINE> <INDENT> return self._condition.winddirection <NEW_LINE> <DEDENT> @property <NEW_LINE> def temperature_unit(self): <NEW_LINE> <INDENT> return TEMP_CELSIUS <NEW_LINE> <DEDENT> @property <NEW_LINE> def forecast(self): <NEW_LINE> <INDENT> if self._forecast: <NEW_LINE> <INDENT> fcdata_out = [] <NEW_LINE> for data_in in self._forecast: <NEW_LINE> <INDENT> data_out = {} <NEW_LINE> data_out[ATTR_FORECAST_TIME] = data_in.forecastDate <NEW_LINE> data_out[ATTR_FORECAST_CONDITION] = next((k for k, v in CONDITION_CLASSES.items() if int(data_in.idWeatherType) in v), None) <NEW_LINE> data_out[ATTR_FORECAST_TEMP_LOW] = data_in.tMin <NEW_LINE> data_out[ATTR_FORECAST_TEMP] = data_in.tMax <NEW_LINE> data_out[ATTR_FORECAST_PRECIPITATION] = data_in.precipitaProb <NEW_LINE> fcdata_out.append(data_out) <NEW_LINE> <DEDENT> return fcdata_out <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def device_state_attributes(self): <NEW_LINE> <INDENT> data = dict() <NEW_LINE> if self._description: <NEW_LINE> <INDENT> data[ATTR_WEATHER_DESCRIPTION] = self._description <NEW_LINE> <DEDENT> return data
Representation of a weather condition.
62598fab7b25080760ed7448
class VerletListHadressLennardJonesCappedLocal(InteractionLocal, interaction_VerletListHadressLennardJonesCapped): <NEW_LINE> <INDENT> def __init__(self, vl, fixedtupleList): <NEW_LINE> <INDENT> if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup(): <NEW_LINE> <INDENT> cxxinit(self, interaction_VerletListHadressLennardJonesCapped, vl, fixedtupleList) <NEW_LINE> <DEDENT> <DEDENT> def setPotentialAT(self, type1, type2, potential): <NEW_LINE> <INDENT> if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup(): <NEW_LINE> <INDENT> self.cxxclass.setPotentialAT(self, type1, type2, potential) <NEW_LINE> <DEDENT> <DEDENT> def setPotentialCG(self, type1, type2, potential): <NEW_LINE> <INDENT> if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup(): <NEW_LINE> <INDENT> self.cxxclass.setPotentialCG(self, type1, type2, potential) <NEW_LINE> <DEDENT> <DEDENT> def getPotentialAT(self, type1, type2): <NEW_LINE> <INDENT> if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup(): <NEW_LINE> <INDENT> return self.cxxclass.getPotentialAT(self, type1, type2) <NEW_LINE> <DEDENT> <DEDENT> def getPotentialCG(self, type1, type2): <NEW_LINE> <INDENT> if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup(): <NEW_LINE> <INDENT> return self.cxxclass.getPotentialCG(self, type1, type2)
The (local) Lennard Jones interaction using Verlet lists.
62598fab627d3e7fe0e06e47
class GitHubPullRequestBackend(GitHubBackend): <NEW_LINE> <INDENT> def pull(self): <NEW_LINE> <INDENT> self.github_repository.get_issues(state='all') <NEW_LINE> return {}
A backend where change requests are stored as GitHub Pull Requests.
62598fab379a373c97d98fad
class ListFeatures(object): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def defaultFeatures(cls): <NEW_LINE> <INDENT> features = cls() <NEW_LINE> features.setCookieService(True) <NEW_LINE> features.setColumnSearch(True, True) <NEW_LINE> features.setColumnShowHide(True) <NEW_LINE> features.setSearchDialog(True) <NEW_LINE> features.setCsvExport(True) <NEW_LINE> features.setGlobalSearch(False, '') <NEW_LINE> features.setGlobalSort(False, '') <NEW_LINE> features.setHideHeaders(False) <NEW_LINE> return features <NEW_LINE> <DEDENT> def __init__(self): <NEW_LINE> <INDENT> self._cookie_service = { 'enabled': False, } <NEW_LINE> self._column_search = { 'enabled': False, 'regexp': False } <NEW_LINE> self._columns_show_hide = { 'enabled': False } <NEW_LINE> self._search_dialog = { 'enabled': False } <NEW_LINE> self._csv_export = { 'enabled': False } <NEW_LINE> self._global_search = { 'enabled': False, 'element_path': '' } <NEW_LINE> self._global_sort = { 'enabled': False, 'element_paths': '' } <NEW_LINE> self._hide_headers = { 'enabled': False } <NEW_LINE> <DEDENT> def setCookieService(self, enabled): <NEW_LINE> <INDENT> self._cookie_service['enabled'] = enabled <NEW_LINE> <DEDENT> def setColumnSearch(self, enabled, regexp): <NEW_LINE> <INDENT> self._column_search['enabled'] = enabled <NEW_LINE> self._column_search['regexp'] = regexp <NEW_LINE> <DEDENT> def setColumnShowHide(self, enabled): <NEW_LINE> <INDENT> self._columns_show_hide['enabled'] = enabled <NEW_LINE> <DEDENT> def setSearchDialog(self, enabled): <NEW_LINE> <INDENT> self._search_dialog['enabled'] = enabled <NEW_LINE> <DEDENT> def setCsvExport(self, enabled): <NEW_LINE> <INDENT> self._csv_export['enabled'] = enabled <NEW_LINE> <DEDENT> def setGlobalSearch(self, enabled, element_path): <NEW_LINE> <INDENT> if enabled: <NEW_LINE> <INDENT> if not element_path: <NEW_LINE> <INDENT> logging.warning('Trying to enable global search with no element_path') <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if element_path: <NEW_LINE> <INDENT> logging.warning('Non empty element_path in disabled global search') <NEW_LINE> <DEDENT> <DEDENT> self._global_search['enabled'] = enabled <NEW_LINE> self._global_search['element_path'] = element_path <NEW_LINE> <DEDENT> def setGlobalSort(self, enabled, element_paths): <NEW_LINE> <INDENT> if enabled: <NEW_LINE> <INDENT> if not element_paths: <NEW_LINE> <INDENT> logging.warning('Trying to enable global sort with no element_paths') <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if element_paths: <NEW_LINE> <INDENT> logging.warning('Non empty element_paths in disabled global sort') <NEW_LINE> <DEDENT> <DEDENT> self._global_sort['enabled'] = enabled <NEW_LINE> self._global_sort['element_paths'] = element_paths <NEW_LINE> <DEDENT> def setHideHeaders(self, enabled): <NEW_LINE> <INDENT> self._hide_headers['enabled'] = enabled <NEW_LINE> <DEDENT> def get(self): <NEW_LINE> <INDENT> return { 'cookie_service': self._cookie_service, 'column_search': self._column_search, 'columns_show_hide': self._columns_show_hide, 'search_dialog': self._search_dialog, 'csv_export': self._csv_export, 'global_search': self._global_search, 'global_sort': self._global_sort, 'hide_headers': self._hide_headers, }
Represents features of the list which define, for instance, which elements should be displayed.
62598fab7047854f4633f374
class NoBodyError(Error): <NEW_LINE> <INDENT> pass
Error that indicates a send message request has no body.
62598fab99fddb7c1ca62db6
class CreateReviews(Command): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def setup_parser(subparser): <NEW_LINE> <INDENT> subparser.add_argument('--user', default='test1', help='username to submit as') <NEW_LINE> subparser.add_argument('--identity', default=None, help='ssh identity file used to authenticate as ' 'user') <NEW_LINE> subparser.add_argument('--approve', action='store_true', help='Mark the changes as approved') <NEW_LINE> subparser.add_argument('--queue', action='store_true', help='Mark the changes for merge') <NEW_LINE> subparser.add_argument('--keep-clone', action='store_true', help="don't delete the clone from the local FS") <NEW_LINE> subparser.add_argument('--repo-path', default=None, help='clone the test repo to this location') <NEW_LINE> subparser.add_argument('--branch', default='master', help='target branch') <NEW_LINE> subparsers = subparser.add_subparsers(dest='subcommand') <NEW_LINE> simple = subparsers.add_parser('simple') <NEW_LINE> simple.add_argument('num_features', type=int, help='Number of feature branches to create/submit') <NEW_LINE> pass_fail = subparsers.add_parser('pass-fail') <NEW_LINE> pass_fail.add_argument('changes', nargs='+', choices=['P', 'F']) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def run_args(cls, config, args): <NEW_LINE> <INDENT> if args.queue: <NEW_LINE> <INDENT> args.approve = True <NEW_LINE> <DEDENT> if args.repo_path is not None: <NEW_LINE> <INDENT> args.keep_clone = True <NEW_LINE> <DEDENT> config['gerrit.rest.username'] = 'test1' <NEW_LINE> config['gerrit.ssh.username'] = 'test1' <NEW_LINE> gerrit = common.GerritRest(**config['gerrit.rest']) <NEW_LINE> if args.subcommand == 'simple': <NEW_LINE> <INDENT> automation.create_reviews(config, gerrit, args) <NEW_LINE> <DEDENT> elif args.subcommand == 'pass-fail': <NEW_LINE> <INDENT> automation.create_pass_fail(config, gerrit, args) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logging.error('Unrecognized subcommand %s', args.subcommand)
Create some non-conflicting feature branches based off of master, submit each as a review, and optionally mark them approved and queued.
62598fab8e7ae83300ee903d
class Solution: <NEW_LINE> <INDENT> def bstToDoublyList(self, root): <NEW_LINE> <INDENT> dummy = DoublyListNode(0) <NEW_LINE> self.cur = dummy <NEW_LINE> self.helper(root) <NEW_LINE> return dummy.next <NEW_LINE> <DEDENT> def helper(self, node): <NEW_LINE> <INDENT> if node is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.helper(node.left) <NEW_LINE> newListNode = DoublyListNode(node.val) <NEW_LINE> self.cur.next = newListNode <NEW_LINE> newListNode.prev = self.cur <NEW_LINE> self.cur = newListNode <NEW_LINE> self.helper(node.right) <NEW_LINE> return
@param root: The root of tree @return: the head of doubly list node
62598fabadb09d7d5dc0a526
class MultiFieldMultiSliceAliasTest(BfRuntimeTest): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> client_id = 0 <NEW_LINE> p4_name = "tna_field_slice" <NEW_LINE> BfRuntimeTest.setUp(self, client_id, p4_name) <NEW_LINE> self.table_name = "SwitchIngress.forward_multi_field_multi_slice_alias" <NEW_LINE> seed = random.randint(1, 65535) <NEW_LINE> random.seed(seed) <NEW_LINE> logger.info("seed used is %d", seed) <NEW_LINE> self.port_field_name = "ig_intr_md.ingress_port" <NEW_LINE> <DEDENT> def runTest(self): <NEW_LINE> <INDENT> bfrt_info = self.interface.bfrt_info_get("tna_field_slice") <NEW_LINE> table_obj = bfrt_info.table_get(self.table_name) <NEW_LINE> MultiSliceTestHelper(self, table_obj, exm_0_field_name="hdr.ipv6.src_addr[53:19]", tcam_field_name="ipv6.srcaddr_106_80_", lpm_field_name="hdr.ipv6.dst_addr[81:60]", exm_1_field_name="ipv6.dstaddr_23_9_", is_multi_field=True)
@brief This test adds entries to the table, sends packets which should miss and hit the entries and verifies, reads back the entries and verifies and finally deletes the entries
62598fab7047854f4633f375
class _TiffParser(object): <NEW_LINE> <INDENT> def __init__(self, ifd_entries): <NEW_LINE> <INDENT> super(_TiffParser, self).__init__() <NEW_LINE> self._ifd_entries = ifd_entries <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def parse(cls, stream): <NEW_LINE> <INDENT> stream_rdr = cls._make_stream_reader(stream) <NEW_LINE> ifd0_offset = stream_rdr.read_long(4) <NEW_LINE> ifd_entries = _IfdEntries.from_stream(stream_rdr, ifd0_offset) <NEW_LINE> return cls(ifd_entries) <NEW_LINE> <DEDENT> @property <NEW_LINE> def horz_dpi(self): <NEW_LINE> <INDENT> return self._dpi(TIFF_TAG.X_RESOLUTION) <NEW_LINE> <DEDENT> @property <NEW_LINE> def vert_dpi(self): <NEW_LINE> <INDENT> return self._dpi(TIFF_TAG.Y_RESOLUTION) <NEW_LINE> <DEDENT> @property <NEW_LINE> def px_height(self): <NEW_LINE> <INDENT> return self._ifd_entries.get(TIFF_TAG.IMAGE_LENGTH) <NEW_LINE> <DEDENT> @property <NEW_LINE> def px_width(self): <NEW_LINE> <INDENT> return self._ifd_entries.get(TIFF_TAG.IMAGE_WIDTH) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _detect_endian(cls, stream): <NEW_LINE> <INDENT> stream.seek(0) <NEW_LINE> endian_str = stream.read(2) <NEW_LINE> return BIG_ENDIAN if endian_str == b'MM' else LITTLE_ENDIAN <NEW_LINE> <DEDENT> def _dpi(self, resolution_tag): <NEW_LINE> <INDENT> if resolution_tag not in self._ifd_entries: <NEW_LINE> <INDENT> return 72 <NEW_LINE> <DEDENT> resolution_unit = self._ifd_entries[TIFF_TAG.RESOLUTION_UNIT] <NEW_LINE> if resolution_unit == 1: <NEW_LINE> <INDENT> return 72 <NEW_LINE> <DEDENT> units_per_inch = 1 if resolution_unit == 2 else 2.54 <NEW_LINE> dots_per_unit = self._ifd_entries[resolution_tag] <NEW_LINE> return int(round(dots_per_unit * units_per_inch)) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _make_stream_reader(cls, stream): <NEW_LINE> <INDENT> endian = cls._detect_endian(stream) <NEW_LINE> return StreamReader(stream, endian)
Parses a TIFF image stream to extract the image properties found in its main image file directory (IFD)
62598fab0c0af96317c5631e
class LineEndingTests(EditorConfigTestCase): <NEW_LINE> <INDENT> def test_check_crlf(self): <NEW_LINE> <INDENT> self.assertFileErrors('crlf_valid.txt', []) <NEW_LINE> self.assertFileErrors('crlf_invalid_cr.txt', [ "Final newline found", "Incorrect line ending found: cr", ]) <NEW_LINE> self.assertFileErrors('crlf_invalid_lf.txt', [ "Final newline found", "Incorrect line ending found: lf", ]) <NEW_LINE> <DEDENT> def test_check_cr(self): <NEW_LINE> <INDENT> self.assertFileErrors('cr_valid.txt', []) <NEW_LINE> self.assertFileErrors('cr_invalid_lf.txt', [ "Incorrect line ending found: lf", ]) <NEW_LINE> self.assertFileErrors('cr_invalid_crlf.txt', [ "Incorrect line ending found: crlf", ]) <NEW_LINE> <DEDENT> def test_check_lf(self): <NEW_LINE> <INDENT> self.assertFileErrors('lf_valid.txt', []) <NEW_LINE> self.assertFileErrors('lf_invalid_cr.txt', [ "Incorrect line ending found: cr", ]) <NEW_LINE> self.assertFileErrors('lf_invalid_crlf.txt', [ "Incorrect line ending found: crlf", "No final newline found", ]) <NEW_LINE> <DEDENT> def test_empty_file(self): <NEW_LINE> <INDENT> self.assertFileErrors('lf_empty.txt', [])
Tests for EditorConfigChecker line endings
62598fab7d847024c075c35f
class Permission(AbsPermission): <NEW_LINE> <INDENT> def __init__(self, perm=""): <NEW_LINE> <INDENT> self._perm = perm <NEW_LINE> <DEDENT> @property <NEW_LINE> def permission(self): <NEW_LINE> <INDENT> return self._perm <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self._perm <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self._perm
Permissions class
62598fab6aa9bd52df0d4e64
class Deck(Hand): <NEW_LINE> <INDENT> def populate(self): <NEW_LINE> <INDENT> self.cards = [] <NEW_LINE> for suit in Card.SUITS: <NEW_LINE> <INDENT> for rank in Card.RANKS: <NEW_LINE> <INDENT> self.add(Card(rank, suit)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def shuffle(self): <NEW_LINE> <INDENT> import random <NEW_LINE> random.shuffle(self.cards) <NEW_LINE> <DEDENT> def deal(self, hands, per_hand = 1): <NEW_LINE> <INDENT> for round in range(per_hand): <NEW_LINE> <INDENT> for hand in hands: <NEW_LINE> <INDENT> if self.cards: <NEW_LINE> <INDENT> top_card = self.cards[0] <NEW_LINE> self.give(top_card, hand) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("Не могу больше сдавать: карты кончились!")
Колода игральных карт
62598fab4527f215b58e9e7d
class SDSSLogger(logging.Logger): <NEW_LINE> <INDENT> def __init__(self, name): <NEW_LINE> <INDENT> super(SDSSLogger, self).__init__(name) <NEW_LINE> <DEDENT> def init(self, log_level=logging.INFO, capture_warnings=True): <NEW_LINE> <INDENT> self.setLevel(logging.DEBUG) <NEW_LINE> self.sh = logging.StreamHandler() <NEW_LINE> self.sh.emit = colored_formatter <NEW_LINE> self.addHandler(self.sh) <NEW_LINE> self.sh.setLevel(log_level) <NEW_LINE> self.fh = None <NEW_LINE> self.log_filename = None <NEW_LINE> sys.excepthook = self._catch_exceptions <NEW_LINE> self.warnings_logger = None <NEW_LINE> if capture_warnings: <NEW_LINE> <INDENT> self.capture_warnings() <NEW_LINE> <DEDENT> <DEDENT> def _catch_exceptions(self, exctype, value, tb): <NEW_LINE> <INDENT> self.error(get_exception_formatted(exctype, value, tb)) <NEW_LINE> <DEDENT> def capture_warnings(self): <NEW_LINE> <INDENT> logging.captureWarnings(True) <NEW_LINE> self.warnings_logger = logging.getLogger('py.warnings') <NEW_LINE> for handler in self.warnings_logger.handlers: <NEW_LINE> <INDENT> if isinstance(handler, logging.StreamHandler): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> self.warnings_logger.addHandler(self.sh) <NEW_LINE> <DEDENT> def save_log(self, path): <NEW_LINE> <INDENT> shutil.copyfile(self.log_filename, os.path.expanduser(path)) <NEW_LINE> <DEDENT> def start_file_logger(self, path, log_level=logging.DEBUG): <NEW_LINE> <INDENT> log_file_path = os.path.expanduser(path) <NEW_LINE> logdir = os.path.dirname(log_file_path) <NEW_LINE> try: <NEW_LINE> <INDENT> if not os.path.exists(logdir): <NEW_LINE> <INDENT> os.makedirs(logdir) <NEW_LINE> <DEDENT> if os.path.exists(log_file_path): <NEW_LINE> <INDENT> strtime = datetime.datetime.utcnow().strftime('%Y-%m-%d_%H:%M:%S') <NEW_LINE> shutil.move(log_file_path, log_file_path + '.' + strtime) <NEW_LINE> <DEDENT> self.fh = TimedRotatingFileHandler( str(log_file_path), when='midnight', utc=True) <NEW_LINE> self.fh.suffix = '%Y-%m-%d_%H:%M:%S' <NEW_LINE> <DEDENT> except (IOError, OSError) as ee: <NEW_LINE> <INDENT> warnings.warn('log file {0!r} could not be opened for ' 'writing: {1}'.format(log_file_path, ee), RuntimeWarning) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.fh.setFormatter(SDSSFormatter()) <NEW_LINE> self.addHandler(self.fh) <NEW_LINE> self.fh.setLevel(log_level) <NEW_LINE> if self.warnings_logger: <NEW_LINE> <INDENT> self.warnings_logger.addHandler(self.fh) <NEW_LINE> <DEDENT> self.log_filename = log_file_path <NEW_LINE> <DEDENT> <DEDENT> def set_level(self, level): <NEW_LINE> <INDENT> self.sh.setLevel(level) <NEW_LINE> if self.fh: <NEW_LINE> <INDENT> self.fh.setLevel(level)
Custom logging system. Parameters ---------- name : str The name of the logger. log_level : int The initial logging level for the console handler. capture_warnings : bool Whether to capture warnings and redirect them to the log.
62598fabdd821e528d6d8ed1
class StandardNS(object): <NEW_LINE> <INDENT> __snsHandler = dict() <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.__snsHandler["owl"] = self.__owlNamespace() <NEW_LINE> self.__snsHandler["rdf"] = self.__rdfNamespace() <NEW_LINE> self.__snsHandler["rdfs"] = self.__rdfsNamespace() <NEW_LINE> self.__snsHandler["xsd"] = self.__xsdNamespace() <NEW_LINE> <DEDENT> def getSnsHandler(self): <NEW_LINE> <INDENT> return self.__snsHandler <NEW_LINE> <DEDENT> def __owlNamespace(self): <NEW_LINE> <INDENT> owlHandler = dict() <NEW_LINE> owlHandler["Class"] = OWL.Class <NEW_LINE> owlHandler["ObjectProperty"] = OWL.ObjectProperty <NEW_LINE> owlHandler["DatatypeProperty"] = OWL.DatatypeProperty <NEW_LINE> owlHandler["Restriction"] = OWL.Restriction <NEW_LINE> owlHandler["onProperty"] = OWL.onProperty <NEW_LINE> owlHandler["maxCardinality"] = OWL.maxCardinality <NEW_LINE> return owlHandler <NEW_LINE> <DEDENT> def __rdfNamespace(self): <NEW_LINE> <INDENT> rdfHandler = dict() <NEW_LINE> rdfHandler["Property"] = RDF.Property <NEW_LINE> rdfHandler["type"] = RDF.type <NEW_LINE> rdfHandler["datatype"] = RDF.datatype <NEW_LINE> return rdfHandler <NEW_LINE> <DEDENT> def __rdfsNamespace(self): <NEW_LINE> <INDENT> rdfsHandler = dict() <NEW_LINE> rdfsHandler["subClassOf"] = RDFS.subClassOf <NEW_LINE> rdfsHandler["domain"] = RDFS.domain <NEW_LINE> rdfsHandler["range"] = RDFS.range <NEW_LINE> return rdfsHandler <NEW_LINE> <DEDENT> def __xsdNamespace(self): <NEW_LINE> <INDENT> xsdHandler = dict() <NEW_LINE> xsdHandler["string"] = XSD.string <NEW_LINE> xsdHandler["int"] = XSD.int <NEW_LINE> xsdHandler["boolean"] = XSD.boolean <NEW_LINE> xsdHandler["float"] = XSD.float <NEW_LINE> xsdHandler["nonNegativeInteger"] = XSD.nonNegativeInteger <NEW_LINE> return xsdHandler
Provides a dictionary of dictionaries containing all the needed tags for OWL, RDF, RDFS, XSD.
62598fabac7a0e7691f724a6
class person(): <NEW_LINE> <INDENT> country = '中国' <NEW_LINE> def __init__(self,name,age,sex,address): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.age = age <NEW_LINE> self.sex = sex <NEW_LINE> self.__address = address <NEW_LINE> <DEDENT> def getName(self): <NEW_LINE> <INDENT> print('我的名字叫%s,我来自%s,我住在%s!'%(self.name,person.country,self.__address)) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def getA(): <NEW_LINE> <INDENT> print('我的名字叫%s'%person.country) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def getB(cls): <NEW_LINE> <INDENT> print('我的名字叫%s'%cls.country)
这是一个人类
62598fab7d43ff24874273d0
class DiskOpUseSwap(BaseDiskOp): <NEW_LINE> <INDENT> swap_part = None <NEW_LINE> path = None <NEW_LINE> def __init__(self, device, swap_part): <NEW_LINE> <INDENT> BaseDiskOp.__init__(self, device) <NEW_LINE> self.swap_part = swap_part <NEW_LINE> self.path = self.swap_part.path <NEW_LINE> <DEDENT> def describe(self): <NEW_LINE> <INDENT> return "Use {} as swap partition".format(self.swap_part.path) <NEW_LINE> <DEDENT> def apply(self, disk, simulate): <NEW_LINE> <INDENT> return True
Use an existing swap paritition
62598fab7cff6e4e811b59c8
class ControlShared(ControlBase): <NEW_LINE> <INDENT> meta_type = "ControlShared" <NEW_LINE> security = ClassSecurityInfo() <NEW_LINE> control_title = 'Shared' <NEW_LINE> security.declareProtected('View management screens', 'edit') <NEW_LINE> def edit(self, *args, **kw): <NEW_LINE> <INDENT> temp = ['<div class="">'] <NEW_LINE> temp.append(self.checkMasterLocation()) <NEW_LINE> temp.append('</div>') <NEW_LINE> return ''.join(temp) <NEW_LINE> <DEDENT> security.declarePrivate('checkMasterLocation') <NEW_LINE> def checkMasterLocation(self): <NEW_LINE> <INDENT> temp = [] <NEW_LINE> cdoc = self.getCompoundDoc() <NEW_LINE> if cdoc.masterLocation is not None: <NEW_LINE> <INDENT> if cdoc.masterLocation != cdoc.getPath(): <NEW_LINE> <INDENT> master = self.unrestrictedTraverse(cdoc.masterLocation, None) <NEW_LINE> if master is not None and master.meta_type == 'CompoundDoc': <NEW_LINE> <INDENT> if cdoc.DisplayManager is None: <NEW_LINE> <INDENT> temp.append("<p>I don't have a DisplayManager</p>") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if aq_base(cdoc.DisplayManager) is aq_base(master.DisplayManager): <NEW_LINE> <INDENT> temp.append('<p>I am sharing DisplayManager</p>') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> temp.append('<p>I am not sharing DisplayManager</p>') <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> temp.append('<p>Sharing is enabled and I am the master document</p>') <NEW_LINE> <DEDENT> <DEDENT> return ''.join(temp)
Show the status of which items are shared
62598fab45492302aabfc46d
class SetUpTest(): <NEW_LINE> <INDENT> fixtures = ['fixtures/simplemenu.json'] <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> self.thumbnail = os.path.join(MODEL_DIR, "thumbnail.png") <NEW_LINE> self.thumbnail_content = open(self.thumbnail, 'rb') <NEW_LINE> self.file = os.path.join(MODEL_DIR, "example.model3") <NEW_LINE> self.file_content = open(self.file, 'rb') <NEW_LINE> self.modelzip_file = os.path.join(MODEL_DIR, "example.zip") <NEW_LINE> self.modelzip_file_content = open(self.modelzip_file, 'rb') <NEW_LINE> self.model_oversize = os.path.join(MODEL_DIR, "dummy_oversize.model3") <NEW_LINE> self.model_oversize_content = open(self.model_oversize, 'rb') <NEW_LINE> self.creator = User.objects.create( username="creator", email="creator@email.com" ) <NEW_LINE> self.creator.set_password("password") <NEW_LINE> self.creator.save() <NEW_LINE> self.staff = User.objects.create( username="staff", email="staff@email.com" ) <NEW_LINE> self.staff.set_password("password") <NEW_LINE> self.staff.save() <NEW_LINE> self.group = Group.objects.create(name="Style Managers") <NEW_LINE> self.group.user_set.add(self.staff) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> self.thumbnail_content.close() <NEW_LINE> self.file_content.close() <NEW_LINE> self.modelzip_file_content.close() <NEW_LINE> self.model_oversize_content.close()
SetUp for all Test Class
62598fab3d592f4c4edbae68
class DeltaFetch(object): <NEW_LINE> <INDENT> def __init__(self, dir, dbmodule='anydbm'): <NEW_LINE> <INDENT> self.dir = dir <NEW_LINE> self.dbmodule = __import__(dbmodule) <NEW_LINE> dispatcher.connect(self.spider_opened, signal=signals.spider_opened) <NEW_LINE> dispatcher.connect(self.spider_closed, signal=signals.spider_closed) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_crawler(cls, crawler): <NEW_LINE> <INDENT> s = crawler.settings <NEW_LINE> if not s.getbool('DELTAFETCH_ENABLED'): <NEW_LINE> <INDENT> raise NotConfigured <NEW_LINE> <DEDENT> dir = data_path(s.get('DELTAFETCH_DIR', 'deltafetch')) <NEW_LINE> dbmodule = s.get('DELTAFETCH_DBM_MODULE', 'anydbm') <NEW_LINE> return cls(dir, dbmodule) <NEW_LINE> <DEDENT> def spider_opened(self, spider): <NEW_LINE> <INDENT> if not os.path.exists(self.dir): <NEW_LINE> <INDENT> os.makedirs(self.dir) <NEW_LINE> <DEDENT> dbpath = os.path.join(self.dir, '%s.db' % spider.name) <NEW_LINE> flag = 'n' if getattr(spider, 'deltafetch_reset', False) else 'c' <NEW_LINE> self.db = self.dbmodule.open(dbpath, flag) <NEW_LINE> <DEDENT> def spider_closed(self, spider): <NEW_LINE> <INDENT> self.db.close() <NEW_LINE> <DEDENT> def process_spider_output(self, response, result, spider): <NEW_LINE> <INDENT> for r in result: <NEW_LINE> <INDENT> if isinstance(r, Request): <NEW_LINE> <INDENT> key = self._get_key(r) <NEW_LINE> if self.db.has_key(key): <NEW_LINE> <INDENT> spider.log("Ignoring already visited: %s" % r, level=log.INFO) <NEW_LINE> continue <NEW_LINE> <DEDENT> <DEDENT> elif isinstance(r, BaseItem): <NEW_LINE> <INDENT> key = self._get_key(response.request) <NEW_LINE> self.db[key] = str(time.time()) <NEW_LINE> <DEDENT> yield r <NEW_LINE> <DEDENT> <DEDENT> def _get_key(self, request): <NEW_LINE> <INDENT> return request.meta.get('deltafetch_key') or request_fingerprint(request)
This is a spider middleware to ignore requests to pages containing items seen in previous crawls of the same spider, thus producing a "delta crawl" containing only new items. This also speeds up the crawl, by reducing the number of requests that need to be crawled, and processed (typically, item requests are the most cpu intensive). Supported settings: * DELTAFETCH_ENABLED - to enable (or disable) this extension * DELTAFETCH_DIR - directory where to store state * DELTAFETCH_DBM_MODULE - which DBM module to use for storage Supported spider arguments: * deltafetch_reset - reset the state, clearing out all seen requests Supported request meta keys: * deltafetch_key - used to define the lookup key for that request. by default it's the fingerprint, but it can be changed to contain an item id, for example. This requires support from the spider, but makes the extension more efficient for sites that many URLs for the same item.
62598fabd486a94d0ba2bf6a
class _S3(object): <NEW_LINE> <INDENT> def __init__(self, uri, s3=None, aws_access_key_id=None, aws_secret_access_key=None, *args, **kwargs): <NEW_LINE> <INDENT> result = urlparse(uri) <NEW_LINE> self.bucket = result.netloc <NEW_LINE> self.key = result.path.lstrip('/') <NEW_LINE> if s3 is not None: <NEW_LINE> <INDENT> self.s3 = s3 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.s3 = get_s3_connection(aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> bucket = self.s3.get_bucket(self.bucket) <NEW_LINE> <DEDENT> except boto.exception.S3ResponseError: <NEW_LINE> <INDENT> bucket = self.s3.create_bucket(self.bucket) <NEW_LINE> <DEDENT> self.object = bucket.get_key(self.key) <NEW_LINE> if self.object is None: <NEW_LINE> <INDENT> self.object = bucket.new_key(self.key) <NEW_LINE> <DEDENT> self.subtype.__init__(self, uri, *args, **kwargs)
Parametrized S3 bucket Class Examples -------- >>> S3(CSV) <class 'into.backends.aws.S3(CSV)'>
62598fab5fc7496912d48250
class RegularGrammar(): <NEW_LINE> <INDENT> def __init__( self, initial_symbol: str="", productions: Dict[str, Set[str]]=None) -> None: <NEW_LINE> <INDENT> self._initial_symbol = initial_symbol <NEW_LINE> self._productions = productions if productions else {} <NEW_LINE> <DEDENT> def initial_symbol(self): <NEW_LINE> <INDENT> return self._initial_symbol <NEW_LINE> <DEDENT> def productions(self): <NEW_LINE> <INDENT> return self._productions <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def from_nfa(nfa) -> 'RegularGrammar': <NEW_LINE> <INDENT> initial_symbol = nfa.initial_state <NEW_LINE> productions = {} <NEW_LINE> for k, states in nfa.transition_table.items(): <NEW_LINE> <INDENT> for state in states: <NEW_LINE> <INDENT> if k[0] not in productions: <NEW_LINE> <INDENT> productions[k[0]] = set() <NEW_LINE> <DEDENT> productions[k[0]].add(k[1] + state) <NEW_LINE> if state in nfa.final_states: <NEW_LINE> <INDENT> productions[k[0]].add(k[1]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if nfa.initial_state in nfa.final_states: <NEW_LINE> <INDENT> new_initial_symbol = initial_symbol + "'" <NEW_LINE> productions[new_initial_symbol] = productions.get(initial_symbol, set()) | {"&"} <NEW_LINE> initial_symbol = new_initial_symbol <NEW_LINE> <DEDENT> return RegularGrammar(initial_symbol, productions)
Regular grammar object, it is represented as a dictionary, for each non terminal symbol of the grammar, there is a dictionary entry with the corresponding strings that it can derive. For example, the grammar: S -> aA | bB | a | b A -> aA | a B -> bB | b is represented as: { "S": {"aA", "bB", "a", "b"}, "A": {"aA", "a"}, "B": {"bB", "b"} }
62598fab1b99ca400228f4fe
class idqCalibrationCheck(esUtils.EventSupervisorTask): <NEW_LINE> <INDENT> name = "idqCalibration" <NEW_LINE> def __init__(self, timeout, ifo, classifier, emailOnSuccess=[], emailOnFailure=[], emailOnException=[], logDir='.', logTag='iQ'): <NEW_LINE> <INDENT> self.ifo = ifo <NEW_LINE> self.classifier = classifier <NEW_LINE> self.description = "a check that iDQ reported the calibration data as expected for %s at %s"%(self.classifier, self.ifo) <NEW_LINE> super(idqCalibrationCheck, self).__init__( timeout, emailOnSuccess=emailOnSuccess, emailOnFailure=emailOnFailure, emailOnException=emailOnException, logDir=logDir, logTag=logTag, ) <NEW_LINE> <DEDENT> def idqCalibration(self, graceid, gdb, verbose=False, annotate=False, **kwargs): <NEW_LINE> <INDENT> if verbose: <NEW_LINE> <INDENT> logger = esUtils.genTaskLogger( self.logDir, self.name, logTag=self.logTag ) <NEW_LINE> logger.info( "%s : %s"%(graceid, self.description) ) <NEW_LINE> <DEDENT> jsonname = "%s_%s(.*)_calib-(.*)-(.*).json"%(self.ifo, self.classifier) <NEW_LINE> fragment = "iDQ calibration sanity check for %s at %s"%(self.classifier, self.ifo) <NEW_LINE> self.warning, action_required = esUtils.check4file( graceid, gdb, jsonname, regex=True, tagnames=None, verbose=verbose, logFragment=fragment, logRegex=False, logTag=logger.name if verbose else None ) <NEW_LINE> if verbose or annotate: <NEW_LINE> <INDENT> if action_required: <NEW_LINE> <INDENT> message = "action required : "+self.warning <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> message = "no action required : "+self.warning <NEW_LINE> <DEDENT> if verbose: <NEW_LINE> <INDENT> logger.debug( message ) <NEW_LINE> <DEDENT> if annotate: <NEW_LINE> <INDENT> esUtils.writeGDBLog( gdb, graceid, message ) <NEW_LINE> <DEDENT> <DEDENT> return action_required
a check that iDQ reported historical calibration as expected
62598fab8a43f66fc4bf2118
class CurrentUser(_ApiResourceBase): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self._iface = self.get_client().user <NEW_LINE> super().__init__(*args, **kwargs) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.steam_id) <NEW_LINE> <DEDENT> @property <NEW_LINE> def user(self): <NEW_LINE> <INDENT> return User(self.steam_id) <NEW_LINE> <DEDENT> @property <NEW_LINE> def logged_in(self): <NEW_LINE> <INDENT> return self._iface.get_is_logged_on() <NEW_LINE> <DEDENT> @property <NEW_LINE> def behind_nat(self): <NEW_LINE> <INDENT> return self._iface.get_is_behind_nat() <NEW_LINE> <DEDENT> @property <NEW_LINE> def level(self): <NEW_LINE> <INDENT> return self._iface.get_level() <NEW_LINE> <DEDENT> @property <NEW_LINE> def steam_id(self): <NEW_LINE> <INDENT> return self._iface.get_id() <NEW_LINE> <DEDENT> @property <NEW_LINE> def steam_handle(self): <NEW_LINE> <INDENT> return self.get_client().h_user
Exposed methods related to a current Steam client user. Can be accessed through ``api.current_user``: .. code-block:: python user = api.current_user
62598fabf548e778e596b540
class FunctionBrowserTest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testInitShowTable(self): <NEW_LINE> <INDENT> myDialog = FunctionBrowser(PARENT) <NEW_LINE> myStr = myDialog.table.toNewlineFreeString() <NEW_LINE> assert len(myStr) > 1000, "Please check." <NEW_LINE> <DEDENT> def testFilterTable(self): <NEW_LINE> <INDENT> myDialog = FunctionBrowser(PARENT) <NEW_LINE> list_category = myDialog.combo_box_content['category'] <NEW_LINE> for i in xrange(1, len(list_category)): <NEW_LINE> <INDENT> myDialog.comboBox_category.setCurrentIndex(i) <NEW_LINE> verifyColumn(myDialog.table, 2, list_category[i], 'only') <NEW_LINE> <DEDENT> myDialog.comboBox_datatype.setCurrentIndex(3) <NEW_LINE> myDatatype = myDialog.comboBox_datatype.currentText() <NEW_LINE> if myDatatype == 'sigab': <NEW_LINE> <INDENT> verifyColumn(myDialog.table, 5, myDatatype, 'included') <NEW_LINE> <DEDENT> <DEDENT> def testRestButton(self): <NEW_LINE> <INDENT> raise SkipTest("This test hangs Jenkins.") <NEW_LINE> myDialog = FunctionBrowser(PARENT) <NEW_LINE> expectedTable = myDialog.table.toNewlineFreeString() <NEW_LINE> myDialog.comboBox_category.setCurrentIndex(1) <NEW_LINE> myDialog.comboBox_subcategory.setCurrentIndex(1) <NEW_LINE> resetButton = myDialog.myButtonBox.button(QDialogButtonBox.Reset) <NEW_LINE> realTableFilter = myDialog.table.toNewlineFreeString() <NEW_LINE> resetButton.click() <NEW_LINE> realTableReset = myDialog.table.toNewlineFreeString() <NEW_LINE> msgFilter = 'It should be different table because it is filtered.' <NEW_LINE> assert expectedTable != realTableFilter, msgFilter <NEW_LINE> msgReset = ('It should be the same table because reset button ' 'is pressed.') <NEW_LINE> assert expectedTable == realTableReset, msgReset <NEW_LINE> <DEDENT> @unittest.skip('Skipping as this test hangs Jenkins if docs not found.') <NEW_LINE> def test_showHelp(self): <NEW_LINE> <INDENT> raise SkipTest("This test hangs Jenkins if docs dir not present.") <NEW_LINE> myDialog = FunctionBrowser(PARENT) <NEW_LINE> myButton = myDialog.buttonBox.button(QDialogButtonBox.Help) <NEW_LINE> myButton.click() <NEW_LINE> message = 'Help dialog was not created when help button pressed' <NEW_LINE> assert myDialog.helpDialog is not None, message
Tests for the function browser gui.
62598faba8370b77170f0378
class Download(DownloadRuntimeConfig,DownloadImpl): <NEW_LINE> <INDENT> def __init__(self,session,tdef): <NEW_LINE> <INDENT> DownloadImpl.__init__(self,session,tdef) <NEW_LINE> <DEDENT> def get_def(self): <NEW_LINE> <INDENT> return DownloadImpl.get_def(self) <NEW_LINE> <DEDENT> def set_state_callback(self,usercallback,getpeerlist=True): <NEW_LINE> <INDENT> DownloadImpl.set_state_callback(self,usercallback,getpeerlist=getpeerlist) <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> DownloadImpl.stop(self) <NEW_LINE> <DEDENT> def restart(self): <NEW_LINE> <INDENT> DownloadImpl.restart(self) <NEW_LINE> <DEDENT> def update_peerlist(self, highpeers, lowpeers): <NEW_LINE> <INDENT> return DownloadImpl.update_peerlist(self, highpeers, lowpeers) <NEW_LINE> <DEDENT> def get_packet_loss(self): <NEW_LINE> <INDENT> return DownloadImpl.get_packet_loss(self) <NEW_LINE> <DEDENT> def get_num_msgs(self): <NEW_LINE> <INDENT> return DownloadImpl.get_num_msgs(self) <NEW_LINE> <DEDENT> def set_server_ip(self, ipAddr): <NEW_LINE> <INDENT> DownloadImpl.set_server_ip(self, ipAddr) <NEW_LINE> <DEDENT> def get_server_ip(self): <NEW_LINE> <INDENT> return DownloadImpl.get_server_ip(self) <NEW_LINE> <DEDENT> def set_flag(self, ipAddr): <NEW_LINE> <INDENT> return DownloadImpl.set_flag(self, ipAddr) <NEW_LINE> <DEDENT> def set_max_desired_speed(self,direct,speed): <NEW_LINE> <INDENT> DownloadImpl.set_max_desired_speed(self,direct,speed) <NEW_LINE> <DEDENT> def get_max_desired_speed(self,direct): <NEW_LINE> <INDENT> return DownloadImpl.get_max_desired_speed(self,direct) <NEW_LINE> <DEDENT> def get_dest_files(self, exts = None): <NEW_LINE> <INDENT> return DownloadImpl.get_dest_files(self, exts) <NEW_LINE> <DEDENT> def ask_coopdl_helpers(self,permidlist): <NEW_LINE> <INDENT> self.dllock.acquire() <NEW_LINE> try: <NEW_LINE> <INDENT> peerreclist = self.session.lm.peer_db.getPeers(permidlist, ['permid','ip','port']) <NEW_LINE> if self.sd is not None: <NEW_LINE> <INDENT> ask_coopdl_helpers_lambda = lambda:self.sd.ask_coopdl_helpers(peerreclist) <NEW_LINE> self.session.lm.rawserver.add_task(ask_coopdl_helpers_lambda,0) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise OperationNotPossibleWhenStoppedException() <NEW_LINE> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> self.dllock.release() <NEW_LINE> <DEDENT> <DEDENT> def stop_coopdl_helpers(self,permidlist): <NEW_LINE> <INDENT> self.dllock.acquire() <NEW_LINE> try: <NEW_LINE> <INDENT> peerreclist = self.session.lm.peer_db.getPeers(permidlist, ['permid','ip','port']) <NEW_LINE> if self.sd is not None: <NEW_LINE> <INDENT> stop_coopdl_helpers_lambda = lambda:self.sd.stop_coopdl_helpers(peerreclist) <NEW_LINE> self.session.lm.rawserver.add_task(stop_coopdl_helpers_lambda,0) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise OperationNotPossibleWhenStoppedException() <NEW_LINE> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> self.dllock.release()
Representation of a running BT download/upload A Download implements the DownloadConfigInterface which can be used to change download parameters are runtime (for selected parameters). cf. libtorrent torrent_handle
62598fab3346ee7daa337617
class ReplyToViewer: <NEW_LINE> <INDENT> def __init__(self, reply_to): <NEW_LINE> <INDENT> ctx = zmq.Context() <NEW_LINE> self.sock = ctx.socket(zmq.PAIR) <NEW_LINE> self.sock.linger = 1000 <NEW_LINE> self.sock.connect(reply_to) <NEW_LINE> _logger.debug(f"Connecting zmq.PAIR to {reply_to}") <NEW_LINE> self.pollout = zmq.Poller() <NEW_LINE> self.pollout.register(self.sock, zmq.POLLOUT) <NEW_LINE> <DEDENT> def _send(self, message): <NEW_LINE> <INDENT> socks = dict(self.pollout.poll(300)) <NEW_LINE> if socks.get(self.sock) == zmq.POLLOUT: <NEW_LINE> <INDENT> as_json = json.dumps(message) <NEW_LINE> self.sock.send_unicode(as_json, flags=zmq.NOBLOCK) <NEW_LINE> <DEDENT> <DEDENT> def show_state(self, game_state): <NEW_LINE> <INDENT> self._send(game_state)
A viewer which dumps to a given stream.
62598fab3317a56b869be519
class MoneyAgent(Agent): <NEW_LINE> <INDENT> def __init__(self, unique_id, model): <NEW_LINE> <INDENT> super().__init__(unique_id, model) <NEW_LINE> self.wealth = 1 <NEW_LINE> <DEDENT> def step(self): <NEW_LINE> <INDENT> if self.wealth == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> other_agent = random.choice(self.model.schedule.agents) <NEW_LINE> other_agent.wealth += 1 <NEW_LINE> self.wealth -= 1
An agent with fixed initial wealth
62598fab7047854f4633f376
class GtpError(Exception): <NEW_LINE> <INDENT> pass
Error reported by a command handler.
62598fab8e71fb1e983bba50
class MachineLearningComputeManagementClientConfiguration(Configuration): <NEW_LINE> <INDENT> def __init__( self, credential, subscription_id, **kwargs ): <NEW_LINE> <INDENT> if credential is None: <NEW_LINE> <INDENT> raise ValueError("Parameter 'credential' must not be None.") <NEW_LINE> <DEDENT> if subscription_id is None: <NEW_LINE> <INDENT> raise ValueError("Parameter 'subscription_id' must not be None.") <NEW_LINE> <DEDENT> super(MachineLearningComputeManagementClientConfiguration, self).__init__(**kwargs) <NEW_LINE> self.credential = credential <NEW_LINE> self.subscription_id = subscription_id <NEW_LINE> self.api_version = "2017-08-01-preview" <NEW_LINE> self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) <NEW_LINE> kwargs.setdefault('sdk_moniker', 'mgmt-machinelearningcompute/{}'.format(VERSION)) <NEW_LINE> self._configure(**kwargs) <NEW_LINE> <DEDENT> def _configure( self, **kwargs ): <NEW_LINE> <INDENT> self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) <NEW_LINE> self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) <NEW_LINE> self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) <NEW_LINE> self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) <NEW_LINE> self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) <NEW_LINE> self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) <NEW_LINE> self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) <NEW_LINE> self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) <NEW_LINE> self.authentication_policy = kwargs.get('authentication_policy') <NEW_LINE> if self.credential and not self.authentication_policy: <NEW_LINE> <INDENT> self.authentication_policy = policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs)
Configuration for MachineLearningComputeManagementClient. Note that all parameters used to create this instance are saved as instance attributes. :param credential: Credential needed for the client to connect to Azure. :type credential: ~azure.core.credentials.TokenCredential :param subscription_id: The Azure subscription ID. :type subscription_id: str
62598fab1f037a2d8b9e408b
class TransparentPolicy(ABC): <NEW_LINE> <INDENT> def __init__(self, transparent_params): <NEW_LINE> <INDENT> if transparent_params is None: <NEW_LINE> <INDENT> transparent_params = set() <NEW_LINE> <DEDENT> unexpected_keys = set(transparent_params).difference(TRANSPARENCY_KEYS) <NEW_LINE> if unexpected_keys: <NEW_LINE> <INDENT> raise KeyError(f"Unrecognized transparency keys: {unexpected_keys}") <NEW_LINE> <DEDENT> self.transparent_params = transparent_params <NEW_LINE> <DEDENT> def _get_default_transparency_dict(self, obs, ff, hid): <NEW_LINE> <INDENT> def consolidate(acts): <NEW_LINE> <INDENT> return np.squeeze(np.concatenate(acts)) <NEW_LINE> <DEDENT> transparency_dict = { "obs": obs, "hid": hid, "ff_policy": consolidate(ff["policy"]), "ff_value": consolidate(ff["value"]), } <NEW_LINE> transparency_dict = _filter_dict(transparency_dict, self.transparent_params) <NEW_LINE> return transparency_dict
Policy which returns its observations and/or activations in its call to self.predict :param transparent_params: (set) a subset of TRANSPARENCY_KEYS. If key is present, that data will be included in the transparency_dict returned in step_transparent.
62598fab32920d7e50bc5ff2
class UserViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = User.objects.all() <NEW_LINE> serializer_class = UserSerializer <NEW_LINE> permission_classes = (permissions.IsAuthenticatedOrReadOnly,) <NEW_LINE> http_method_names = ('get', 'put')
This viewset automatically provides `list` and `detail` actions.
62598fabcc0a2c111447afae
class GlanceUtilsTest(common.HeatTestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(GlanceUtilsTest, self).setUp() <NEW_LINE> self.glance_client = mock.MagicMock() <NEW_LINE> con = utils.dummy_context() <NEW_LINE> c = con.clients <NEW_LINE> self.glance_plugin = c.client_plugin('glance') <NEW_LINE> self.glance_plugin.client = lambda: self.glance_client <NEW_LINE> self.my_image = mock.MagicMock() <NEW_LINE> <DEDENT> def test_find_image_by_name_or_id(self): <NEW_LINE> <INDENT> img_id = str(uuid.uuid4()) <NEW_LINE> img_name = 'myfakeimage' <NEW_LINE> self.my_image.id = img_id <NEW_LINE> self.my_image.name = img_name <NEW_LINE> self.glance_client.images.get.side_effect = [ self.my_image, exc.HTTPNotFound(), exc.HTTPNotFound(), exc.HTTPNotFound()] <NEW_LINE> self.glance_client.images.list.side_effect = [ [self.my_image], [], [self.my_image, self.my_image]] <NEW_LINE> self.assertEqual(img_id, self.glance_plugin.find_image_by_name_or_id(img_id)) <NEW_LINE> self.assertEqual(img_id, self.glance_plugin.find_image_by_name_or_id(img_name)) <NEW_LINE> self.assertRaises(exceptions.NotFound, self.glance_plugin.find_image_by_name_or_id, 'noimage') <NEW_LINE> self.assertRaises(exceptions.NoUniqueMatch, self.glance_plugin.find_image_by_name_or_id, 'myfakeimage')
Basic tests for :module:'heat.engine.resources.clients.os.glance'.
62598fabe5267d203ee6b8a7
class WebResource: <NEW_LINE> <INDENT> def read_json(self): <NEW_LINE> <INDENT> return "Sample plain text as json." <NEW_LINE> <DEDENT> def read_html(self): <NEW_LINE> <INDENT> pass
An instance of this class wraps web data. While it has many output formats, the server can only read the json output.
62598fab66673b3332c30369
class bernoulliArm(): <NEW_LINE> <INDENT> def __init__(self, mean): <NEW_LINE> <INDENT> self.mean = mean <NEW_LINE> <DEDENT> def sample(self, t): <NEW_LINE> <INDENT> return np.random.binomial(p=self.mean, n=1)
Defines a Bernoulli arm
62598fab7cff6e4e811b59ca
class GetProfile(Requester): <NEW_LINE> <INDENT> def __init__(self, session, cid): <NEW_LINE> <INDENT> key = get_key(session, 'storage.msn.com', False) <NEW_LINE> Requester.__init__(self, session, 'http://www.msn.com/webservices/storage/w10/GetProfile', 'storage.msn.com', 443, '/storageservice/SchematizedStore.asmx', XmlManager.get('getprofile', key, cid)) <NEW_LINE> self.session = session <NEW_LINE> self.cid = cid <NEW_LINE> <DEDENT> def handle_response(self, request, response): <NEW_LINE> <INDENT> if response.status == 200: <NEW_LINE> <INDENT> nick = safe_split(response.body, '<DisplayName>', '</DisplayName>') <NEW_LINE> message = safe_split(response.body, '<PersonalStatus>', '</PersonalStatus>') <NEW_LINE> cache_key = safe_split(response.body, '<CacheKey>', '</CacheKey>') <NEW_LINE> rid = safe_split(response.body, '<ResourceID>', '</ResourceID>') <NEW_LINE> pre_auth_url = safe_split(response.body, '<PreAuthURL>', '</PreAuthURL>') <NEW_LINE> self.session.extras["CacheKey"] = cache_key <NEW_LINE> self.session.extras["ResourceID"] = rid <NEW_LINE> self.session.contacts.me.nick = nick <NEW_LINE> self.session.contacts.me.message = message <NEW_LINE> self.session.add_event(e3.Event.EVENT_PROFILE_GET_SUCCEED, nick, message) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.session.add_event(e3.Event.EVENT_PROFILE_GET_FAILED, 'Can\'t get profile for %s' % self.cid)
make a request to get the nick and personal message
62598fab4e4d5625663723c4
class ImagePortletHelper(grok.CodeView): <NEW_LINE> <INDENT> grok.context(Interface) <NEW_LINE> grok.baseclass()
Expose stuff downloadable from the image portlet BLOBs.
62598fab3d592f4c4edbae6a
class TestOwnershipBase(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.user1 = get_user_model().objects.create_superuser( 'user1', 'user1@example.com', 'password' ) <NEW_LINE> self.user2 = get_user_model().objects.create_superuser( 'user2', 'user2@example.com', 'password' ) <NEW_LINE> self.client = user_client(self.user1) <NEW_LINE> self.service = ServiceFactory() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> for Model in [Domain, Record, get_user_model()]: <NEW_LINE> <INDENT> Model.objects.all().delete() <NEW_LINE> <DEDENT> <DEDENT> def assertOwner(self, request, username): <NEW_LINE> <INDENT> self.assertEqual(request.data['owner'], username)
Base test class creating some users.
62598fab5fc7496912d48251
class PluginInfo(object): <NEW_LINE> <INDENT> def __init__(self, infojson=None): <NEW_LINE> <INDENT> self._meta = 'IonPlugin Definition format 1.0' <NEW_LINE> self.name = None <NEW_LINE> self.version = "0.0" <NEW_LINE> self.allow_autorun = True <NEW_LINE> self.config = {} <NEW_LINE> self.runtypes = [] <NEW_LINE> self.features = [] <NEW_LINE> self.runlevels = [] <NEW_LINE> self.depends = [] <NEW_LINE> self.docs = "" <NEW_LINE> self.major_block = "" <NEW_LINE> self.pluginorm = None <NEW_LINE> if infojson: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.parse(infojson) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> _logger.exception("Unable to inspect plugin for required parameters.") <NEW_LINE> <DEDENT> <DEDENT> return <NEW_LINE> <DEDENT> def parse(self, data={}): <NEW_LINE> <INDENT> if isinstance(data, basestring): <NEW_LINE> <INDENT> data = json.loads(data) <NEW_LINE> <DEDENT> extract_keys = vars(self).keys() <NEW_LINE> for k in extract_keys: <NEW_LINE> <INDENT> if k in data: <NEW_LINE> <INDENT> setattr(self, k, data[k]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def todict(self): <NEW_LINE> <INDENT> d = vars(self) <NEW_LINE> for k, v in d.iteritems(): <NEW_LINE> <INDENT> if isinstance(v, property): <NEW_LINE> <INDENT> d[k] = str(v) <NEW_LINE> <DEDENT> <DEDENT> return d <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return json.dumps(self.todict(), indent=2) <NEW_LINE> <DEDENT> def load_instance(self, plugin): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.config = plugin.getUserInput() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> _logger.exception("Failed to query plugin for getUserInput") <NEW_LINE> <DEDENT> for a in ('runtypes', 'features', 'runlevels', 'depends', 'allow_autorun', 'major_block'): <NEW_LINE> <INDENT> v = getattr(plugin, a, None) <NEW_LINE> if v is not None: <NEW_LINE> <INDENT> setattr(self, a, v) <NEW_LINE> <DEDENT> <DEDENT> self.docs = getattr(plugin, '__doc__', "") <NEW_LINE> return self <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def from_instance(plugin): <NEW_LINE> <INDENT> return PluginInfo(plugin._metadata()).load_instance(plugin) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_launch(cls, plugin, launch): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> legacyplugin = get_launch_class(plugin) <NEW_LINE> pi = legacyplugin() <NEW_LINE> info = cls.from_instance(pi) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> _logger.exception("Failed to build and parse python class for legacy launch.sh - '%s':'%s'", plugin, launch) <NEW_LINE> info = { 'name': os.path.basename(os.path.dirname(launch)), 'version': get_version_launchsh(launch), } <NEW_LINE> <DEDENT> return info
Class to encapsulate plugin introspection, to and from json block or plugin class instances
62598fab1b99ca400228f4ff
class NSNitroNserrInvalidnetmask(NSNitroCliErrors): <NEW_LINE> <INDENT> pass
Nitro error code 1111 Invalid netmask
62598fab8a43f66fc4bf211a
@override_settings(SEARCH_ENGINE="search.tests.utils.ForceRefreshElasticSearchEngine") <NEW_LINE> @override_settings(ELASTIC_SEARCH_IMPL=ErroringElasticImpl) <NEW_LINE> class ErroringElasticTests(TestCase, SearcherMixin): <NEW_LINE> <INDENT> def test_index_failure_bulk(self): <NEW_LINE> <INDENT> with patch('search.elastic.bulk', return_value=[0, [exceptions.ElasticsearchException()]]): <NEW_LINE> <INDENT> with self.assertRaises(exceptions.ElasticsearchException): <NEW_LINE> <INDENT> self.searcher.index([{"name": "abc test"}]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def test_index_failure_general(self): <NEW_LINE> <INDENT> with patch('search.elastic.bulk', side_effect=Exception()): <NEW_LINE> <INDENT> with self.assertRaises(Exception): <NEW_LINE> <INDENT> self.searcher.index([{"name": "abc test"}]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def test_search_failure(self): <NEW_LINE> <INDENT> with self.assertRaises(exceptions.ElasticsearchException): <NEW_LINE> <INDENT> self.searcher.search("abc test") <NEW_LINE> <DEDENT> <DEDENT> def test_remove_failure_bulk(self): <NEW_LINE> <INDENT> doc_id = 'test_id' <NEW_LINE> error = {'delete': { 'status': 500, '_index': 'test_index', '_version': 1, 'found': True, '_id': doc_id }} <NEW_LINE> with patch('search.elastic.bulk', side_effect=BulkIndexError('Simulated error', [error])): <NEW_LINE> <INDENT> with self.assertRaises(BulkIndexError): <NEW_LINE> <INDENT> self.searcher.remove(["test_id"]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def test_remove_failure_general(self): <NEW_LINE> <INDENT> with patch('search.elastic.bulk', side_effect=Exception()): <NEW_LINE> <INDENT> with self.assertRaises(Exception): <NEW_LINE> <INDENT> self.searcher.remove(["test_id"])
testing handling of elastic exceptions when they happen
62598fabf548e778e596b542
class Entry(models.Model): <NEW_LINE> <INDENT> topic = models.ForeignKey('Topic', on_delete=models.CASCADE) <NEW_LINE> text = models.TextField() <NEW_LINE> date_added = models.DateTimeField(auto_now_add=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name_plural = 'entries' <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> text_form = self.text[:50] <NEW_LINE> if len(text_form) >= 50: <NEW_LINE> <INDENT> text_form = self.text[:50] + "..." <NEW_LINE> <DEDENT> return text_form
Информация, изученная пользователем по теме
62598fab76e4537e8c3ef54c
class ComputeHealthChecksListRequest(_messages.Message): <NEW_LINE> <INDENT> filter = _messages.StringField(1) <NEW_LINE> maxResults = _messages.IntegerField(2, variant=_messages.Variant.UINT32, default=500) <NEW_LINE> orderBy = _messages.StringField(3) <NEW_LINE> pageToken = _messages.StringField(4) <NEW_LINE> project = _messages.StringField(5, required=True)
A ComputeHealthChecksListRequest object. Fields: filter: Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: FIELD_NAME COMPARISON_STRING LITERAL_STRING. The FIELD_NAME is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The COMPARISON_STRING must be either eq (equals) or ne (not equals). The LITERAL_STRING is the string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. For example, filter=name ne example- instance. Compute Engine Beta API Only: If you use filtering in the Beta API, you can also filter on nested fields. For example, you could filter on instances whose scheduling.automaticRestart eq true. In particular, use filtering on nested fields to take advantage of instance labels to organize and filter results based on label values. The Beta API also supports filtering on multiple expressions by providing each separate expression within parentheses. For example, (scheduling.automaticRestart eq true) (zone eq us-central1-f). Multiple expressions are treated as AND expressions meaning that resources must match all expressions to pass the filters. maxResults: Maximum count of results to be returned. orderBy: Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name. You can also sort results in descending order based on the creation timestamp using orderBy="creationTimestamp desc". This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first. Currently, only sorting by name or creationTimestamp desc is supported. pageToken: Specifies a page token to use. Use this parameter if you want to list the next page of results. Set pageToken to the nextPageToken returned by a previous list request. project: Project ID for this request.
62598fabf548e778e596b543
class ByteArray(AppMessageType): <NEW_LINE> <INDENT> type = AppMessageTuple.Type.ByteArray
Represents a uint8_t *
62598fabf7d966606f747f83
class InputBoolean(ToggleEntity, RestoreEntity): <NEW_LINE> <INDENT> def __init__(self, config: typing.Optional[dict], from_yaml: bool = False): <NEW_LINE> <INDENT> self._config = config <NEW_LINE> self._editable = True <NEW_LINE> self._state = config.get(CONF_INITIAL) <NEW_LINE> if from_yaml: <NEW_LINE> <INDENT> self._editable = False <NEW_LINE> self.entity_id = ENTITY_ID_FORMAT.format(self.unique_id) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def should_poll(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._config.get(CONF_NAME) <NEW_LINE> <DEDENT> @property <NEW_LINE> def state_attributes(self): <NEW_LINE> <INDENT> return {ATTR_EDITABLE: self._editable} <NEW_LINE> <DEDENT> @property <NEW_LINE> def icon(self): <NEW_LINE> <INDENT> return self._config.get(CONF_ICON) <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_on(self): <NEW_LINE> <INDENT> return self._state <NEW_LINE> <DEDENT> @property <NEW_LINE> def unique_id(self): <NEW_LINE> <INDENT> return self._config[CONF_ID] <NEW_LINE> <DEDENT> async def async_added_to_opp(self): <NEW_LINE> <INDENT> await super().async_added_to_opp() <NEW_LINE> if self._state is not None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> state = await self.async_get_last_state() <NEW_LINE> self._state = state and state.state == STATE_ON <NEW_LINE> <DEDENT> async def async_turn_on(self, **kwargs): <NEW_LINE> <INDENT> self._state = True <NEW_LINE> await self.async_update_op_state() <NEW_LINE> <DEDENT> async def async_turn_off(self, **kwargs): <NEW_LINE> <INDENT> self._state = False <NEW_LINE> await self.async_update_op_state() <NEW_LINE> <DEDENT> async def async_update_config(self, config: typing.Dict) -> None: <NEW_LINE> <INDENT> self._config = config <NEW_LINE> self.async_write_op_state()
Representation of a boolean input.
62598fab2ae34c7f260ab080
class JSON: <NEW_LINE> <INDENT> def __init__(self, json: str, indent: int = 2, highlight: bool = True) -> None: <NEW_LINE> <INDENT> data = loads(json) <NEW_LINE> json = dumps(data, indent=indent) <NEW_LINE> highlighter = JSONHighlighter() if highlight else NullHighlighter() <NEW_LINE> self.text = highlighter(json) <NEW_LINE> self.text.no_wrap = True <NEW_LINE> self.text.overflow = None <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_data(cls, data: Any, indent: int = 2, highlight: bool = True) -> "JSON": <NEW_LINE> <INDENT> json_instance: "JSON" = cls.__new__(cls) <NEW_LINE> json = dumps(data, indent=indent) <NEW_LINE> highlighter = JSONHighlighter() if highlight else NullHighlighter() <NEW_LINE> json_instance.text = highlighter(json) <NEW_LINE> json_instance.text.no_wrap = True <NEW_LINE> json_instance.text.overflow = None <NEW_LINE> return json_instance <NEW_LINE> <DEDENT> def __rich__(self) -> Text: <NEW_LINE> <INDENT> return self.text
A renderable which pretty prints JSON. Args: json (str): JSON encoded data. indent (int, optional): Number of characters to indent by. Defaults to 2. highlight (bool, optional): Enable highlighting. Defaults to True.
62598fab379a373c97d98fb1
class ServiceError(Exception): <NEW_LINE> <INDENT> def __init__(self, message, result=None): <NEW_LINE> <INDENT> Exception.__init__(self, message) <NEW_LINE> self.result = result
Raised when a service error occurs.
62598fab38b623060ffa9038
class LinkedImageConversionParser(ResolveUIDAndCaptionFilter): <NEW_LINE> <INDENT> def __init__(self, target='images', sourcedomain=''): <NEW_LINE> <INDENT> ResolveUIDAndCaptionFilter.__init__(self) <NEW_LINE> self.items = [] <NEW_LINE> self.target = target <NEW_LINE> self.sourcedomain = sourcedomain <NEW_LINE> <DEDENT> def __call__(self, data): <NEW_LINE> <INDENT> data = re.sub(r'<([^<>\s]+?)\s*/>', self._shorttag_replace, data) <NEW_LINE> soup = BeautifulSoup(data, 'html.parser') <NEW_LINE> for elem in soup.find_all('img'): <NEW_LINE> <INDENT> attributes = elem.attrs <NEW_LINE> src = attributes.get('src', '') <NEW_LINE> title = attributes.get('title', '') <NEW_LINE> alt = attributes.get('alt', '') <NEW_LINE> if attributes.get('height', None): <NEW_LINE> <INDENT> del attributes['height'] <NEW_LINE> <DEDENT> if attributes.get('width', None): <NEW_LINE> <INDENT> del attributes['width'] <NEW_LINE> <DEDENT> if attributes.get('style', None): <NEW_LINE> <INDENT> del attributes['style'] <NEW_LINE> <DEDENT> if src.startswith("images/"): <NEW_LINE> <INDENT> image = None <NEW_LINE> imageid = src.split('/')[-1] <NEW_LINE> imagedata = createImage(self.sourcedomain + '/' + src) <NEW_LINE> if imagedata: <NEW_LINE> <INDENT> imagepath = self.target + "/" + imageid <NEW_LINE> image = { '_path': imagepath, '_type': 'Image', 'image': { 'filename': imageid, 'contenttype': '', 'data': imagedata } } <NEW_LINE> self.items.append(image) <NEW_LINE> elem['src'] = "/" + imagepath + "/@@images/image/medium" <NEW_LINE> elem['class'] = "image-right" <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> logger.warn("src found not starting with images/ src: {}".format(src)) <NEW_LINE> <DEDENT> <DEDENT> return six.text_type(soup)
Eventuell plone.outputfilters_captioned_image überschreiben: snippet für images
62598fab3317a56b869be51a
class UserViewSet(DRFCacheMixin, viewsets.ReadOnlyModelViewSet): <NEW_LINE> <INDENT> queryset = ( User.objects .select_related('department', 'administrative_department') .prefetch_related('groups') .all() .order_by('id') ) <NEW_LINE> serializer_class = auth.serializers.UserSerializer <NEW_LINE> permission_classes = ( auth.permissions.SchoolAdminOnlyPermission, ) <NEW_LINE> def _get_paginated_response(self, queryset): <NEW_LINE> <INDENT> page = self.paginate_queryset(queryset) <NEW_LINE> if page is not None: <NEW_LINE> <INDENT> serializer = self.get_serializer(page, many=True) <NEW_LINE> return self.get_paginated_response(serializer.data) <NEW_LINE> <DEDENT> serializer = self.get_serializer(queryset, many=True) <NEW_LINE> return Response(serializer.data) <NEW_LINE> <DEDENT> def list(self, request): <NEW_LINE> <INDENT> username = request.query_params.get('username', None) <NEW_LINE> if username is None or username == '': <NEW_LINE> <INDENT> raise BadRequest('请输入要查询的用户职工号') <NEW_LINE> <DEDENT> queryset = self.filter_queryset(self.get_queryset()).filter( username=username) <NEW_LINE> return self._get_paginated_response(queryset)
Create API views for User.
62598fab0c0af96317c56321
class MergeSort(object): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def sort(arr): <NEW_LINE> <INDENT> if not arr: <NEW_LINE> <INDENT> raise EmptyArray("Array is empty") <NEW_LINE> <DEDENT> elif not is_sortable(arr[0]): <NEW_LINE> <INDENT> raise IsNotSortable("No order for the object defined") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> aux = np.empty([len(arr)], dtype=object) <NEW_LINE> lo = 0 <NEW_LINE> high = len(arr) <NEW_LINE> mid = lo + int((high - lo)/2) <NEW_LINE> return MergeSort._sort(arr, aux, lo, mid, high) <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def _sort(arr, aux, lo, mid, high): <NEW_LINE> <INDENT> if (lo == mid): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> left_mid = lo + int((mid - lo)/2) <NEW_LINE> right_mid = mid + int((high - mid)/2) <NEW_LINE> MergeSort._sort(arr, aux, lo, left_mid, mid) <NEW_LINE> MergeSort._sort(arr, aux, mid, right_mid, high) <NEW_LINE> MergeSort._merge(arr, aux, lo, mid, high) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _merge(arr, aux, lo, mid, high): <NEW_LINE> <INDENT> aux[lo:high] = arr[lo:high] <NEW_LINE> left_indx = lo <NEW_LINE> right_indx = mid <NEW_LINE> for k in range(lo, high): <NEW_LINE> <INDENT> if left_indx == mid: <NEW_LINE> <INDENT> arr[k] = aux[right_indx] <NEW_LINE> right_indx += 1 <NEW_LINE> <DEDENT> elif right_indx == high: <NEW_LINE> <INDENT> arr[k] = aux[left_indx] <NEW_LINE> left_indx += 1 <NEW_LINE> <DEDENT> elif aux[left_indx] <= aux[right_indx]: <NEW_LINE> <INDENT> arr[k] = aux[left_indx] <NEW_LINE> left_indx += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> arr[k] = aux[right_indx] <NEW_LINE> right_indx += 1 <NEW_LINE> <DEDENT> <DEDENT> return <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _swap(arr, i, j): <NEW_LINE> <INDENT> temp = arr[i] <NEW_LINE> arr[i] = arr[j] <NEW_LINE> arr[j] = temp <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _copy(arr): <NEW_LINE> <INDENT> a = [] <NEW_LINE> for i in range(len(arr)): <NEW_LINE> <INDENT> a.append(arr[i]) <NEW_LINE> <DEDENT> return a
Merge Sort class for sortable objects. Sorts using divide and conquer
62598fab5fdd1c0f98e5df36
class Command(object): <NEW_LINE> <INDENT> def __init__(self, obj): <NEW_LINE> <INDENT> self._obj = obj <NEW_LINE> <DEDENT> def execute(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def undo(self): <NEW_LINE> <INDENT> raise NotImplementedError
Command interface
62598fab91f36d47f2230e75
class xDataProvider(ABC): <NEW_LINE> <INDENT> def __init__(self, name:str): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> <DEDENT> @abstractproperty <NEW_LINE> def texts(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractproperty <NEW_LINE> def names(self): <NEW_LINE> <INDENT> pass
- interface to data lakes
62598fab32920d7e50bc5ff4
class Variable: <NEW_LINE> <INDENT> def __init__(self, name): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> <DEDENT> def inspect(self): <NEW_LINE> <INDENT> return str(self) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "#<Var: {}>".format(self.name)
The Variable data structure. Represents variables in States, and only holds a variable name to refer to variables.
62598fab167d2b6e312b6f11
class MappingTests(CollectionWithEmptyTests, EqualityTests): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def relabel(annotation): <NEW_LINE> <INDENT> if annotation == ElementT: <NEW_LINE> <INDENT> return KeyT <NEW_LINE> <DEDENT> return annotation <NEW_LINE> <DEDENT> def test_generic_2110_equality_definition( self, a: ClassUnderTest, b: ClassUnderTest ): <NEW_LINE> <INDENT> self.assertEqual(a == b, a.keys() == b.keys() and all(a[k] == b[k] for k in a)) <NEW_LINE> <DEDENT> def test_generic_2480_getitem_on_empty_either_succeeds_or_raises_KeyError( self, a: KeyT ) -> None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.empty[a] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> except BaseException: <NEW_LINE> <INDENT> self.fail() <NEW_LINE> <DEDENT> <DEDENT> def test_generic_2481_getitem_over_all_keys_succeeds( self, a: ClassUnderTest ) -> None: <NEW_LINE> <INDENT> a_keys = a.keys() <NEW_LINE> self.assertIsInstance(a_keys, collections.abc.KeysView) <NEW_LINE> try: <NEW_LINE> <INDENT> for k in a_keys: <NEW_LINE> <INDENT> a[k] <NEW_LINE> <DEDENT> <DEDENT> except KeyError: <NEW_LINE> <INDENT> self.fail() <NEW_LINE> <DEDENT> <DEDENT> def test_generic_2490_items_returns_an_ItemsView(self, a: ClassUnderTest) -> None: <NEW_LINE> <INDENT> self.assertIsInstance(a.items(), collections.abc.ItemsView) <NEW_LINE> <DEDENT> def test_generic_2491_values_returns_an_ValuesView(self, a: ClassUnderTest) -> None: <NEW_LINE> <INDENT> self.assertIsInstance(a.values(), collections.abc.ValuesView) <NEW_LINE> <DEDENT> def test_generic_2492_get_definition( self, a: ClassUnderTest, b: KeyT, c: ValueT ) -> None: <NEW_LINE> <INDENT> if b in a: <NEW_LINE> <INDENT> expected = a[b] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> expected = c <NEW_LINE> <DEDENT> self.assertEqual(a.get(b, c), expected)
The property tests of collections.abc.Mapping.
62598fab30bbd72246469948
@six.add_metaclass(abc.ABCMeta) <NEW_LINE> class PvmVifDriver(object): <NEW_LINE> <INDENT> def __init__(self, adapter, host_uuid, instance): <NEW_LINE> <INDENT> self.adapter = adapter <NEW_LINE> self.host_uuid = host_uuid <NEW_LINE> self.instance = instance <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def plug(self, vif, slot_num, new_vif=True): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def unplug(self, vif, cna_w_list=None): <NEW_LINE> <INDENT> if not cna_w_list: <NEW_LINE> <INDENT> cna_w_list = vm.get_cnas(self.adapter, self.instance) <NEW_LINE> <DEDENT> cna_w = self._find_cna_for_vif(cna_w_list, vif) <NEW_LINE> if not cna_w: <NEW_LINE> <INDENT> LOG.warning('Unable to unplug VIF with mac %(mac)s. The VIF was ' 'not found on the instance.', {'mac': vif['address']}, instance=self.instance) <NEW_LINE> return None <NEW_LINE> <DEDENT> LOG.info('Deleting VIF with mac %(mac)s.', {'mac': vif['address']}, instance=self.instance) <NEW_LINE> try: <NEW_LINE> <INDENT> cna_w.delete() <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> LOG.exception('Unable to unplug VIF with mac %(mac)s.', {'mac': vif['address']}, instance=self.instance) <NEW_LINE> raise exception.VirtualInterfaceUnplugException( reason=six.text_type(e)) <NEW_LINE> <DEDENT> return cna_w <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _find_cna_for_vif(cna_w_list, vif): <NEW_LINE> <INDENT> for cna_w in cna_w_list: <NEW_LINE> <INDENT> if vm.norm_mac(cna_w.mac) == vif['address']: <NEW_LINE> <INDENT> return cna_w <NEW_LINE> <DEDENT> <DEDENT> return None <NEW_LINE> <DEDENT> def pre_live_migrate_at_destination(self, vif, vea_vlan_mappings): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def rollback_live_migration_at_destination(self, vif, vea_vlan_mappings): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def pre_live_migrate_at_source(self, vif): <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> def post_live_migrate_at_source(self, vif): <NEW_LINE> <INDENT> pass
Represents an abstract class for a PowerVM Vif Driver. A VIF Driver understands a given virtual interface type (network). It understands how to plug and unplug a given VIF for a virtual machine.
62598fab435de62698e9bd96
class TempoEvaluation(EvaluationMixin): <NEW_LINE> <INDENT> METRIC_NAMES = [ ('pscore', 'P-score'), ('any', 'one tempo correct'), ('all', 'both tempi correct'), ('acc1', 'Accuracy 1'), ('acc2', 'Accuracy 2') ] <NEW_LINE> def __init__(self, detections, annotations, tolerance=TOLERANCE, double=DOUBLE, triple=TRIPLE, sort=True, max_len=None, name=None, **kwargs): <NEW_LINE> <INDENT> detections = load_tempo(detections, sort=sort, max_len=max_len) <NEW_LINE> annotations = load_tempo(annotations, sort=sort, max_len=max_len) <NEW_LINE> ann = load_tempo(annotations, sort=sort) <NEW_LINE> det = load_tempo(detections, sort=sort, max_len=(len(ann) or None)) <NEW_LINE> self.pscore, self.any, self.all = tempo_evaluation(det, ann, tolerance) <NEW_LINE> det = load_tempo(detections, sort=sort, max_len=1) <NEW_LINE> ann = load_tempo(annotations, sort=sort, max_len=1) <NEW_LINE> self.acc1 = tempo_evaluation(det, ann, tolerance)[1] <NEW_LINE> tempi = ann[:, 0].copy() <NEW_LINE> ann = tempi.copy() <NEW_LINE> if double: <NEW_LINE> <INDENT> ann = np.hstack((ann, tempi * 2., tempi / 2.)) <NEW_LINE> <DEDENT> if triple: <NEW_LINE> <INDENT> ann = np.hstack((ann, tempi * 3., tempi / 3.)) <NEW_LINE> <DEDENT> ann = np.vstack((ann, np.ones_like(ann) / len(ann))).T <NEW_LINE> self.acc2 = tempo_evaluation(det, ann, tolerance)[1] <NEW_LINE> self.name = name <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> def tostring(self, **kwargs): <NEW_LINE> <INDENT> ret = '' <NEW_LINE> if self.name is not None: <NEW_LINE> <INDENT> ret += '%s\n ' % self.name <NEW_LINE> <DEDENT> ret += 'pscore=%.3f (one tempo: %.3f, all tempi: %.3f) ' 'acc1=%.3f acc2=%.3f' % (self.pscore, self.any, self.all, self.acc1, self.acc2) <NEW_LINE> return ret <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.tostring()
Tempo evaluation class. Parameters ---------- detections : str, list of tuples or numpy array Detected tempi (rows) and their strengths (columns). If a file name is given, load them from this file. annotations : str, list or numpy array Annotated ground truth tempi (rows) and their strengths (columns). If a file name is given, load them from this file. tolerance : float, optional Evaluation tolerance (max. allowed deviation). double : bool, optional Include double and half tempo variations. triple : bool, optional Include triple and third tempo variations. sort : bool, optional Sort the tempi by their strengths (descending order). max_len : bool, optional Evaluate at most `max_len` tempi. name : str, optional Name of the evaluation to be displayed. Notes ----- For P-Score, the number of detected tempi will be limited to the number of annotations (if not further limited by `max_len`). For Accuracy 1 & 2 only one detected tempo is used. Depending on `sort`, this can be either the first or the strongest one.
62598fab67a9b606de545f6c
class WordFunction(Function): <NEW_LINE> <INDENT> def __init__(self, function, value, size, *args, **kwargs): <NEW_LINE> <INDENT> super(WordFunction, self).__init__(*args, **kwargs) <NEW_LINE> self.function = function <NEW_LINE> self.value = value <NEW_LINE> self.size = size <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> string = (str(self.function) + "(" + str(self.value) + ", " + str(self.size) + ")") <NEW_LINE> return super(WordFunction, self)._to_string(string=string) <NEW_LINE> <DEDENT> def _equals(self, other): <NEW_LINE> <INDENT> if isinstance(self, type(other)): <NEW_LINE> <INDENT> return (self.function == other.function and self.value._equals(other.value) and self.size._equals(other.size)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return (17 + 23 * hash("WordFunction") + 23 ** 2 * hash(self.function) + 23 ** 3 * hash(self.value) + 23 ** 4 * hash(self.size)) <NEW_LINE> <DEDENT> def __deepcopy__(self, memo): <NEW_LINE> <INDENT> return WordFunction(deepcopy(self.function, memo), deepcopy(self.value, memo), deepcopy(self.size, memo))
A function applied on a word.
62598fab60cbc95b063642ee
class Path(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'is_directory': {'key': 'isDirectory', 'type': 'bool'}, 'last_modified': {'key': 'lastModified', 'type': 'str'}, 'e_tag': {'key': 'eTag', 'type': 'str'}, 'content_length': {'key': 'contentLength', 'type': 'long'}, 'owner': {'key': 'owner', 'type': 'str'}, 'group': {'key': 'group', 'type': 'str'}, 'permissions': {'key': 'permissions', 'type': 'str'}, 'encryption_scope': {'key': 'EncryptionScope', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, name: Optional[str] = None, is_directory: Optional[bool] = False, last_modified: Optional[str] = None, e_tag: Optional[str] = None, content_length: Optional[int] = None, owner: Optional[str] = None, group: Optional[str] = None, permissions: Optional[str] = None, encryption_scope: Optional[str] = None, **kwargs ): <NEW_LINE> <INDENT> super(Path, self).__init__(**kwargs) <NEW_LINE> self.name = name <NEW_LINE> self.is_directory = is_directory <NEW_LINE> self.last_modified = last_modified <NEW_LINE> self.e_tag = e_tag <NEW_LINE> self.content_length = content_length <NEW_LINE> self.owner = owner <NEW_LINE> self.group = group <NEW_LINE> self.permissions = permissions <NEW_LINE> self.encryption_scope = encryption_scope
Path. :ivar name: :vartype name: str :ivar is_directory: :vartype is_directory: bool :ivar last_modified: :vartype last_modified: str :ivar e_tag: :vartype e_tag: str :ivar content_length: :vartype content_length: long :ivar owner: :vartype owner: str :ivar group: :vartype group: str :ivar permissions: :vartype permissions: str :ivar encryption_scope: The name of the encryption scope under which the blob is encrypted. :vartype encryption_scope: str
62598fab097d151d1a2c0fc9
class TwitterGeo(models.Model): <NEW_LINE> <INDENT> tweet = models.ForeignKey(Tweet) <NEW_LINE> type = models.CharField(max_length=25) <NEW_LINE> latitude = models.CharField(max_length=25) <NEW_LINE> longitude = models.CharField(max_length=25)
Geo coordinate information entered about individual tweets. Going with char fields on the lat/longs for expediency.
62598fab4f88993c371f04da
@python_2_unicode_compatible <NEW_LINE> class DocumentPageContent(models.Model): <NEW_LINE> <INDENT> document_page = models.OneToOneField( DocumentPage, related_name='ocr_content', verbose_name=_('Document page') ) <NEW_LINE> content = models.TextField(blank=True, verbose_name=_('Content')) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return unicode(self.document_page) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = _('Document page content') <NEW_LINE> verbose_name_plural = _('Document pages contents')
Model that describes a document page content
62598fab63b5f9789fe85106
class RemoteBranchLockableFiles(LockableFiles): <NEW_LINE> <INDENT> def __init__(self, bzrdir, _client): <NEW_LINE> <INDENT> self.controldir = bzrdir <NEW_LINE> self._client = _client <NEW_LINE> self._need_find_modes = True <NEW_LINE> LockableFiles.__init__( self, bzrdir.get_branch_transport(None), 'lock', lockdir.LockDir) <NEW_LINE> <DEDENT> def _find_modes(self): <NEW_LINE> <INDENT> self._dir_mode = None <NEW_LINE> self._file_mode = None
A 'LockableFiles' implementation that talks to a smart server. This is not a public interface class.
62598fabd486a94d0ba2bf6e
class TransactionError(NotStandardError): <NEW_LINE> <INDENT> pass
Error en la transacción
62598fab090684286d5936ac
class ListFoldersContinueArg(bb.Struct): <NEW_LINE> <INDENT> __slots__ = [ '_cursor_value', ] <NEW_LINE> _has_required_fields = True <NEW_LINE> def __init__(self, cursor=None): <NEW_LINE> <INDENT> self._cursor_value = bb.NOT_SET <NEW_LINE> if cursor is not None: <NEW_LINE> <INDENT> self.cursor = cursor <NEW_LINE> <DEDENT> <DEDENT> cursor = bb.Attribute("cursor") <NEW_LINE> def _process_custom_annotations(self, annotation_type, field_path, processor): <NEW_LINE> <INDENT> super(ListFoldersContinueArg, self)._process_custom_annotations(annotation_type, field_path, processor)
:ivar sharing.ListFoldersContinueArg.cursor: The cursor returned by the previous API call specified in the endpoint description.
62598fab32920d7e50bc5ff5
class TestPathResponseResultResponseDetailedStatus(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testPathResponseResultResponseDetailedStatus(self): <NEW_LINE> <INDENT> pass
PathResponseResultResponseDetailedStatus unit test stubs
62598fab460517430c43202d
class CheckinDetailsInputSet(InputSet): <NEW_LINE> <INDENT> def set_CheckinID(self, value): <NEW_LINE> <INDENT> super(CheckinDetailsInputSet, self)._set_input('CheckinID', value) <NEW_LINE> <DEDENT> def set_OauthToken(self, value): <NEW_LINE> <INDENT> super(CheckinDetailsInputSet, self)._set_input('OauthToken', value) <NEW_LINE> <DEDENT> def set_ResponseFormat(self, value): <NEW_LINE> <INDENT> super(CheckinDetailsInputSet, self)._set_input('ResponseFormat', value) <NEW_LINE> <DEDENT> def set_Signature(self, value): <NEW_LINE> <INDENT> super(CheckinDetailsInputSet, self)._set_input('Signature', value)
An InputSet with methods appropriate for specifying the inputs to the CheckinDetails Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
62598fab3cc13d1c6d46570c
class ProductInfoPic(models.Model): <NEW_LINE> <INDENT> ClassOne = models.ForeignKey('ClassOne') <NEW_LINE> ClassTwo = models.ForeignKey('ClassTwo') <NEW_LINE> Product = models.ForeignKey('Products') <NEW_LINE> Picture = models.ImageField(upload_to='product_info_picture') <NEW_LINE> ImageName = models.CharField(max_length= 150)
产品详细介绍图片表格。 ClassOne:隶属的第一级别的类; ClassTwo:隶属的第二级别的类; Product:隶属产品; Picture:图片路径; ImageName:图片名称;
62598fabd486a94d0ba2bf6f