code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class GridLayout(CellLayout): <NEW_LINE> <INDENT> def __init__(self, content: Sequence[Sequence[Any]], **kwargs): <NEW_LINE> <INDENT> grid_shape = [] <NEW_LINE> num_rows = len(content) <NEW_LINE> height = 1/num_rows <NEW_LINE> for row in content: <NEW_LINE> <INDENT> num_columns = len(row) <NEW_LINE> width = 1/num_columns <NEW_LINE> grid_shape.append([(width, height) for _ in range(len(row))]) <NEW_LINE> <DEDENT> super().__init__(content, grid_shape, **kwargs)
Evenly spaced grid layout. Creates a CellLayout, automatically setting widths and heights as an even split based on the shape of the content passed to make a grid
6259904aa8ecb033258725ec
class NamedApplicationKey(models.Model): <NEW_LINE> <INDENT> nickname = models.CharField(max_length=256) <NEW_LINE> description = models.TextField(blank=True) <NEW_LINE> application_key = models.ForeignKey('ApplicationKey') <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.nickname <NEW_LINE> <DEDENT> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> if not (self.nickname and self.description): <NEW_LINE> <INDENT> raise ValidationError("Nickname and description are required") <NEW_LINE> <DEDENT> if not self.pk: <NEW_LINE> <INDENT> key = ApplicationKey(is_named=True) <NEW_LINE> key.save() <NEW_LINE> self.application_key = key <NEW_LINE> <DEDENT> super(NamedApplicationKey, self).save(*args, **kwargs)
The reason to create a named key is if you want to pre-select it as the start key for a Login. For example, perhaps you want to preconfigure a master VM with this start key.
6259904ae64d504609df9dbd
class ReportType(CrashType): <NEW_LINE> <INDENT> def __init__(self, search, report_type): <NEW_LINE> <INDENT> super(ReportType, self).__init__(report_type) <NEW_LINE> self.original_search = search <NEW_LINE> search=Search(search=search, type=report_type) <NEW_LINE> self.reports = search <NEW_LINE> self.buckets = cached_threshold(search) <NEW_LINE> <DEDENT> def restify(self): <NEW_LINE> <INDENT> d = dict() <NEW_LINE> d['reports'] = self.reports <NEW_LINE> d['name'] = self.name <NEW_LINE> d['buckets'] = self.buckets <NEW_LINE> return d
API object representing a particular type inside a search context.
6259904ad99f1b3c44d06a76
class get_openstack_host_usage_args: <NEW_LINE> <INDENT> thrift_spec = ( None, (1, TType.STRING, 'request', None, None, ), ) <NEW_LINE> def __init__(self, request=None,): <NEW_LINE> <INDENT> self.request = request <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRING: <NEW_LINE> <INDENT> self.request = 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.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('get_openstack_host_usage_args') <NEW_LINE> if self.request is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('request', TType.STRING, 1) <NEW_LINE> oprot.writeString(self.request) <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 __hash__(self): <NEW_LINE> <INDENT> value = 17 <NEW_LINE> value = (value * 31) ^ hash(self.request) <NEW_LINE> return value <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other)
Attributes: - request
6259904a26068e7796d4dd1f
class CooperatorHunter(Player): <NEW_LINE> <INDENT> name = 'Cooperator Hunter' <NEW_LINE> classifier = { 'memory_depth': float('inf'), 'stochastic': False, 'inspects_source': False, 'manipulates_source': False, 'manipulates_state': False } <NEW_LINE> def strategy(self, opponent): <NEW_LINE> <INDENT> if len(self.history) >= 4 and len(opponent.history) == opponent.cooperations: <NEW_LINE> <INDENT> return D <NEW_LINE> <DEDENT> return C
A player who hunts for cooperators.
6259904a21a7993f00c67344
class ExpressRouteCircuitListResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'value': {'key': 'value', 'type': '[ExpressRouteCircuit]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(ExpressRouteCircuitListResult, self).__init__(**kwargs) <NEW_LINE> self.value = kwargs.get('value', None) <NEW_LINE> self.next_link = kwargs.get('next_link', None)
Response for ListExpressRouteCircuit API service call. :param value: A list of ExpressRouteCircuits in a resource group. :type value: list[~azure.mgmt.network.v2019_12_01.models.ExpressRouteCircuit] :param next_link: The URL to get the next set of results. :type next_link: str
6259904a711fe17d825e168b
class TrafficParticipant(Actor): <NEW_LINE> <INDENT> def __init__(self, carla_actor, parent, node, prefix): <NEW_LINE> <INDENT> self.classification_age = 0 <NEW_LINE> super(TrafficParticipant, self).__init__(carla_actor=carla_actor, parent=parent, node=node, prefix=prefix) <NEW_LINE> self.odometry_publisher = node.new_publisher( Odometry, self.get_topic_prefix() + "/odometry") <NEW_LINE> <DEDENT> def update(self, frame, timestamp): <NEW_LINE> <INDENT> self.classification_age += 1 <NEW_LINE> self.publish_transform(self.get_ros_transform(None, None, str(self.get_id()))) <NEW_LINE> self.publish_marker() <NEW_LINE> self.send_odometry() <NEW_LINE> super(TrafficParticipant, self).update(frame, timestamp) <NEW_LINE> <DEDENT> def send_odometry(self): <NEW_LINE> <INDENT> odometry = Odometry(header=self.get_msg_header("map")) <NEW_LINE> odometry.child_frame_id = self.get_prefix() <NEW_LINE> odometry.pose.pose = self.get_current_ros_pose() <NEW_LINE> odometry.twist.twist = self.get_current_ros_twist_rotated() <NEW_LINE> self.odometry_publisher.publish(odometry) <NEW_LINE> <DEDENT> def get_object_info(self): <NEW_LINE> <INDENT> obj = Object(header=self.get_msg_header("map")) <NEW_LINE> obj.id = self.get_id() <NEW_LINE> obj.pose = self.get_current_ros_pose() <NEW_LINE> obj.twist = self.get_current_ros_twist() <NEW_LINE> obj.accel = self.get_current_ros_accel() <NEW_LINE> obj.shape.type = SolidPrimitive.BOX <NEW_LINE> obj.shape.dimensions.extend([ self.carla_actor.bounding_box.extent.x * 2.0, self.carla_actor.bounding_box.extent.y * 2.0, self.carla_actor.bounding_box.extent.z * 2.0 ]) <NEW_LINE> if self.get_classification() != Object.CLASSIFICATION_UNKNOWN: <NEW_LINE> <INDENT> obj.object_classified = True <NEW_LINE> obj.classification = self.get_classification() <NEW_LINE> obj.classification_certainty = 255 <NEW_LINE> obj.classification_age = self.classification_age <NEW_LINE> <DEDENT> return obj <NEW_LINE> <DEDENT> def get_classification(self): <NEW_LINE> <INDENT> return Object.CLASSIFICATION_UNKNOWN
actor implementation details for traffic participant
6259904a23e79379d538d8d9
class DeleteWarModeForm(_WarModeBoundForm): <NEW_LINE> <INDENT> def delete_warmode(self): <NEW_LINE> <INDENT> db.delete(self.warmode)
Used to delete a warmode from the admin panel.
6259904a63b5f9789fe86548
class MessageError(IOError): <NEW_LINE> <INDENT> pass
An error occurred from message communication.
6259904a8e05c05ec3f6f848
class SessionConfig(object): <NEW_LINE> <INDENT> _HostName = "" <NEW_LINE> User = "" <NEW_LINE> Port = 22 <NEW_LINE> Protocol = "ssh" <NEW_LINE> UserKnownHostsFile = "/dev/null" <NEW_LINE> StrictHostKeyChecking = False <NEW_LINE> PasswordAuthentication = False <NEW_LINE> IdentityFile = None <NEW_LINE> IdentitiesOnly = False <NEW_LINE> LogLevel = "FATAL" <NEW_LINE> ForwardAgent = True <NEW_LINE> def __init__(self, data=None): <NEW_LINE> <INDENT> if data: <NEW_LINE> <INDENT> for key in data: <NEW_LINE> <INDENT> self.__dict__[key] = data[key] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @property <NEW_LINE> def HostName(self): <NEW_LINE> <INDENT> return self._HostName <NEW_LINE> <DEDENT> @HostName.setter <NEW_LINE> def HostName(self, value): <NEW_LINE> <INDENT> pos = value.find('@') <NEW_LINE> if pos >= 0: <NEW_LINE> <INDENT> self.User, self._Hostname = value.split('@') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._HostName = value <NEW_LINE> <DEDENT> <DEDENT> def check_settings(self): <NEW_LINE> <INDENT> print("Hostname", self.HostName) <NEW_LINE> print("_Hostname", self._HostName) <NEW_LINE> print("Port", self.Port) <NEW_LINE> if len(self.HostName) == 0: <NEW_LINE> <INDENT> print("HostName") <NEW_LINE> return False <NEW_LINE> <DEDENT> if len(self.Port) == 0: <NEW_LINE> <INDENT> print("Port") <NEW_LINE> return False <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> def get_connection_name(self): <NEW_LINE> <INDENT> if self.User: <NEW_LINE> <INDENT> return self.User + '@' + self.HostName + ':' + self.Port <NEW_LINE> <DEDENT> return self.HostName + ':' + self.Port
Connection settings for a session
6259904aec188e330fdf9c79
class ForumCategoryAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> list_display = ('title', ) <NEW_LINE> search_fields = ('title', ) <NEW_LINE> fields = ('title', 'ordering')
``ForumCategory`` admin form.
6259904ab5575c28eb7136b7
class PublicIngredientApiTest(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.client = APIClient() <NEW_LINE> <DEDENT> def test_login_required(self): <NEW_LINE> <INDENT> res = self.client.get(INGREDIENTS_URL) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)
Test the publicly available ingredients API
6259904a009cb60464d02912
class NoHeader(BasicReader): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> Basic.__init__(self) <NEW_LINE> self.header.start_line = None <NEW_LINE> self.data.start_line = 0
Read a table with no header line. Columns are autonamed using header.auto_format which defaults to "col%d". Otherwise this reader the same as the :class:`Basic` class from which it is derived. Example:: # Table data 1 2 "hello there" 3 4 world
6259904a435de62698e9d1e3
@synceventregister <NEW_LINE> class ServerSMDisable(SMSyncEvent): <NEW_LINE> <INDENT> pass
Disable Server
6259904a07f4c71912bb0810
class Password(BASE): <NEW_LINE> <INDENT> __tablename__ = 'password' <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> local_user_id = Column(Integer) <NEW_LINE> password = Column(String(128))
password table
6259904a07f4c71912bb0811
class ConnectModule(BaseModule): <NEW_LINE> <INDENT> pass
Module which will be started just after connecting to the server.
6259904ad53ae8145f91983e
class Test_Sample_Problem(unittest.TestCase): <NEW_LINE> <INDENT> def test_optimization(self): <NEW_LINE> <INDENT> beam = SampleProblemBeam() <NEW_LINE> self.assertAlmostEqual(beam.frequency(), 113.0, delta=0.5) <NEW_LINE> self.assertAlmostEqual(beam.cost(), 1060.0) <NEW_LINE> self.assertAlmostEqual(beam.mass(), 2230.0) <NEW_LINE> prefs = classfunctions.from_input(SAMPLE_INPUT) <NEW_LINE> optimize.optimize(beam, prefs, plot=False) <NEW_LINE> self.assertLess(beam.cost(), 1060.0)
Test by optimizing a beam problem from the literature.
6259904a71ff763f4b5e8b83
class BVConcatToZeroExtend: <NEW_LINE> <INDENT> def filter(self, node): <NEW_LINE> <INDENT> if not node.has_ident() or node.get_ident() != 'concat': <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if not is_bv_const(node[1]): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return get_bv_constant_value(node[1])[0] == 0 <NEW_LINE> <DEDENT> def mutations(self, node): <NEW_LINE> <INDENT> return [ Simplification( { node.id: Node(('_', 'zero_extend', get_bv_constant_value( node[1])[1]), node[2]) }, []) ] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return 'replace concat by zero_extend'
Replace a ``concat`` with zero by ``zero_extend``.
6259904a07d97122c4218080
class Range: <NEW_LINE> <INDENT> def __init__(self, location: int, length: int): <NEW_LINE> <INDENT> self.__location = location <NEW_LINE> self.__length = length <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "[{}, {})".format(self.location, self.location + self.length) <NEW_LINE> <DEDENT> @property <NEW_LINE> def location(self) -> int: <NEW_LINE> <INDENT> return self.__location <NEW_LINE> <DEDENT> @property <NEW_LINE> def length(self) -> int: <NEW_LINE> <INDENT> return self.__length <NEW_LINE> <DEDENT> @property <NEW_LINE> def max(self) -> int: <NEW_LINE> <INDENT> return self.location + self.length <NEW_LINE> <DEDENT> @property <NEW_LINE> def proto(self): <NEW_LINE> <INDENT> protobuf = iterm2.api_pb2.Range() <NEW_LINE> protobuf.location = self.location <NEW_LINE> protobuf.length = self.length <NEW_LINE> return protobuf <NEW_LINE> <DEDENT> @property <NEW_LINE> def toSet(self): <NEW_LINE> <INDENT> return self.to_set <NEW_LINE> <DEDENT> @property <NEW_LINE> def to_set(self): <NEW_LINE> <INDENT> return set(range(self.location, self.location + self.length))
Describes a range of integers. :param location: The first value in the range. :param length: The number of values in the range.
6259904a1f5feb6acb163fd2
class TestV1TypedLocalObjectReference(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 testV1TypedLocalObjectReference(self): <NEW_LINE> <INDENT> pass
V1TypedLocalObjectReference unit test stubs
6259904a16aa5153ce4018cb
@implementer(ITransport) <NEW_LINE> class WrappingWebSocketAdapter: <NEW_LINE> <INDENT> def onConnect(self, requestOrResponse): <NEW_LINE> <INDENT> if isinstance(requestOrResponse, protocol.ConnectionRequest): <NEW_LINE> <INDENT> request = requestOrResponse <NEW_LINE> for p in request.protocols: <NEW_LINE> <INDENT> if p in self.factory._subprotocols: <NEW_LINE> <INDENT> self._binaryMode = (p != 'base64') <NEW_LINE> return p <NEW_LINE> <DEDENT> <DEDENT> raise http.HttpException(http.NOT_ACCEPTABLE[0], "this server only speaks %s WebSocket subprotocols" % self.factory._subprotocols) <NEW_LINE> <DEDENT> elif isinstance(requestOrResponse, protocol.ConnectionResponse): <NEW_LINE> <INDENT> response = requestOrResponse <NEW_LINE> if response.protocol not in self.factory._subprotocols: <NEW_LINE> <INDENT> self.failConnection(protocol.WebSocketProtocol.CLOSE_STATUS_CODE_PROTOCOL_ERROR, "this client only speaks %s WebSocket subprotocols" % self.factory._subprotocols) <NEW_LINE> <DEDENT> self._binaryMode = (response.protocol != 'base64') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception("logic error") <NEW_LINE> <DEDENT> <DEDENT> def onOpen(self): <NEW_LINE> <INDENT> self._proto.connectionMade() <NEW_LINE> <DEDENT> def onMessage(self, payload, isBinary): <NEW_LINE> <INDENT> if isBinary != self._binaryMode: <NEW_LINE> <INDENT> self.failConnection(protocol.WebSocketProtocol.CLOSE_STATUS_CODE_UNSUPPORTED_DATA, "message payload type does not match the negotiated subprotocol") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if not isBinary: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> payload = b64decode(payload) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self.failConnection(protocol.WebSocketProtocol.CLOSE_STATUS_CODE_INVALID_PAYLOAD, "message payload base64 decoding error: {}".format(e)) <NEW_LINE> <DEDENT> <DEDENT> self._proto.dataReceived(payload) <NEW_LINE> <DEDENT> <DEDENT> def onClose(self, wasClean, code, reason): <NEW_LINE> <INDENT> self._proto.connectionLost(None) <NEW_LINE> <DEDENT> def write(self, data): <NEW_LINE> <INDENT> assert(type(data) == bytes) <NEW_LINE> if self._binaryMode: <NEW_LINE> <INDENT> self.sendMessage(data, isBinary = True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> data = b64encode(data) <NEW_LINE> self.sendMessage(data, isBinary = False) <NEW_LINE> <DEDENT> <DEDENT> def writeSequence(self, data): <NEW_LINE> <INDENT> for d in data: <NEW_LINE> <INDENT> self.write(data) <NEW_LINE> <DEDENT> <DEDENT> def loseConnection(self): <NEW_LINE> <INDENT> self.sendClose() <NEW_LINE> <DEDENT> def getPeer(self): <NEW_LINE> <INDENT> return self.transport.getPeer() <NEW_LINE> <DEDENT> def getHost(self): <NEW_LINE> <INDENT> return self.transport.getHost()
An adapter for stream-based transport over WebSocket. This follows "websockify" (https://github.com/kanaka/websockify) and should be compatible with that. It uses WebSocket subprotocol negotiation and 2+ subprotocols: - binary (or a compatible subprotocol) - base64 Octets are either transmitted as the payload of WebSocket binary messages when using the 'binary' subprotocol (or an alternative binary compatible subprotocol), or encoded with Base64 and then transmitted as the payload of WebSocket text messages when using the 'base64' subprotocol.
6259904a0a50d4780f7067ac
class MediaOption(StringOption): <NEW_LINE> <INDENT> def __init__(self, label): <NEW_LINE> <INDENT> StringOption.__init__(self, label, "")
This class describes an option that allows a media object from the database to be selected.
6259904a8da39b475be045ce
class ChineseAnimalIntentHandler(AbstractRequestHandler): <NEW_LINE> <INDENT> def can_handle(self, handler_input): <NEW_LINE> <INDENT> return is_intent_name("ChineseAnimalIntent")(handler_input) <NEW_LINE> <DEDENT> def handle(self, handler_input): <NEW_LINE> <INDENT> year = handler_input.request_envelope.request.intent.slots['year'].value <NEW_LINE> try: <NEW_LINE> <INDENT> data = ddb.get_item( TableName="ChineseAnimal", Key = { 'BirthYear': { 'N': year } } ) <NEW_LINE> <DEDENT> except BaseException as e: <NEW_LINE> <INDENT> print(e) <NEW_LINE> raise(e) <NEW_LINE> <DEDENT> speech_text = "Your animal is a " + data['Item']['Animal']['S'] + '. Wanna know something else? Apparently you are ' + data['Item']['PersonalityTraits']['S'] <NEW_LINE> print (speech_text) <NEW_LINE> handler_input.response_builder.speak(speech_text).ask( speech_text).set_card(SimpleCard( "Hello World", speech_text)) <NEW_LINE> return handler_input.response_builder.response
Handler for Chinese Animal Intent.
6259904a94891a1f408ba0e4
class Profile(object): <NEW_LINE> <INDENT> def __init__(self, info): <NEW_LINE> <INDENT> self.name = info['name'] <NEW_LINE> self.constants = tuple((cst['name'], cst['value']) for cst in info['constants']) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'Profile(name=%s, constants=%r}' % (self.name, self.constants)
Information about a profile.
6259904a91af0d3eaad3b202
class PBPackageRequirement(object): <NEW_LINE> <INDENT> def __init__(self, name): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.compare = None <NEW_LINE> self.version = None <NEW_LINE> <DEDENT> def ev(self, func): <NEW_LINE> <INDENT> return func(self.name, self.compare or ">=", self.version) <NEW_LINE> <DEDENT> def __str__(self, lvl=0): <NEW_LINE> <INDENT> return " "*lvl + "PackageRequirement({0}, {1}, {2})".format(self.name, self.compare, self.version)
Store info on a dependency package: - Package name (typically deb or rpm or something like that) - Version + Comparator
6259904ad7e4931a7ef3d455
@dataclass <NEW_LINE> class Venue(Base): <NEW_LINE> <INDENT> location: Location <NEW_LINE> title: str <NEW_LINE> address: str <NEW_LINE> foursquare_id: Optional[str] = None <NEW_LINE> foursquare_type: Optional[str] = None <NEW_LINE> google_place_id: Optional[str] = None <NEW_LINE> google_place_type: Optional[str] = None
This object represents a venue.
6259904a96565a6dacd2d978
class CedulaField(MultiValueField): <NEW_LINE> <INDENT> widget = CedulaWidget <NEW_LINE> default_error_messages = { 'invalid_choices': _("Debe seleccionar una nacionalidad válida") } <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> error_messages = { 'required': _("Debe indicar un número de Cédula"), 'invalid': _("El valor indicado no es válido"), 'incomplete': _("El número de Cédula esta incompleto") } <NEW_LINE> fields = ( ChoiceField(choices=SHORT_NACIONALIDAD), CharField(max_length=8) ) <NEW_LINE> label = _("Cedula de Identidad:") <NEW_LINE> super(CedulaField, self).__init__( error_messages=error_messages, fields=fields, label=label, require_all_fields=True, *args, **kwargs ) <NEW_LINE> <DEDENT> def compress(self, data_list): <NEW_LINE> <INDENT> if data_list: <NEW_LINE> <INDENT> return ''.join(data_list) <NEW_LINE> <DEDENT> return ''
! Clase que agrupa los campos de la nacionalidad y número de cédula de identidad en un solo campo del formulario @author Ing. Roldan Vargas (rvargas at cenditel.gob.ve) @copyright <a href='http://www.gnu.org/licenses/gpl-3.0.html'>GNU Public License versión 3 (GPLv3)</a> @date 26-04-2016 @version 1.0.0
6259904a462c4b4f79dbcdde
class Timetable(models.Model): <NEW_LINE> <INDENT> form = models.ForeignKey( TimetableSchoolForm, on_delete=models.PROTECT, related_name='lessons', verbose_name=_('Form') ) <NEW_LINE> day_of_week = models.PositiveSmallIntegerField( blank=False, null=False, choices=DAYS_OF_WEEK, verbose_name=_('Day of week') ) <NEW_LINE> lesson_number = models.PositiveSmallIntegerField( blank=False, null=False, choices=tuple(zip(school_models.PERIOD_NUMBERS, [str(n) for n in school_models.PERIOD_NUMBERS])), verbose_name=_('Lesson number') ) <NEW_LINE> subject = models.ForeignKey( school_models.SchoolSubject, on_delete=models.PROTECT, verbose_name=_('Subject') ) <NEW_LINE> classroom = models.ForeignKey( school_models.Classroom, blank=True, null=True, on_delete=models.PROTECT, verbose_name=_('Classroom') ) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return ' | '.join((days_of_week[self.day_of_week], str(self.lesson_number), str(self.subject))) <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return ' | '.join((days_of_week[self.day_of_week], str(self.lesson_number), str(self.subject))) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> ordering = ('day_of_week', 'lesson_number') <NEW_LINE> verbose_name = _('Lesson') <NEW_LINE> verbose_name_plural = _('Lessons')
Represents timetable
6259904a6e29344779b01a20
class WebClient(object): <NEW_LINE> <INDENT> def __init__(self, host, port): <NEW_LINE> <INDENT> self.host = host <NEW_LINE> self.port = port <NEW_LINE> <DEDENT> def _get_json_data_from_endpoint(self, endpoint): <NEW_LINE> <INDENT> url = "http://%s:%d/aircraft/%s" % (self.host, self.port, endpoint) <NEW_LINE> response = requests.get(url) <NEW_LINE> data = json.loads(response.text) <NEW_LINE> return data <NEW_LINE> <DEDENT> def get_gps_data(self): <NEW_LINE> <INDENT> return self._get_json_data_from_endpoint("instruments/gps") <NEW_LINE> <DEDENT> def get_accelerometer_data(self): <NEW_LINE> <INDENT> return self._get_json_data_from_endpoint("sensors/accelerometer") <NEW_LINE> <DEDENT> def get_gyroscope_data(self): <NEW_LINE> <INDENT> return self._get_json_data_from_endpoint("sensors/gyroscope") <NEW_LINE> <DEDENT> def get_thermometer_data(self): <NEW_LINE> <INDENT> return self._get_json_data_from_endpoint("sensors/thermometer") <NEW_LINE> <DEDENT> def get_pressure_sensor_data(self): <NEW_LINE> <INDENT> return self._get_json_data_from_endpoint("sensors/pressure_sensor") <NEW_LINE> <DEDENT> def get_pitot_tube_data(self): <NEW_LINE> <INDENT> return self._get_json_data_from_endpoint("sensors/pitot_tube") <NEW_LINE> <DEDENT> def get_ins_data(self): <NEW_LINE> <INDENT> return self._get_json_data_from_endpoint("sensors/ins") <NEW_LINE> <DEDENT> def get_engine_data(self): <NEW_LINE> <INDENT> return self._get_json_data_from_endpoint("engine") <NEW_LINE> <DEDENT> def get_flight_controls(self): <NEW_LINE> <INDENT> return self._get_json_data_from_endpoint("controls")
The WebClient is used to retrieve flight data from Huginn's web server
6259904a30dc7b76659a0c12
class EchoListener(DecisionBase): <NEW_LINE> <INDENT> id = "echo-listener" <NEW_LINE> def __init__(self, interval=10, threshold=90.0, **kwargs): <NEW_LINE> <INDENT> if "id" not in kwargs: <NEW_LINE> <INDENT> LOG.error("exchange parameter (id=...) not specified!") <NEW_LINE> return <NEW_LINE> <DEDENT> self.id = kwargs['id'] <NEW_LINE> super(EchoListener, self).__init__(interval, threshold, self.fake_func, **kwargs) <NEW_LINE> <DEDENT> def fake_func(self, items): <NEW_LINE> <INDENT> if items: <NEW_LINE> <INDENT> return float(items[-1]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> <DEDENT> def fire(self, sender, value, *args, **kwargs): <NEW_LINE> <INDENT> LOG.info("Basic listener sender:[%s]" % sender) <NEW_LINE> self.escalate(sender, "notify-email", value)
A basic class to detect CPU peaks. Initial threshold is max 90% load over 5 min period.
6259904a0fa83653e46f62bd
class UnDirectedGraph(Graph): <NEW_LINE> <INDENT> def __init__(self, size): <NEW_LINE> <INDENT> super(UnDirectedGraph, self).__init__(size) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if isinstance(other, UnDirectedGraph): <NEW_LINE> <INDENT> return self.is_equal(other) <NEW_LINE> <DEDENT> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other <NEW_LINE> <DEDENT> def __copy__(self): <NEW_LINE> <INDENT> return self.do_copy(UnDirectedGraph(self.size)) <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def is_weighted(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def is_directed(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def is_connected(self): <NEW_LINE> <INDENT> visitor = VertexVisitor() <NEW_LINE> self.depth_first_traversal(visitor, 0) <NEW_LINE> visited = [] <NEW_LINE> visited = visitor.get_visited() <NEW_LINE> return len(visited) == self.get_number_of_vertices() <NEW_LINE> <DEDENT> def is_cyclic(self): <NEW_LINE> <INDENT> result = self.classify_edges() <NEW_LINE> return result.has_back_edges() <NEW_LINE> <DEDENT> def add_edge(self, u, v, weight=0): <NEW_LINE> <INDENT> head_vertex_index = u.get_vertex_number() <NEW_LINE> tail_vertex_index = v.get_vertex_number() <NEW_LINE> self.adjacency_list[head_vertex_index].append( UnDirectedGraphEdge(self, u, v)) <NEW_LINE> self.adjacency_list[tail_vertex_index].append( UnDirectedGraphEdge(self, v, u))
The interface of an undirected graph data structure.
6259904ab57a9660fecd2e5c
class State(enum.Enum): <NEW_LINE> <INDENT> up = 'up' <NEW_LINE> down = 'down' <NEW_LINE> frozen = 'frozen'
Enumeration of node/server states.
6259904a63b5f9789fe8654c
class User(Base): <NEW_LINE> <INDENT> id = Column(Integer, primary_key=True) <NEW_LINE> name = Column(String, nullable=False, unique=True) <NEW_LINE> admin = Column(Boolean, nullable=False, server_default=false())
User model used for: - authentication and authorization - querying user's packages (by user name) - logging user actions Note: existence of a User entry does not imply existence of a corresponding user in the authentication system. For example, when adding group maintainers, the User entry is created without checking for existence of the user. Regular users can: - edit packages (make tracked, set manual priority...) - create groups in their namespace - edit groups where marked as maintainers - get a convenience "My packages" link, although anyone can get to the same page by constructing the right URL Admins can: - edit all groups - cancel builds
6259904ad4950a0f3b111832
class TestCommon: <NEW_LINE> <INDENT> def test_integrate_column(self): <NEW_LINE> <INDENT> t = math.integrate_column(np.arange(5)) <NEW_LINE> assert(np.isclose(t, 8)) <NEW_LINE> <DEDENT> def test_integrate_column_coordinates(self): <NEW_LINE> <INDENT> x = np.linspace(0, 1, 5) <NEW_LINE> t = math.integrate_column(np.arange(5), x) <NEW_LINE> assert(np.isclose(t, 2)) <NEW_LINE> <DEDENT> def test_interpolate_halflevels(self): <NEW_LINE> <INDENT> ref = np.array([0.5, 1.5, 2.5]) <NEW_LINE> t = math.interpolate_halflevels(np.arange(4)) <NEW_LINE> assert(np.allclose(t, ref)) <NEW_LINE> <DEDENT> def test_sum_digits(self): <NEW_LINE> <INDENT> assert(math.sum_digits(1) == 1) <NEW_LINE> assert(math.sum_digits(10) == 1) <NEW_LINE> assert(math.sum_digits(100) == 1) <NEW_LINE> assert(math.sum_digits(123) == 6) <NEW_LINE> assert(math.sum_digits(2**8) == 13) <NEW_LINE> <DEDENT> def test_nlogspace(self): <NEW_LINE> <INDENT> ref = np.array([1, 10, 100]) <NEW_LINE> t = math.nlogspace(1, 100, 3) <NEW_LINE> assert(np.allclose(t, ref)) <NEW_LINE> <DEDENT> def test_promote_maximally(self): <NEW_LINE> <INDENT> x = np.array(1, dtype='int8') <NEW_LINE> t = math.promote_maximally(x) <NEW_LINE> assert(t.dtype == 'int64') <NEW_LINE> <DEDENT> def test_squeezable_logspace(self): <NEW_LINE> <INDENT> ref = np.array([1, 3.16227766, 100]) <NEW_LINE> t = math.squeezable_logspace(1, 100, 3, squeeze=0.5) <NEW_LINE> assert(np.allclose(t, ref)) <NEW_LINE> <DEDENT> def test_squeezable_logspace_nosqueeze(self): <NEW_LINE> <INDENT> ref = np.array([1, 10, 100]) <NEW_LINE> t = math.squeezable_logspace(1, 100, 3) <NEW_LINE> assert(np.allclose(t, ref)) <NEW_LINE> <DEDENT> def test_squeezable_logspace_fixpointbounds(self): <NEW_LINE> <INDENT> with pytest.raises(ValueError): <NEW_LINE> <INDENT> math.squeezable_logspace(100, 1, fixpoint=1.1) <NEW_LINE> <DEDENT> <DEDENT> def test_squeezable_logspace_squeezebounds(self): <NEW_LINE> <INDENT> with pytest.raises(ValueError): <NEW_LINE> <INDENT> math.squeezable_logspace(100, 1, squeeze=2.01)
Testing common mathematical functions.
6259904a7cff6e4e811b6e19
class DatumAttachment(models.Model): <NEW_LINE> <INDENT> owner = models.ForeignKey(User, related_name='+') <NEW_LINE> datum = models.ForeignKey(Datum) <NEW_LINE> name = models.CharField(max_length=256) <NEW_LINE> package = models.FileField(_('file'), upload_to=get_package_file_path('attachment'), max_length=100, storage=protected_storage) <NEW_LINE> original_name = models.CharField(max_length=256) <NEW_LINE> meta_description = models.TextField(blank=True) <NEW_LINE> meta_type = models.TextField(blank=False, default='unknow') <NEW_LINE> created = CreationDateTimeField(_('created')) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> get_latest_by = 'created' <NEW_LINE> ordering = ('name', '-created') <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> @models.permalink <NEW_LINE> def get_absolute_url(self): <NEW_LINE> <INDENT> return ('datasets_datumattachment_detail', (), {'dataset_id': self.datum.dataset_id, 'datum_id': self.datum_id, 'pk': self.pk}) <NEW_LINE> <DEDENT> def is_user_allowed(self, user): <NEW_LINE> <INDENT> return self.datum.is_user_allowed(user) <NEW_LINE> <DEDENT> def file_url(self): <NEW_LINE> <INDENT> return reverse('datasets_datumattachment_file', kwargs={'dataset_id': self.datum.dataset_id, 'datum_id': self.datum_id, 'pk': self.pk})
Attachment with possible results of processing the datum
6259904a29b78933be26aab2
class HTTPNotAcceptable(falcon.HTTPNotAcceptable): <NEW_LINE> <INDENT> pass
wrapper for HTTP Not Acceptable response status code: 406
6259904a8e71fb1e983bcea5
class RectDrawingObject(DrawingObject): <NEW_LINE> <INDENT> def __init__(self, *varg, **kwarg): <NEW_LINE> <INDENT> DrawingObject.__init__(self, *varg, **kwarg) <NEW_LINE> <DEDENT> def objectContainsPoint(self, x, y): <NEW_LINE> <INDENT> if x < self.position.x: return False <NEW_LINE> if x > self.position.x + self.size.x: return False <NEW_LINE> if y < self.position.y: return False <NEW_LINE> if y > self.position.y + self.size.y: return False <NEW_LINE> return True <NEW_LINE> <DEDENT> def _privateDraw(self, dc, position, selected): <NEW_LINE> <INDENT> dc.DrawRectangle(position.x, position.y, self.size.width, self.size.height)
DrawingObject subclass that represents an axis-aligned rectangle.
6259904a379a373c97d9a40a
class Exception(exceptions.Exception): <NEW_LINE> <INDENT> pass
Base class for any kind of exceptions used by this package.
6259904a8da39b475be045d0
class Category(Document): <NEW_LINE> <INDENT> structure = { 'name': unicode, 'description': unicode, 'icon_small': unicode, 'icon_big': unicode, "is_hidden": bool, "order": int, "items_order": [ObjectId], 'parent': ObjectId, } <NEW_LINE> default_values = { "order": 0, "is_hidden": True, "name": u"", "description": u"", "items_order": [], } <NEW_LINE> use_dot_notation = True <NEW_LINE> use_schemaless = True
Category Forms tree
6259904a94891a1f408ba0e5
class IsPresentPlaceholder(ModelBase): <NEW_LINE> <INDENT> _serialized_names = { 'input_name': 'isPresent', } <NEW_LINE> def __init__( self, input_name: str, ): <NEW_LINE> <INDENT> super().__init__(locals())
Represents the command-line argument placeholder that will be replaced at run-time by a boolean value specifying whether the caller has passed an argument for the specified optional input.
6259904abe383301e0254bfa
class AquiferMaterialListAPIView(ListAPIView): <NEW_LINE> <INDENT> swagger_schema = None <NEW_LINE> queryset = AquiferMaterial.objects.all() <NEW_LINE> serializer_class = serializers.AquiferMaterialSerializer
List aquifer materials codes get: return a list of aquifer material codes
6259904a507cdc57c63a617f
class Reduction(Layer): <NEW_LINE> <INDENT> def __init__(self, reduction, axis=-2, **kwargs): <NEW_LINE> <INDENT> self.reduction = reduction <NEW_LINE> self.axis = axis <NEW_LINE> super(Reduction, self).__init__(**kwargs) <NEW_LINE> <DEDENT> def call(self, inputs, weights=None): <NEW_LINE> <INDENT> if weights is None: <NEW_LINE> <INDENT> return get_reduce_op(self.reduction)(inputs, axis=self.axis) <NEW_LINE> <DEDENT> if weights.shape.rank + 1 == inputs.shape.rank: <NEW_LINE> <INDENT> weights = array_ops.expand_dims(weights, -1) <NEW_LINE> <DEDENT> weighted_inputs = math_ops.multiply(inputs, weights) <NEW_LINE> if self.reduction in ("sum", "prod", "min", "max"): <NEW_LINE> <INDENT> return get_reduce_op(self.reduction)(weighted_inputs, axis=self.axis) <NEW_LINE> <DEDENT> if self.reduction == "mean": <NEW_LINE> <INDENT> input_sum = math_ops.reduce_sum(weighted_inputs, axis=self.axis) <NEW_LINE> weight_sum = math_ops.reduce_sum(weights, axis=self.axis) <NEW_LINE> return math_ops.divide(input_sum, weight_sum) <NEW_LINE> <DEDENT> if self.reduction == "sqrtn": <NEW_LINE> <INDENT> logging.warning("Reduction `sqrtn` is deprecated and will be removed " "2021-01-01. Please use the `sum` reduction and divide " "the output by the normalized weights instead.") <NEW_LINE> input_sum = math_ops.reduce_sum(weighted_inputs, axis=self.axis) <NEW_LINE> squared_weights = math_ops.pow(weights, 2) <NEW_LINE> squared_weights_sum = math_ops.reduce_sum(squared_weights, axis=self.axis) <NEW_LINE> sqrt_weights_sum = math_ops.sqrt(squared_weights_sum) <NEW_LINE> return math_ops.divide(input_sum, sqrt_weights_sum) <NEW_LINE> <DEDENT> raise ValueError("%s is not a supported weighted reduction." % self.reduction)
Performs an optionally-weighted reduction. This layer performs a reduction across one axis of its input data. This data may optionally be weighted by passing in an identical float tensor. Args: reduction: The type of reduction to perform. Can be one of the following: "max", "mean", "min", "prod", or "sum". This layer uses the Tensorflow reduce op which corresponds to that reduction (so, for "mean", we use "reduce_mean"). axis: The axis to reduce along. Defaults to '-2', which is usually the axis that contains embeddings (but is not within the embedding itself). Input shape: A tensor of 2 or more dimensions of any numeric dtype. Output: A tensor of 1 less dimension than the input tensor, of the same dtype. Call arguments: inputs: The data to reduce. weights: An optional tensor or constant of the same shape as inputs that will weight the input data before it is reduced.
6259904a435de62698e9d1e7
class TestInsertXlsxWorksheetRequest(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 testInsertXlsxWorksheetRequest(self): <NEW_LINE> <INDENT> pass
InsertXlsxWorksheetRequest unit test stubs
6259904ae64d504609df9dc0
class MonochromaticNarrow(XRaySource): <NEW_LINE> <INDENT> def __init__(self, tilt): <NEW_LINE> <INDENT> super(MonochromaticNarrow, self).__init__(tilt) <NEW_LINE> self.stddev = 0.0033 / 6 <NEW_LINE> self.mean = tilt <NEW_LINE> self.anggenerator = norm(loc=self.mean, scale=self.stddev) <NEW_LINE> <DEDENT> def get_wave(self): <NEW_LINE> <INDENT> wavelength = 1.5418e-10 <NEW_LINE> angle = self.anggenerator.rvs() <NEW_LINE> k = 2 * constants.pi / wavelength <NEW_LINE> kx = k * sin(angle) <NEW_LINE> kz = k * cos(angle) <NEW_LINE> planewave = lambda x, z: exp(1j * kx * x) * exp(1j * kz * z) <NEW_LINE> return planewave, wavelength
This class implements a monochromatic X-ray source with a lower angular spread
6259904adc8b845886d5499d
class RegenerateurDeDocumentsSansEffet(RegenerateurDeDocuments): <NEW_LINE> <INDENT> def supprimer_documents(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def creer_generateur_transactions(self): <NEW_LINE> <INDENT> return GroupeurTransactionsSansEffet()
Empeche la regeneration d'un domaine
6259904a50485f2cf55dc36b
class Module(object): <NEW_LINE> <INDENT> def __init__(self, filename, ast_list): <NEW_LINE> <INDENT> self.filename = filename <NEW_LINE> self.normalized_filename = os.path.abspath(filename) <NEW_LINE> self.ast_list = ast_list <NEW_LINE> self.public_symbols = self._get_exported_symbols() <NEW_LINE> <DEDENT> def _get_exported_symbols(self): <NEW_LINE> <INDENT> if not self.ast_list: <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> return dict([(n.name, n) for n in self.ast_list if n.is_exportable()])
Data container represting a single source file.
6259904ad99f1b3c44d06a7c
class Globals(object): <NEW_LINE> <INDENT> def __init__(self, config): <NEW_LINE> <INDENT> self.cache = CacheManager(**parse_cache_config_options(config)) <NEW_LINE> self.dbhost="localhost" <NEW_LINE> self.dbport=3306 <NEW_LINE> self.dbuser="pstar" <NEW_LINE> self.dbpasswd="zp910131" <NEW_LINE> self.dbdb="mhtrade"
Globals acts as a container for objects available throughout the life of the application
6259904a07d97122c4218083
class DataXRR(Graphical_view): <NEW_LINE> <INDENT> def __init__(self, parent, data): <NEW_LINE> <INDENT> Graphical_view.__init__(self, parent, data) <NEW_LINE> self._data = data <NEW_LINE> self._theta_array = self._data["data"]["theta_array"].value <NEW_LINE> self._simulation = self._data["data"]["XRR"].value <NEW_LINE> self.create_canva() <NEW_LINE> self.axes.plot(self._theta_array, self._simulation, 'r-', label='XRR sim') <NEW_LINE> self.axes.set_yscale('log') <NEW_LINE> self.axes.set_ylabel('XRR') <NEW_LINE> self.axes.set_xlabel('theta (deg.)') <NEW_LINE> self.axes.relim() <NEW_LINE> self.axes.autoscale_view(True, True, True) <NEW_LINE> self.axes.legend() <NEW_LINE> <DEDENT> def data_to_str(self): <NEW_LINE> <INDENT> result = "" <NEW_LINE> for line, theta in enumerate(self._theta_array): <NEW_LINE> <INDENT> result += str(theta) + "\t" + str(self._simulation[line]) + "\n" <NEW_LINE> <DEDENT> return result
data xrr view
6259904ad53ae8145f919841
class CueTrack(CueBase): <NEW_LINE> <INDENT> TimeOffset = namedtuple('TimeOffset', ['mins', 'secs', 'frames']) <NEW_LINE> class Index: <NEW_LINE> <INDENT> number = PropertyDescriptor() <NEW_LINE> time_offset = TimeOffsetPropertyDescriptor() <NEW_LINE> def __init__(self, number, time_offset): <NEW_LINE> <INDENT> self.number = number <NEW_LINE> self.time_offset = time_offset <NEW_LINE> <DEDENT> @property <NEW_LINE> def time_offset_str(self): <NEW_LINE> <INDENT> return '{0:02d}:{1:02d}:{2:02d}'.format(self.time_offset.mins, self.time_offset.secs, self.time_offset.frames) <NEW_LINE> <DEDENT> @property <NEW_LINE> def time_offset_timedelta(self): <NEW_LINE> <INDENT> seconds = self.time_offset.secs + self.time_offset.frames / 75 <NEW_LINE> return timedelta(minutes = self.time_offset.mins, seconds = seconds) <NEW_LINE> <DEDENT> @property <NEW_LINE> def time_offset_in_seconds(self): <NEW_LINE> <INDENT> return self.time_offset_timedelta.total_seconds() <NEW_LINE> <DEDENT> <DEDENT> number = PropertyDescriptor() <NEW_LINE> type = PropertyDescriptor() <NEW_LINE> flags = PropertyDescriptor() <NEW_LINE> isrc = PropertyDescriptor() <NEW_LINE> pregap = TimeOffsetPropertyDescriptor() <NEW_LINE> postgap = TimeOffsetPropertyDescriptor() <NEW_LINE> duration = PropertyDescriptor() <NEW_LINE> def __init__(self, number, type): <NEW_LINE> <INDENT> self.number = number <NEW_LINE> self.type = type <NEW_LINE> self.indexes = [] <NEW_LINE> <DEDENT> @property <NEW_LINE> def offset_in_seconds(self): <NEW_LINE> <INDENT> offset_in_seconds = 0 <NEW_LINE> if len(self.indexes) > 0: <NEW_LINE> <INDENT> offset_in_seconds = self.indexes[0].time_offset_in_seconds <NEW_LINE> <DEDENT> return offset_in_seconds <NEW_LINE> <DEDENT> @property <NEW_LINE> def duration_in_seconds(self): <NEW_LINE> <INDENT> return self.duration.total_seconds() if self.duration else 0 <NEW_LINE> <DEDENT> @property <NEW_LINE> def default_output_format(self): <NEW_LINE> <INDENT> return ' $number\t$time_offset\t$duration\t$title' <NEW_LINE> <DEDENT> @property <NEW_LINE> def default_substitute_dictionary(self): <NEW_LINE> <INDENT> sd = super().default_substitute_dictionary <NEW_LINE> if len(self.indexes) > 0: <NEW_LINE> <INDENT> sd['time_offset'] = self.indexes[0].time_offset_str <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sd['time_offset'] = '' <NEW_LINE> <DEDENT> sd['number'] = '{0:02d}'.format(self.number) if self.number else '' <NEW_LINE> if self.duration: <NEW_LINE> <INDENT> minutes = math.floor(self.duration.total_seconds() / 60) <NEW_LINE> sd['duration'] = '{0:02d}:{1:02d}'.format(minutes, self.duration.seconds - 60 * minutes) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sd['duration'] = ' : ' <NEW_LINE> <DEDENT> return sd
Cue track attributes / processing
6259904a21a7993f00c6734a
class EmissionType(str): <NEW_LINE> <INDENT> pass
The type of emission Values are: chlorine, carbonDioxide, hydrogenSulfide, nitrogenOxide, sulfurDioxide, carbonDisulfide
6259904a26068e7796d4dd25
class RadiusNthSelector(_NthSelector): <NEW_LINE> <INDENT> def key(self, obj: Shape) -> float: <NEW_LINE> <INDENT> if isinstance(obj, (Edge, Wire)): <NEW_LINE> <INDENT> return obj.radius() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("Can not get a radius from this object")
Select the object with the Nth radius. Applicability: All Edge and Wires. Will ignore any shape that can not be represented as a circle or an arc of a circle.
6259904a23e79379d538d8df
class QVideoFrame(): <NEW_LINE> <INDENT> def bits(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def bytesPerLine(self): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> def endTime(self): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> def fieldType(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def handle(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def handleType(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def height(self): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> def imageFormatFromPixelFormat(self, QVideoFrame_PixelFormat): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def isMapped(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def isReadable(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def isValid(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def isWritable(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def map(self, QAbstractVideoBuffer_MapMode): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def mapMode(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def mappedBytes(self): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> def pixelFormat(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def pixelFormatFromImageFormat(self, QImage_Format): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def setEndTime(self, p_int): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def setFieldType(self, QVideoFrame_FieldType): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def setStartTime(self, p_int): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def size(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def startTime(self): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> def unmap(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def width(self): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> def __init__(self, *__args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> __weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None) <NEW_LINE> BottomField = 2 <NEW_LINE> Format_ARGB32 = 1 <NEW_LINE> Format_ARGB32_Premultiplied = 2 <NEW_LINE> Format_ARGB8565_Premultiplied = 7 <NEW_LINE> Format_AYUV444 = 15 <NEW_LINE> Format_AYUV444_Premultiplied = 16 <NEW_LINE> Format_BGR24 = 11 <NEW_LINE> Format_BGR32 = 10 <NEW_LINE> Format_BGR555 = 13 <NEW_LINE> Format_BGR565 = 12 <NEW_LINE> Format_BGRA32 = 8 <NEW_LINE> Format_BGRA32_Premultiplied = 9 <NEW_LINE> Format_BGRA5658_Premultiplied = 14 <NEW_LINE> Format_IMC1 = 24 <NEW_LINE> Format_IMC2 = 25 <NEW_LINE> Format_IMC3 = 26 <NEW_LINE> Format_IMC4 = 27 <NEW_LINE> Format_Invalid = 0 <NEW_LINE> Format_NV12 = 22 <NEW_LINE> Format_NV21 = 23 <NEW_LINE> Format_RGB24 = 4 <NEW_LINE> Format_RGB32 = 3 <NEW_LINE> Format_RGB555 = 6 <NEW_LINE> Format_RGB565 = 5 <NEW_LINE> Format_User = 1000 <NEW_LINE> Format_UYVY = 20 <NEW_LINE> Format_Y16 = 29 <NEW_LINE> Format_Y8 = 28 <NEW_LINE> Format_YUV420P = 18 <NEW_LINE> Format_YUV444 = 17 <NEW_LINE> Format_YUYV = 21 <NEW_LINE> Format_YV12 = 19 <NEW_LINE> InterlacedFrame = 3 <NEW_LINE> ProgressiveFrame = 0 <NEW_LINE> TopField = 1
QVideoFrame() QVideoFrame(QAbstractVideoBuffer, QSize, QVideoFrame.PixelFormat) QVideoFrame(int, QSize, int, QVideoFrame.PixelFormat) QVideoFrame(QImage) QVideoFrame(QVideoFrame)
6259904ad10714528d69f07e
class GetFields(Get): <NEW_LINE> <INDENT> def get_client_request(self, parameters = {}): <NEW_LINE> <INDENT> return self.client_io.get_fields(parameters) <NEW_LINE> <DEDENT> def export_fields(self, parameters={}): <NEW_LINE> <INDENT> df = self.append_df(parameters) <NEW_LINE> df.to_csv(root + raw_fields, encoding='utf-8', index = False)
Inherited Class that deals with contact fields get requests.
6259904a0a366e3fb87dddc7
class ApplicationRunner: <NEW_LINE> <INDENT> def __init__(self, url, realm, extra = None, debug = False, debug_wamp = False, debug_app = False): <NEW_LINE> <INDENT> self.url = url <NEW_LINE> self.realm = realm <NEW_LINE> self.extra = extra or dict() <NEW_LINE> self.debug = debug <NEW_LINE> self.debug_wamp = debug_wamp <NEW_LINE> self.debug_app = debug_app <NEW_LINE> self.make = None <NEW_LINE> <DEDENT> def run(self, make): <NEW_LINE> <INDENT> from twisted.internet import reactor <NEW_LINE> if self.debug or self.debug_wamp or self.debug_app: <NEW_LINE> <INDENT> log.startLogging(sys.stdout) <NEW_LINE> <DEDENT> def create(): <NEW_LINE> <INDENT> cfg = ComponentConfig(self.realm, self.extra) <NEW_LINE> try: <NEW_LINE> <INDENT> session = make(cfg) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> log.err() <NEW_LINE> reactor.stop() <NEW_LINE> <DEDENT> session.debug_app = self.debug_app <NEW_LINE> return session <NEW_LINE> <DEDENT> isSecure, host, port, resource, path, params = parseWsUrl(self.url) <NEW_LINE> transport_factory = WampWebSocketClientFactory(create, url = self.url, debug = self.debug, debug_wamp = self.debug_wamp) <NEW_LINE> client = clientFromString(reactor, "tcp:{}:{}".format(host, port)) <NEW_LINE> client.connect(transport_factory) <NEW_LINE> reactor.run()
This class is a convenience tool mainly for development and quick hosting of WAMP application components. It can host a WAMP application component in a WAMP-over-WebSocket client connecting to a WAMP router.
6259904a29b78933be26aab3
class TestIntradayStockPrice(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 testIntradayStockPrice(self): <NEW_LINE> <INDENT> pass
IntradayStockPrice unit test stubs
6259904a16aa5153ce4018cf
class CMakeCurrentModule(Directive): <NEW_LINE> <INDENT> has_content = False <NEW_LINE> required_arguments = 1 <NEW_LINE> optional_arguments = 0 <NEW_LINE> final_argument_whitespace = False <NEW_LINE> option_spec = {} <NEW_LINE> def run(self): <NEW_LINE> <INDENT> env = self.state.document.settings.env <NEW_LINE> modname = self.arguments[0].strip() <NEW_LINE> if modname == 'None': <NEW_LINE> <INDENT> env.temp_data['py:module'] = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> env.temp_data['py:module'] = modname <NEW_LINE> <DEDENT> return []
This directive is just to tell Sphinx that we're documenting stuff in module foo, but links to module foo won't lead here.
6259904ab830903b9686ee6b
class PyScikitImage(PythonPackage): <NEW_LINE> <INDENT> homepage = "http://scikit-image.org/" <NEW_LINE> url = "https://pypi.io/packages/source/s/scikit-image/scikit-image-0.12.3.tar.gz" <NEW_LINE> version('0.12.3', '04ea833383e0b6ad5f65da21292c25e1') <NEW_LINE> extends('python', ignore=r'bin/.*\.py$') <NEW_LINE> depends_on('py-dask', type=('build', 'run')) <NEW_LINE> depends_on('pil', type=('build', 'run')) <NEW_LINE> depends_on('py-networkx', type=('build', 'run')) <NEW_LINE> depends_on('py-six', type=('build', 'run')) <NEW_LINE> depends_on('py-scipy', type=('build', 'run')) <NEW_LINE> depends_on('py-matplotlib', type=('build', 'run')) <NEW_LINE> depends_on('py-setuptools', type='build') <NEW_LINE> depends_on('[email protected]:', type='build')
Image processing algorithms for SciPy, including IO, morphology, filtering, warping, color manipulation, object detection, etc.
6259904a94891a1f408ba0e6
class MyHtmlParser(HTMLParser): <NEW_LINE> <INDENT> A, TD, TR, TABLE = ('a', 'td', 'tr', 'table') <NEW_LINE> def __init__(self, url): <NEW_LINE> <INDENT> HTMLParser.__init__(self) <NEW_LINE> self.url = url <NEW_LINE> self.current_item = {} <NEW_LINE> self.item_name = None <NEW_LINE> self.page_empty = 29500 <NEW_LINE> self.inside_tr = False <NEW_LINE> self.find_data = False <NEW_LINE> self.check_size = False <NEW_LINE> <DEDENT> def handle_starttag(self, tag, attrs): <NEW_LINE> <INDENT> params = dict(attrs) <NEW_LINE> if tag == self.TR and params.get('align') == 'right': <NEW_LINE> <INDENT> self.inside_tr = True <NEW_LINE> self.current_item = {} <NEW_LINE> <DEDENT> if not self.inside_tr: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if "href" in params: <NEW_LINE> <INDENT> link = params["href"] <NEW_LINE> if params.get('class') == 'details_link': <NEW_LINE> <INDENT> if tag == self.A and link.startswith('details.php'): <NEW_LINE> <INDENT> self.current_item["desc_link"] = "".join((self.url, link)) <NEW_LINE> self.current_item["engine_url"] = self.url <NEW_LINE> self.item_name = "name" <NEW_LINE> self.find_data = True <NEW_LINE> <DEDENT> <DEDENT> elif link.startswith('download.php'): <NEW_LINE> <INDENT> self.current_item["link"] = "".join((self.url, link)) <NEW_LINE> <DEDENT> elif link.endswith('#startcomments'): <NEW_LINE> <INDENT> self.item_name = "size" <NEW_LINE> self.find_data = True <NEW_LINE> self.check_size = True <NEW_LINE> <DEDENT> elif link.endswith('#seeders'): <NEW_LINE> <INDENT> self.item_name = "seeds" <NEW_LINE> self.find_data = True <NEW_LINE> <DEDENT> elif link.endswith('#leechers'): <NEW_LINE> <INDENT> self.item_name = "leech" <NEW_LINE> self.find_data = True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def handle_data(self, data): <NEW_LINE> <INDENT> if self.inside_tr and self.item_name and self.find_data and not self.check_size: <NEW_LINE> <INDENT> self.find_data = False <NEW_LINE> self.current_item[self.item_name] = data.strip().replace(',', '') <NEW_LINE> <DEDENT> elif self.inside_tr and self.item_name and self.find_data and self.check_size: <NEW_LINE> <INDENT> if data.endswith('MB') or data.endswith('GB'): <NEW_LINE> <INDENT> self.check_size = False <NEW_LINE> self.current_item[self.item_name] = data.strip() <NEW_LINE> self.item_name = None <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def handle_endtag(self, tag): <NEW_LINE> <INDENT> if self.inside_tr and tag == self.TR: <NEW_LINE> <INDENT> self.inside_tr = False <NEW_LINE> self.item_name = None <NEW_LINE> self.find_data = False <NEW_LINE> array_length = len(self.current_item) <NEW_LINE> if array_length < 1: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> prettyPrinter(self.current_item) <NEW_LINE> self.current_item = {}
Sub-class for parsing results
6259904a507cdc57c63a6181
class DarcyFlowModel(OneDimensionalFlowRelationship): <NEW_LINE> <INDENT> non_Darcy = False <NEW_LINE> def __init__(self, k=1.0): <NEW_LINE> <INDENT> self._attribute_list = ['k'] <NEW_LINE> self.k = k <NEW_LINE> <DEDENT> def v_from_i(self, hyd_grad, **kwargs): <NEW_LINE> <INDENT> return self.k * hyd_grad <NEW_LINE> <DEDENT> def i_from_v(self, velocity, **kwargs): <NEW_LINE> <INDENT> return velocity / self.k <NEW_LINE> <DEDENT> def dv_di(self, hyd_grad, **kwargs): <NEW_LINE> <INDENT> return np.ones_like(hyd_grad, dtype=float) * self.k * np.sign(hyd_grad) <NEW_LINE> <DEDENT> def vdrain_strain_rate(self, eta, head, **kwargs): <NEW_LINE> <INDENT> return head * self.k * eta <NEW_LINE> <DEDENT> def v_and_i_for_plotting(self, **kwargs): <NEW_LINE> <INDENT> npts = kwargs.get('npts', 100) <NEW_LINE> xmin, xmax = kwargs.get('xmin', 0), kwargs.get('xmax', 50) <NEW_LINE> x = np.linspace(xmin, xmax, npts) <NEW_LINE> y = self.v_from_i(x) <NEW_LINE> return x, y
Darcian flow model Parameters ---------- k : float, optional Darcian permeability. Default k=1. Notes ----- Darcian flow is described by: .. math:: v = ki
6259904a3eb6a72ae038ba3d
class DuplicateColumnNameError(Exception): <NEW_LINE> <INDENT> def __init__(self, name: str, index: int, filename: Optional[str] = None) -> None: <NEW_LINE> <INDENT> super().__init__(name, index, filename) <NEW_LINE> self.name = name <NEW_LINE> self.index = index <NEW_LINE> self.filename = filename
Raised when a duplicate column name is found in a TXT file. Column names are considered duplicates when they are exactly the same. Column names that differ only in casing (e.g. `mycolumn` and `MyColumn`) do not cause this exception. Attributes: name: Duplicate column name. index: Index of the duplicate column. This *should* be the greater of the two indices of the duplicate columns (though not guaranteed). filename: Name of the TXT file, if available.
6259904acb5e8a47e493cb78
class AsyncResponseHandler(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.mutex = Lock() <NEW_LINE> self.mutex.acquire() <NEW_LINE> <DEDENT> def __call__(self, status, response, hostlist): <NEW_LINE> <INDENT> self.status = status <NEW_LINE> self.response = response <NEW_LINE> self.hostlist = hostlist <NEW_LINE> self.mutex.release() <NEW_LINE> <DEDENT> def waitFor(self): <NEW_LINE> <INDENT> self.mutex.acquire() <NEW_LINE> self.mutex.release() <NEW_LINE> return self.status, self.response, self.hostlist
Utility class to handle asynchronous method calls.
6259904a0c0af96317c57752
class ListArchiverForm(forms.Form): <NEW_LINE> <INDENT> archivers = forms.MultipleChoiceField( widget=forms.CheckboxSelectMultiple, label=_('Activate archivers for this list')) <NEW_LINE> def __init__(self, archivers, *args, **kwargs): <NEW_LINE> <INDENT> super(ListArchiverForm, self).__init__(*args, **kwargs) <NEW_LINE> self.fields['archivers'].choices = sorted( [(key, key) for key in archivers.keys()])
Select archivers for a list.
6259904aac7a0e7691f738be
class SubRubricInline(admin.TabularInline): <NEW_LINE> <INDENT> model = SubRubric
Встроенный редактор подрубрик
6259904ad6c5a102081e34ff
class Scoreboard(object): <NEW_LINE> <INDENT> def refresh(self, jsonScoreboard, teams): <NEW_LINE> <INDENT> self.games.clear() <NEW_LINE> for jsonGame in jsonScoreboard['games']: <NEW_LINE> <INDENT> self.games.append(Game(jsonGame, teams)) <NEW_LINE> <DEDENT> <DEDENT> def __init__(self): <NEW_LINE> <INDENT> self.games = []
Todays Games
6259904a82261d6c527308b7
class CompanyPayment(models.Model): <NEW_LINE> <INDENT> company_membership = models.ForeignKey(CompanyMembership, null=True, on_delete=models.SET_NULL) <NEW_LINE> amount = models.DecimalField(max_digits=12, decimal_places=2, default=0.00, help_text='Amount paid for membership (including VAT)') <NEW_LINE> payment_date = models.DateField(help_text='Date where payment is completed by the registered company') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> ordering = ['-payment_date', 'company_membership',] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.company_membership
Model represents company payment record
6259904ad53ae8145f919843
class Prod(Config): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(Prod, self).__init__() <NEW_LINE> self.DEBUG = False <NEW_LINE> self.TESTING = False <NEW_LINE> self.ENVIROMENT = "Production" <NEW_LINE> self.SECURITY_LOGIN_WITHOUT_CONFIRMATION = False <NEW_LINE> self.SECURITY_CONFIRMABLE = True <NEW_LINE> self.LOG_LEVEL = logging.INFO <NEW_LINE> self.CACHE_TYPE = "simple" <NEW_LINE> self.BOOTSTRAP_SERVE_LOCAL = False
Production Config.
6259904a21a7993f00c6734c
class CommandDontExistException(Exception): <NEW_LINE> <INDENT> pass
Исключение для случая если команда с заданным именем не существует
6259904a71ff763f4b5e8b89
class Color(util.AutoNumberEnum): <NEW_LINE> <INDENT> red = () <NEW_LINE> blue = () <NEW_LINE> green = () <NEW_LINE> yellow = ()
Enumerated colors of cards. Attributes: red blue green yellow
6259904a0a366e3fb87dddc9
class Lesson(BaseModel): <NEW_LINE> <INDENT> lesson_id = PrimaryKeyField() <NEW_LINE> title = CharField(max_length=256) <NEW_LINE> description = CharField(max_length=256, null=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> table_name = 'lessons'
课程
6259904a29b78933be26aab4
class Member(Person, TimeStampedModel): <NEW_LINE> <INDENT> subteam = models.ForeignKey( "SubTeam", on_delete=models.SET_NULL, related_name='members', blank=True, null=True, verbose_name='subteam of member', ) <NEW_LINE> description = models.CharField( max_length=75, blank=True, verbose_name='description (e.g. department)', ) <NEW_LINE> eng_description = models.CharField( max_length=75, blank=True, verbose_name='english description (e.g. department)', ) <NEW_LINE> linkedin_link = models.TextField( blank=True, null=True, verbose_name="Linkedin profile link of this person" ) <NEW_LINE> working = models.TextField( blank=True, null=True, verbose_name='working experiences' ) <NEW_LINE> eng_working = models.TextField( blank=True, null=True, verbose_name='english working experiences' ) <NEW_LINE> class MemberManager(models.Manager): <NEW_LINE> <INDENT> def get_queryset(self): <NEW_LINE> <INDENT> return (super().get_queryset() .select_related('leader', 'subteam') .prefetch_related('subteam__leaders')) <NEW_LINE> <DEDENT> <DEDENT> objects = MemberManager() <NEW_LINE> def role(self): <NEW_LINE> <INDENT> if self.subteam == None: <NEW_LINE> <INDENT> subteam_str = "Ekip Üyesi" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> subteam_str = str(self.subteam.name) <NEW_LINE> <DEDENT> is_old = " Eski" if self.is_retired else "" <NEW_LINE> try: <NEW_LINE> <INDENT> is_team_leader = bool(self.leader) <NEW_LINE> <DEDENT> except ObjectDoesNotExist: <NEW_LINE> <INDENT> is_team_leader = False <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> is_tech_leader = bool(self.techLeader) <NEW_LINE> <DEDENT> except ObjectDoesNotExist: <NEW_LINE> <INDENT> is_tech_leader = False <NEW_LINE> <DEDENT> if self.subteam and self in self.subteam.leaders.all(): <NEW_LINE> <INDENT> return subteam_str + " Lideri" <NEW_LINE> <DEDENT> elif is_team_leader: <NEW_LINE> <INDENT> return "Takım Lideri" <NEW_LINE> <DEDENT> elif is_tech_leader: <NEW_LINE> <INDENT> return "Teknik Lider" <NEW_LINE> <DEDENT> elif not self.subteam: <NEW_LINE> <INDENT> return "Ekip Üyesi" <NEW_LINE> <DEDENT> return subteam_str + is_old + " Üyesi" <NEW_LINE> <DEDENT> def eng_role(self): <NEW_LINE> <INDENT> if self.subteam == None: <NEW_LINE> <INDENT> subteam_str = "Member of Subteam" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> subteam_str = str(self.subteam.eng_name) <NEW_LINE> <DEDENT> is_old = " Old" if self.is_retired else "" <NEW_LINE> try: <NEW_LINE> <INDENT> is_team_leader = bool(self.leader) <NEW_LINE> <DEDENT> except ObjectDoesNotExist: <NEW_LINE> <INDENT> is_team_leader = False <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> is_tech_leader = bool(self.techLeader) <NEW_LINE> <DEDENT> except ObjectDoesNotExist: <NEW_LINE> <INDENT> is_tech_leader = False <NEW_LINE> <DEDENT> if self.subteam and self in self.subteam.leaders.all(): <NEW_LINE> <INDENT> return " Leader of " + subteam_str <NEW_LINE> <DEDENT> elif is_team_leader: <NEW_LINE> <INDENT> return "Team Leader" <NEW_LINE> <DEDENT> elif is_tech_leader: <NEW_LINE> <INDENT> return "Technical Leader" <NEW_LINE> <DEDENT> elif not self.subteam: <NEW_LINE> <INDENT> return "Sub-Team Member" <NEW_LINE> <DEDENT> return is_old + " Member of " + subteam_str
Team member model, a member is a person.
6259904a8da39b475be045d4
class CsvEventFormatter(CsvFormatter): <NEW_LINE> <INDENT> implements(IMessageFormatter) <NEW_LINE> FIELDS = ( 'timestamp', 'event_id', 'status', 'user_message_id', 'nack_reason', ) <NEW_LINE> def _format_field_status(self, message): <NEW_LINE> <INDENT> return message.status() <NEW_LINE> <DEDENT> def _format_field_nack_reason(self, message): <NEW_LINE> <INDENT> return message.get('nack_reason', u'') or u''
Formatter for writing messages to requests as CSV.
6259904a23849d37ff8524a0
class MatchCondition(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'match_variable': {'required': True}, 'operator': {'required': True}, 'match_value': {'required': True}, } <NEW_LINE> _attribute_map = { 'match_variable': {'key': 'matchVariable', 'type': 'str'}, 'selector': {'key': 'selector', 'type': 'str'}, 'operator': {'key': 'operator', 'type': 'str'}, 'negate_condition': {'key': 'negateCondition', 'type': 'bool'}, 'match_value': {'key': 'matchValue', 'type': '[str]'}, 'transforms': {'key': 'transforms', 'type': '[str]'}, } <NEW_LINE> def __init__( self, *, match_variable: Union[str, "MatchVariable"], operator: Union[str, "Operator"], match_value: List[str], selector: Optional[str] = None, negate_condition: Optional[bool] = None, transforms: Optional[List[Union[str, "TransformType"]]] = None, **kwargs ): <NEW_LINE> <INDENT> super(MatchCondition, self).__init__(**kwargs) <NEW_LINE> self.match_variable = match_variable <NEW_LINE> self.selector = selector <NEW_LINE> self.operator = operator <NEW_LINE> self.negate_condition = negate_condition <NEW_LINE> self.match_value = match_value <NEW_LINE> self.transforms = transforms
Define a match condition. All required parameters must be populated in order to send to Azure. :param match_variable: Required. Request variable to compare with. Possible values include: "RemoteAddr", "RequestMethod", "QueryString", "PostArgs", "RequestUri", "RequestHeader", "RequestBody", "Cookies", "SocketAddr". :type match_variable: str or ~azure.mgmt.frontdoor.models.MatchVariable :param selector: Match against a specific key from the QueryString, PostArgs, RequestHeader or Cookies variables. Default is null. :type selector: str :param operator: Required. Comparison type to use for matching with the variable value. Possible values include: "Any", "IPMatch", "GeoMatch", "Equal", "Contains", "LessThan", "GreaterThan", "LessThanOrEqual", "GreaterThanOrEqual", "BeginsWith", "EndsWith", "RegEx". :type operator: str or ~azure.mgmt.frontdoor.models.Operator :param negate_condition: Describes if the result of this condition should be negated. :type negate_condition: bool :param match_value: Required. List of possible match values. :type match_value: list[str] :param transforms: List of transforms. :type transforms: list[str or ~azure.mgmt.frontdoor.models.TransformType]
6259904a379a373c97d9a40e
class AtomScan(win32k_core.Win32kPluginMixin, common.PoolScannerPlugin): <NEW_LINE> <INDENT> allocation = ['_POOL_HEADER', '_RTL_ATOM_TABLE'] <NEW_LINE> __name = "atomscan" <NEW_LINE> @classmethod <NEW_LINE> def args(cls, parser): <NEW_LINE> <INDENT> parser.add_argument( "-S", "--sort-by", choices=["atom", "refcount", "offset"], default="offset", help="Sort by [offset | atom | refcount]") <NEW_LINE> <DEDENT> def __init__(self, sort_by=None, **kwargs): <NEW_LINE> <INDENT> super(AtomScan, self).__init__(**kwargs) <NEW_LINE> self.sort_by = sort_by <NEW_LINE> <DEDENT> def generate_hits(self): <NEW_LINE> <INDENT> scanner = PoolScanAtom( profile=self.win32k_profile, session=self.session, address_space=self.address_space) <NEW_LINE> for pool_header in scanner.scan(): <NEW_LINE> <INDENT> version = self.profile.metadata('version') <NEW_LINE> fixup = 0 <NEW_LINE> if self.profile.metadata('arch') == 'I386': <NEW_LINE> <INDENT> if version > "5.1": <NEW_LINE> <INDENT> fixup = 8 <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if version > "5.1": <NEW_LINE> <INDENT> fixup = 16 <NEW_LINE> <DEDENT> <DEDENT> atom_table = self.win32k_profile._RTL_ATOM_TABLE( offset=pool_header.obj_offset + pool_header.size() + fixup, vm=pool_header.obj_vm) <NEW_LINE> if atom_table.is_valid(): <NEW_LINE> <INDENT> yield atom_table <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def render(self, renderer): <NEW_LINE> <INDENT> renderer.table_header( [("TableOfs(P)", "physical_offset", "[addr]"), ("AtomOfs(V)", "virtual_offset", "[addrpad]"), ("Atom", "atom", "[addr]"), ("Refs", "refs", "6"), ("Pinned", "pinned", "6"), ("Name", "name", ""), ]) <NEW_LINE> for atom_table in self.generate_hits(): <NEW_LINE> <INDENT> atoms = [] <NEW_LINE> for atom in atom_table.atoms(vm=self.kernel_address_space): <NEW_LINE> <INDENT> if atom.is_string_atom(): <NEW_LINE> <INDENT> atoms.append(atom) <NEW_LINE> <DEDENT> <DEDENT> if self.sort_by == "atom": <NEW_LINE> <INDENT> attr = "Atom" <NEW_LINE> <DEDENT> elif self.sort_by == "refcount": <NEW_LINE> <INDENT> attr = "ReferenceCount" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> attr = "obj_offset" <NEW_LINE> <DEDENT> for atom in sorted(atoms, key=lambda x: getattr(x, attr)): <NEW_LINE> <INDENT> renderer.table_row(atom_table.obj_offset, atom.obj_offset, atom.Atom, atom.ReferenceCount, atom.Pinned, atom.Name)
Pool scanner for _RTL_ATOM_TABLE
6259904a8a349b6b43687632
class ChildSiteDescriptor(object): <NEW_LINE> <INDENT> pass
A placeholder for the old descriptor. Sites migrated from an older Lineage need this.
6259904a3eb6a72ae038ba3f
class OccurrenceDetailView(OccurrenceViewMixin, DetailView): <NEW_LINE> <INDENT> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super(OccurrenceViewMixin, self).get_context_data(**kwargs) <NEW_LINE> context['form'] = peticionForm <NEW_LINE> return context <NEW_LINE> <DEDENT> def form_valid(self, form): <NEW_LINE> <INDENT> return super(OccurrenceDetailView, self).form_valid(form) <NEW_LINE> <DEDENT> def form_invalid(self, form): <NEW_LINE> <INDENT> return super(OccurrenceDetailView, self).form_valid(form) <NEW_LINE> <DEDENT> def post(self, request, *args, **kwargs): <NEW_LINE> <INDENT> form = peticionForm(request.POST) <NEW_LINE> if form.is_valid(): <NEW_LINE> <INDENT> cd = form.cleaned_data <NEW_LINE> self.object = self.get_object() <NEW_LINE> asunto = u'Por: %s Empresa: %s - asistencia a evento %s | Fecha: %s' % (cd['nombre'], cd['empresa'], self.object, self.object.original_start) <NEW_LINE> content = u'Nombre: %s \nEmail contacto: %s \nEmpresa: %s \nPaís: %s \nProvincia: %s \nCargo: %s \nTeléfono: %s \nEvento que desea asistir: %s \nFecha inicio: %s \nFecha final: %s\n Aceptó los términos y condiciones' % (cd['nombre'], cd['email'], cd['empresa'], cd['pais'], cd['provincia'], cd['cargo'], cd['telefono'], self.object, self.object.original_start, self.object.original_end) <NEW_LINE> email = EmailMessage(asunto, content, '[email protected]', ['[email protected]'], headers={'Reply-To': cd['email']}) <NEW_LINE> email.send() <NEW_LINE> return HttpResponseRedirect('/felicidades/') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> context = self.get_context_data(object=self.object) <NEW_LINE> return self.render_to_response(context) <NEW_LINE> <DEDENT> <DEDENT> pass
View to show information of an occurrence of an event.
6259904a6fece00bbacccd9c
class UnifiWirelessClients: <NEW_LINE> <INDENT> def __init__(self, hass): <NEW_LINE> <INDENT> self.hass = hass <NEW_LINE> self.data = {} <NEW_LINE> self._store = hass.helpers.storage.Store(STORAGE_VERSION, STORAGE_KEY) <NEW_LINE> <DEDENT> async def async_load(self): <NEW_LINE> <INDENT> data = await self._store.async_load() <NEW_LINE> if data is not None: <NEW_LINE> <INDENT> self.data = data <NEW_LINE> <DEDENT> <DEDENT> @callback <NEW_LINE> def get_data(self, config_entry): <NEW_LINE> <INDENT> data = self.data.get(config_entry.entry_id, {"wireless_devices": []}) <NEW_LINE> return set(data["wireless_devices"]) <NEW_LINE> <DEDENT> @callback <NEW_LINE> def update_data(self, data, config_entry): <NEW_LINE> <INDENT> self.data[config_entry.entry_id] = {"wireless_devices": list(data)} <NEW_LINE> self._store.async_delay_save(self._data_to_save, SAVE_DELAY) <NEW_LINE> <DEDENT> @callback <NEW_LINE> def _data_to_save(self): <NEW_LINE> <INDENT> return self.data
Class to store clients known to be wireless. This is needed since wireless devices going offline might get marked as wired by UniFi.
6259904a3cc13d1c6d466b1c
@inherit_doc <NEW_LINE> class Zero(MeanFunction): <NEW_LINE> <INDENT> def __init__(self, input_dim, output_dim, name='zero'): <NEW_LINE> <INDENT> super().__init__(input_dim, output_dim, name) <NEW_LINE> <DEDENT> def f(self, Xs): <NEW_LINE> <INDENT> self._validate_inputs(Xs) <NEW_LINE> return [np.zeros(len(X)) for X in Xs] <NEW_LINE> <DEDENT> def mean_gradient(self, Xs): <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> def update_gradient(self, grad): <NEW_LINE> <INDENT> pass
The zero mapping. Note that leaving the `mean_function` parameter as none in all of the models does the same job.
6259904a462c4b4f79dbcde4
class ThumbnailMixin(object): <NEW_LINE> <INDENT> thumb_image_field_name = 'image' <NEW_LINE> thumb_image_filter_spec = 'fill-100x100' <NEW_LINE> thumb_image_width = 50 <NEW_LINE> thumb_classname = 'admin-thumb' <NEW_LINE> thumb_col_header_text = _('image') <NEW_LINE> thumb_default = None <NEW_LINE> def admin_thumb(self, obj): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> image = getattr(obj, self.thumb_image_field_name, None) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> raise ImproperlyConfigured( u"The `thumb_image_field_name` attribute on your `%s` class " "must name a field on your model." % self.__class__.__name__ ) <NEW_LINE> <DEDENT> img_attrs = { 'src': self.thumb_default, 'width': self.thumb_image_width, 'class': self.thumb_classname, } <NEW_LINE> if image: <NEW_LINE> <INDENT> fltr = Filter(spec=self.thumb_image_filter_spec) <NEW_LINE> img_attrs.update({'src': image.get_rendition(fltr).url}) <NEW_LINE> return mark_safe('<img{}>'.format(flatatt(img_attrs))) <NEW_LINE> <DEDENT> elif self.thumb_default: <NEW_LINE> <INDENT> return mark_safe('<img{}>'.format(flatatt(img_attrs))) <NEW_LINE> <DEDENT> return '' <NEW_LINE> <DEDENT> admin_thumb.short_description = thumb_col_header_text
Mixin class to help display thumbnail images in ModelAdmin listing results. `thumb_image_field_name` must be overridden to name a ForeignKey field on your model, linking to `wagtailimages.Image`.
6259904aa8ecb033258725f6
class CoverageTest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.chr1 = (GenomeRegion('hg19', 'chr1', 0, GenomeInfo.GENOMES['hg19']['size']['chr1'])) <NEW_LINE> self.chromosomes = (GenomeRegion('hg19', c, 0, l) for c, l in GenomeInfo.GENOMES['hg19']['size'].iteritems()) <NEW_LINE> <DEDENT> def _runTest(self, starts=None, ends=None, strands=None, values=None, ids=None, edges=None, weights=None, expCoverage=None, customAverageFunction=None, customChrLength=None, allowOverlap=True, debug=False): <NEW_LINE> <INDENT> track = createSimpleTestTrackContent(startList=starts, endList=ends, valList=values, strandList=strands, idList=ids, edgeList=edges, weightsList=weights, customChrLength=customChrLength) <NEW_LINE> c = Coverage(track, debug=debug) <NEW_LINE> self.assertTrue((c is not None)) <NEW_LINE> result = c.calculate() <NEW_LINE> self.assertTrue(result is not None) <NEW_LINE> resFound = False <NEW_LINE> for (k, v) in result.iteritems(): <NEW_LINE> <INDENT> if cmp(k, self.chr1) == 0 or cmp(k, self.chr1Small) == 0: <NEW_LINE> <INDENT> self.assertTrue(v == expCoverage) <NEW_LINE> resFound = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.assertEqual(v.size, 0) <NEW_LINE> <DEDENT> <DEDENT> self.assertTrue(resFound) <NEW_LINE> <DEDENT> def testPointsSimple(self): <NEW_LINE> <INDENT> self._runTest(starts=[4,10], expCoverage=2) <NEW_LINE> <DEDENT> def testPointsComplex(self): <NEW_LINE> <INDENT> starts = [4,10,50,73,123,21441,4124] <NEW_LINE> self._runTest(starts=starts, expCoverage=len(starts)) <NEW_LINE> <DEDENT> def testSegmentsSimple(self): <NEW_LINE> <INDENT> self._runTest(starts=[2], ends=[4], expCoverage=2) <NEW_LINE> <DEDENT> def testSegmentsComplex(self): <NEW_LINE> <INDENT> self._runTest(starts=[2,10,100], ends=[4,45,150], expCoverage=2+35+50) <NEW_LINE> <DEDENT> def testSegmentsOverlapping(self): <NEW_LINE> <INDENT> self._runTest(starts=[2,6], ends=[6,8], expCoverage=6)
Tests of the coverage operation Test objectives * Find correct cover for a non overlapping track * Find correct cover for a overlapping track
6259904a50485f2cf55dc36f
class SimpleApplication(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.ApplicationId = None <NEW_LINE> self.ApplicationName = None <NEW_LINE> self.ApplicationType = None <NEW_LINE> self.MicroserviceType = None <NEW_LINE> self.ApplicationDesc = None <NEW_LINE> self.ProgLang = None <NEW_LINE> self.ApplicationResourceType = None <NEW_LINE> self.CreateTime = None <NEW_LINE> self.UpdateTime = None <NEW_LINE> self.ApigatewayServiceId = None <NEW_LINE> self.ApplicationRuntimeType = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.ApplicationId = params.get("ApplicationId") <NEW_LINE> self.ApplicationName = params.get("ApplicationName") <NEW_LINE> self.ApplicationType = params.get("ApplicationType") <NEW_LINE> self.MicroserviceType = params.get("MicroserviceType") <NEW_LINE> self.ApplicationDesc = params.get("ApplicationDesc") <NEW_LINE> self.ProgLang = params.get("ProgLang") <NEW_LINE> self.ApplicationResourceType = params.get("ApplicationResourceType") <NEW_LINE> self.CreateTime = params.get("CreateTime") <NEW_LINE> self.UpdateTime = params.get("UpdateTime") <NEW_LINE> self.ApigatewayServiceId = params.get("ApigatewayServiceId") <NEW_LINE> self.ApplicationRuntimeType = params.get("ApplicationRuntimeType")
简单应用
6259904ad53ae8145f919846
class TestRedisSessionNew_RedisTTL_Classic( _TestRedisSessionNew__MIXIN_A, _TestRedisSessionNew_CORE, unittest.TestCase ): <NEW_LINE> <INDENT> PYTHON_EXPIRES = False <NEW_LINE> set_redis_ttl = True <NEW_LINE> set_redis_ttl_readheavy = False <NEW_LINE> timeout = 1 <NEW_LINE> timeout_trigger = None <NEW_LINE> def test_refresh(self): <NEW_LINE> <INDENT> session = self._session_new() <NEW_LINE> self.assertEqual(len(session.redis._history), 1) <NEW_LINE> self.assertEqual(session.redis._history[0][0], "get") <NEW_LINE> session["FOO"] = "1" <NEW_LINE> session._deferred_callback(None) <NEW_LINE> self.assertEqual(len(session.redis._history), 2) <NEW_LINE> self.assertEqual(session.redis._history[1][0], "setex") <NEW_LINE> self.assertEqual(session.redis._history[1][2], self.timeout) <NEW_LINE> func_new_session = self._factory_new_session(session) <NEW_LINE> session2 = self._session_get(session, func_new_session) <NEW_LINE> self.assertEqual(session2.managed_dict["FOO"], "1") <NEW_LINE> session2._deferred_callback(None) <NEW_LINE> self.assertEqual(len(session.redis._history), 4) <NEW_LINE> self.assertEqual(session.redis._history[2][0], "get") <NEW_LINE> self.assertEqual(session.redis._history[3][0], "expire") <NEW_LINE> sleepy = self.timeout - 1 <NEW_LINE> print("will sleep for:", sleepy) <NEW_LINE> time.sleep(sleepy) <NEW_LINE> session3 = self._session_get(session, func_new_session) <NEW_LINE> self.assertEqual(session3.managed_dict["FOO"], "1") <NEW_LINE> session3._deferred_callback( None ) <NEW_LINE> self.assertEqual(len(session.redis._history), 6) <NEW_LINE> self.assertEqual(session.redis._history[4][0], "get") <NEW_LINE> self.assertEqual(session.redis._history[5][0], "expire")
these are 1.4x+ tests
6259904a21a7993f00c6734e
class __FRONTEND_VIEW__(pstruct.type): <NEW_LINE> <INDENT> def __init__(self, **attrs): <NEW_LINE> <INDENT> super(_HEAP_ENTRY.__FRONTEND_VIEW__, self).__init__(**attrs) <NEW_LINE> f = self._fields_ = [] <NEW_LINE> if getattr(self, 'WIN64', False): <NEW_LINE> <INDENT> f.extend([ (pint.uint64_t, 'Unencoded'), (pint.uint64_t, 'Encoded'), ]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> f.extend([ (pint.uint32_t, 'Encoded'), (pint.uint32_t, 'Unencoded'), ]) <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> def EncodedValue(self): <NEW_LINE> <INDENT> res = self['Encoded'].int() <NEW_LINE> return res & 0xffffffffff <NEW_LINE> <DEDENT> def EncodedUntouchedValue(self): <NEW_LINE> <INDENT> res = self['Encoded'].int() <NEW_LINE> return res & ~0xffffffffff
This type is used strictly for encoding/decoding and is used when casting the backing type.
6259904a07d97122c4218088
@attr.s(frozen=True, slots=True, hash=True) <NEW_LINE> class SerdeOptions: <NEW_LINE> <INDENT> omit_null_values = attr.ib(validator=instance_of(bool), default=True) <NEW_LINE> convert_datetimes = attr.ib(validator=instance_of(bool), default=True) <NEW_LINE> datetime_format = attr.ib( validator=instance_of(str), default=DEFAULT_DATETIME_FORMAT) <NEW_LINE> union = attr.ib(validator=optional(instance_of(UnionKind)), default=None)
Settings for serialisation and deserialisation
6259904ab57a9660fecd2e62
class AccerciserPreferencesDialog(gtk.Dialog): <NEW_LINE> <INDENT> def __init__(self, plugins_view=None, hotkeys_view=None): <NEW_LINE> <INDENT> gtk.Dialog.__init__(self, _('accerciser Preferences'), buttons=(gtk.STOCK_CLOSE, gtk.ResponseType.CLOSE)) <NEW_LINE> self.connect('response', self._onResponse) <NEW_LINE> self.set_default_size(500, 250) <NEW_LINE> notebook = gtk.Notebook() <NEW_LINE> vbox = self.get_children()[0] <NEW_LINE> vbox.add(notebook) <NEW_LINE> for view, section in [(plugins_view, _('Plugins')), (hotkeys_view, _('Global Hotkeys'))]: <NEW_LINE> <INDENT> if view is not None: <NEW_LINE> <INDENT> sw = gtk.ScrolledWindow() <NEW_LINE> sw.set_shadow_type(gtk.ShadowType.IN) <NEW_LINE> sw.set_policy(gtk.PolicyType.AUTOMATIC, gtk.PolicyType.AUTOMATIC) <NEW_LINE> sw.set_size_request(500, 150) <NEW_LINE> sw.add(view) <NEW_LINE> notebook.append_page(sw, gtk.Label(section)) <NEW_LINE> <DEDENT> <DEDENT> notebook.append_page(_HighlighterView(), gtk.Label(_('Highlighting'))) <NEW_LINE> <DEDENT> def _onResponse(self, dialog, response_id): <NEW_LINE> <INDENT> dialog.destroy()
Class that creates a preferences dialog.
6259904a26068e7796d4dd29
class CutIntoDeterministicTiles(object): <NEW_LINE> <INDENT> def __init__(self, n=3, piece_crop_percentage=0.88, image_size=(99, 99)): <NEW_LINE> <INDENT> assert isinstance(n, int), "The input parameter 'number_of_tiles' for the constructor of " "CutIntoDeterministicTiles " "needs to be of type int." "Got %s." % type(n).__name__ <NEW_LINE> self.n = n <NEW_LINE> assert isinstance(piece_crop_percentage, float), "The input parameter 'piece_crop_percentage' for the constructor of " "CutIntoDeterministicTiles needs to be of type float." "Got %s." % type(piece_crop_percentage).__name__ <NEW_LINE> assert 1 >= piece_crop_percentage > 0, 'The input parameter \'piece_crop_percentage\' needs to be bigger ' 'than zero and smaller or equal to one.' 'Got %s.' % piece_crop_percentage <NEW_LINE> self.piece_crop_percentage = piece_crop_percentage <NEW_LINE> self.image_size = image_size[0] <NEW_LINE> self.piece_size = int(self.image_size / self.n) <NEW_LINE> steps = range(0, self.image_size, self.piece_size) <NEW_LINE> self.boxes = [(i, j, i + self.piece_size, j + self.piece_size) for i, j in product(steps, steps)] <NEW_LINE> self.cropped_piece_size = round(self.piece_crop_percentage * self.piece_size) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "CutIntoDeterministicTiles(n={},piece_crop_percentage={})".format(self.n, self.piece_crop_percentage) <NEW_LINE> <DEDENT> def __call__(self, image): <NEW_LINE> <INDENT> _, height, width = image.shape <NEW_LINE> assert height == width, "CutIntoDeterministicTiles needs a quadratic image. " "Input size was (%d,%d)" % (width, height) <NEW_LINE> assert height % self.n == 0, "CutIntoDeterministicTiles got an image that is" " not divisible into %d parts" % self.n <NEW_LINE> if self.piece_crop_percentage < 1: <NEW_LINE> <INDENT> return [self.random_crop(image[:, x_min:x_max, y_min:y_max]) for (x_min, y_min, x_max, y_max) in self.boxes] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [image[:, x_min:x_max, y_min:y_max] for (x_min, y_min, x_max, y_max) in self.boxes] <NEW_LINE> <DEDENT> <DEDENT> def random_crop(self, tensor): <NEW_LINE> <INDENT> x_shift = (self.piece_size - self.cropped_piece_size) // 2 <NEW_LINE> y_shift = (self.piece_size - self.cropped_piece_size) // 2 <NEW_LINE> return tensor[:, x_shift:self.cropped_piece_size + x_shift, y_shift:self.cropped_piece_size + y_shift]
Cut an image into tiles and crop each tile at a random location.
6259904a71ff763f4b5e8b8b
class Fifo: <NEW_LINE> <INDENT> def __init__(self, path, mode): <NEW_LINE> <INDENT> self.trick = None <NEW_LINE> if not os.path.exists(path): <NEW_LINE> <INDENT> os.mkfifo(path) <NEW_LINE> <DEDENT> if mode == 'w': <NEW_LINE> <INDENT> self.trick = OpenTrick(path) <NEW_LINE> self.trick.start() <NEW_LINE> <DEDENT> self.fd = open(path, mode, encoding='utf-8') <NEW_LINE> <DEDENT> def write(self, data): <NEW_LINE> <INDENT> self.fd.write(data) <NEW_LINE> self.fd.flush() <NEW_LINE> <DEDENT> def readline(self): <NEW_LINE> <INDENT> return self.fd.readline() <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.fd.close() <NEW_LINE> if self.trick: <NEW_LINE> <INDENT> self.trick.fd.close() <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> log.error( 'Unable to close descriptors for the fifo', exc_info=True)
Just a simple file handler, writing and reading in a fifo. Mode is either 'r' or 'w', just like the mode for the open() function.
6259904a8a43f66fc4bf357b
class RecordSizeMismatchError(RecordValidationError): <NEW_LINE> <INDENT> def __init__(self, path, record_size, actual_size): <NEW_LINE> <INDENT> self.path = path <NEW_LINE> self.record_size = record_size <NEW_LINE> self.actual_size = actual_size <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return ( f"Size of file {self.path!r} listed as {self.record_size} in" f" RECORD, actually {self.actual_size}" )
Raised when the size of a file as declared in a wheel's :file:`RECORD` does not match the file's actual size
6259904a23e79379d538d8e4
class ClockDrift(FloatWithUncertaintiesFixedUnit): <NEW_LINE> <INDENT> _minimum = 0 <NEW_LINE> unit = "SECONDS/SAMPLE"
ClockDrift object :type value: float :param value: ClockDrift value :type lower_uncertainty: float :param lower_uncertainty: Lower uncertainty (aka minusError) :type upper_uncertainty: float :param upper_uncertainty: Upper uncertainty (aka plusError) :type measurement_method: str :param measurement_method: Method used in the measurement.
6259904a0a366e3fb87dddcb
class Popen(Process): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.__subproc = subprocess.Popen(*args, **kwargs) <NEW_LINE> self._pid = self.__subproc.pid <NEW_LINE> self._gone = False <NEW_LINE> self._ppid = None <NEW_LINE> self._platform_impl = _psplatform.Process(self._pid) <NEW_LINE> self._last_sys_cpu_times = None <NEW_LINE> self._last_proc_cpu_times = None <NEW_LINE> try: <NEW_LINE> <INDENT> self.create_time <NEW_LINE> <DEDENT> except AccessDenied: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> except NoSuchProcess: <NEW_LINE> <INDENT> raise NoSuchProcess(self._pid, None, "no process found with pid %s" % self._pid) <NEW_LINE> <DEDENT> <DEDENT> def __dir__(self): <NEW_LINE> <INDENT> return list(set(dir(Popen) + dir(subprocess.Popen))) <NEW_LINE> <DEDENT> def __getattribute__(self, name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return object.__getattribute__(self, name) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return object.__getattribute__(self.__subproc, name) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> raise AttributeError("%s instance has no attribute '%s'" % (self.__class__.__name__, name))
A more convenient interface to stdlib subprocess module. It starts a sub process and deals with it exactly as when using subprocess.Popen class but in addition also provides all the property and methods of psutil.Process class in a single interface: >>> import psutil >>> from subprocess import PIPE >>> p = psutil.Popen(["/usr/bin/python", "-c", "print 'hi'"], stdout=PIPE) >>> p.name 'python' >>> p.uids user(real=1000, effective=1000, saved=1000) >>> p.username 'giampaolo' >>> p.communicate() ('hi ', None) >>> p.terminate() >>> p.wait(timeout=2) 0 >>> For method names common to both classes such as kill(), terminate() and wait(), psutil.Process implementation takes precedence. For a complete documentation refers to: http://docs.python.org/library/subprocess.html
6259904abaa26c4b54d50690
class RangePollChoiceVoteForm(happyforms.Form): <NEW_LINE> <INDENT> def __init__(self, choices, *args, **kwargs): <NEW_LINE> <INDENT> super(RangePollChoiceVoteForm, self).__init__(*args, **kwargs) <NEW_LINE> nominees = tuple((i, '%d' % i) for i in range(0, choices.count()+1)) <NEW_LINE> for choice in choices: <NEW_LINE> <INDENT> self.fields['range_poll__%s' % str(choice.id)] = ( forms.ChoiceField(widget=forms.Select(), choices=nominees, label=choice.nominee.get_full_name())) <NEW_LINE> <DEDENT> <DEDENT> def clean(self, *args, **kwargs): <NEW_LINE> <INDENT> if all(int(vote) == 0 for vote in self.cleaned_data.values()): <NEW_LINE> <INDENT> msg = 'You must vote at least one nominee' <NEW_LINE> if self.fields: <NEW_LINE> <INDENT> last_form_entry = self.fields.keys()[-1] <NEW_LINE> self.errors[last_form_entry] = self.error_class([msg]) <NEW_LINE> <DEDENT> <DEDENT> return self.cleaned_data <NEW_LINE> <DEDENT> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> for nominee_id, votes in self.cleaned_data.items(): <NEW_LINE> <INDENT> nominee_id = nominee_id.split('__')[1] <NEW_LINE> (RangePollChoice.objects .filter(pk=nominee_id).update(votes=F('votes')+int(votes)))
Range voting vote form.
6259904ad7e4931a7ef3d45c
class NoopRunner(ActionRunner): <NEW_LINE> <INDENT> KEYS_TO_TRANSFORM = ['stdout', 'stderr'] <NEW_LINE> def __init__(self, runner_id): <NEW_LINE> <INDENT> super(NoopRunner, self).__init__(runner_id=runner_id) <NEW_LINE> <DEDENT> def pre_run(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def run(self, action_parameters): <NEW_LINE> <INDENT> LOG.info('Executing action via NoopRunner: %s', self.runner_id) <NEW_LINE> LOG.info('[Action info] name: %s, Id: %s', self.action_name, str(self.execution_id)) <NEW_LINE> result = { 'failed': False, 'succeeded': True, 'return_code': 0, } <NEW_LINE> status = LIVEACTION_STATUS_SUCCEEDED <NEW_LINE> return (status, jsonify.json_loads(result, NoopRunner.KEYS_TO_TRANSFORM), None)
Runner which does absolutely nothing. No-op action.
6259904a7d847024c075d7b8
class cFilePicker(QtCore.QObject): <NEW_LINE> <INDENT> sigValidFilename = pyqtSignal('bool') <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super(cFilePicker, self).__init__() <NEW_LINE> self.isFilenameInserted = False <NEW_LINE> self.lblCaption = QtGui.QLabel() <NEW_LINE> self.cbxFilename = QtGui.QComboBox() <NEW_LINE> self.cbxFilename.setEditable(True) <NEW_LINE> self.cbxFilename.editTextChanged.connect(self.verifyFilename) <NEW_LINE> self.btnFileDlg = QtGui.QPushButton("...") <NEW_LINE> self.btnFileDlg.setSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Preferred) <NEW_LINE> self.fileDialog = QtGui.QFileDialog() <NEW_LINE> self.btnFileDlg.clicked.connect(self.showFileDialog) <NEW_LINE> <DEDENT> def getWidgets(self): <NEW_LINE> <INDENT> return {'label': self.lblCaption, 'combobox': self.cbxFilename, 'button': self.btnFileDlg, 'dialog': self.fileDialog} <NEW_LINE> <DEDENT> def setHistory(self, fileNames): <NEW_LINE> <INDENT> self.cbxFilename.addItems(fileNames) <NEW_LINE> <DEDENT> def showFileDialog(self): <NEW_LINE> <INDENT> if self.fileDialog.exec_() == QtGui.QDialog.Accepted: <NEW_LINE> <INDENT> if self.isFilenameInserted: <NEW_LINE> <INDENT> self.setFileName(self.fileDialog.selectedFiles()[0]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.setFileName(self.fileDialog.selectedFiles()[0]) <NEW_LINE> self.isFilenameInserted = True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def setFileName(self, name): <NEW_LINE> <INDENT> if self.cbxFilename.count() == 0: <NEW_LINE> <INDENT> self.cbxFilename.addItem(name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.cbxFilename.setItemText(0, name) <NEW_LINE> <DEDENT> self.cbxFilename.setCurrentIndex(0) <NEW_LINE> fileInfo = QtCore.QFileInfo(name) <NEW_LINE> self.fileDialog.setDirectory(fileInfo.dir()) <NEW_LINE> self.fileDialog.selectFile(name) <NEW_LINE> <DEDENT> def verifyFilename(self, filename): <NEW_LINE> <INDENT> self.sigValidFilename.emit(QtCore.QFile.exists(filename)) <NEW_LINE> <DEDENT> def isValidFilename(self): <NEW_LINE> <INDENT> return QtCore.QFile.exists(self.cbxFilename.currentText()) <NEW_LINE> <DEDENT> def getFilename(self): <NEW_LINE> <INDENT> return unicode(self.cbxFilename.currentText())
A file picker widget with a label, a combobox and a button. Pressing the button opens a file dialog. Layouting the label, line edit and button is not done by this class.
6259904aec188e330fdf9c83
class MockObject(MockAnything, object): <NEW_LINE> <INDENT> def __init__(self, class_to_mock): <NEW_LINE> <INDENT> MockAnything.__dict__['__init__'](self) <NEW_LINE> self._known_methods = set() <NEW_LINE> self._known_vars = set() <NEW_LINE> self._class_to_mock = class_to_mock <NEW_LINE> for method in dir(class_to_mock): <NEW_LINE> <INDENT> if callable(getattr(class_to_mock, method)): <NEW_LINE> <INDENT> self._known_methods.add(method) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._known_vars.add(method) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __getattr__(self, name): <NEW_LINE> <INDENT> if name in self._known_vars: <NEW_LINE> <INDENT> return getattr(self._class_to_mock, name) <NEW_LINE> <DEDENT> if name in self._known_methods: <NEW_LINE> <INDENT> return self._CreateMockMethod(name) <NEW_LINE> <DEDENT> raise UnknownMethodCallError(name) <NEW_LINE> <DEDENT> def __eq__(self, rhs): <NEW_LINE> <INDENT> return (isinstance(rhs, MockObject) and self._class_to_mock == rhs._class_to_mock and self._replay_mode == rhs._replay_mode and self._expected_calls_queue == rhs._expected_calls_queue) <NEW_LINE> <DEDENT> def __setitem__(self, key, value): <NEW_LINE> <INDENT> setitem = self._class_to_mock.__dict__.get('__setitem__', None) <NEW_LINE> if setitem is None: <NEW_LINE> <INDENT> raise TypeError('object does not support item assignment') <NEW_LINE> <DEDENT> if self._replay_mode: <NEW_LINE> <INDENT> return MockMethod('__setitem__', self._expected_calls_queue, self._replay_mode)(key, value) <NEW_LINE> <DEDENT> return self._CreateMockMethod('__setitem__')(key, value) <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> getitem = self._class_to_mock.__dict__.get('__getitem__', None) <NEW_LINE> if getitem is None: <NEW_LINE> <INDENT> raise TypeError('unsubscriptable object') <NEW_LINE> <DEDENT> if self._replay_mode: <NEW_LINE> <INDENT> return MockMethod('__getitem__', self._expected_calls_queue, self._replay_mode)(key) <NEW_LINE> <DEDENT> return self._CreateMockMethod('__getitem__')(key) <NEW_LINE> <DEDENT> def __call__(self, *params, **named_params): <NEW_LINE> <INDENT> callable = self._class_to_mock.__dict__.get('__call__', None) <NEW_LINE> if callable is None: <NEW_LINE> <INDENT> raise TypeError('Not callable') <NEW_LINE> <DEDENT> mock_method = self._CreateMockMethod('__call__') <NEW_LINE> return mock_method(*params, **named_params) <NEW_LINE> <DEDENT> @property <NEW_LINE> def __class__(self): <NEW_LINE> <INDENT> return self._class_to_mock
A mock object that simulates the public/protected interface of a class.
6259904a96565a6dacd2d97c
class RegisterView(View): <NEW_LINE> <INDENT> def get(self, request): <NEW_LINE> <INDENT> return render(request, 'register.html') <NEW_LINE> <DEDENT> def post(self, request): <NEW_LINE> <INDENT> form = RegisterForm(request.POST) <NEW_LINE> if form.is_valid(): <NEW_LINE> <INDENT> email = form.cleaned_data.get('email') <NEW_LINE> password = form.cleaned_data.get('password') <NEW_LINE> username = form.cleaned_data.get('username') <NEW_LINE> User.objects.create(email=email, password=password, username=username) <NEW_LINE> return redirect(reverse('login')) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print(form.errors) <NEW_LINE> return redirect(reverse('register'))
注册类视图
6259904ab5575c28eb7136bc
class OneToOnePage(Page): <NEW_LINE> <INDENT> body = RichTextBlock(blank=True) <NEW_LINE> page_ptr = models.OneToOneField(Page, parent_link=True, related_name='+')
A Page containing a O2O relation.
6259904aac7a0e7691f738c2
class Game: <NEW_LINE> <INDENT> def __init__(self, size, method_num): <NEW_LINE> <INDENT> self.done = False <NEW_LINE> self.paused = False <NEW_LINE> self.gol = GoL(size) <NEW_LINE> self.time_list = [] <NEW_LINE> self.method_num = method_num <NEW_LINE> self.methods = {1: self.gol.conv_method, 2: self.gol.loop_method, 3: self.gol.multi_loop_method} <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> self.event_handler() <NEW_LINE> self.gol.grid.display() <NEW_LINE> if not self.paused: <NEW_LINE> <INDENT> t0 = time.time() <NEW_LINE> self.gol.evolve(self.methods[self.method_num]) <NEW_LINE> t1 = time.time() <NEW_LINE> self.time_list.append(t1 - t0) <NEW_LINE> <DEDENT> <DEDENT> def time_analysis(self): <NEW_LINE> <INDENT> print("Mean time per update: {}".format(np.mean(self.time_list))) <NEW_LINE> print("Standard deviation of time to update: {}".format(np.std(self.time_list))) <NEW_LINE> <DEDENT> def event_handler(self): <NEW_LINE> <INDENT> for event in pg.event.get(): <NEW_LINE> <INDENT> if event.type == pg.QUIT: <NEW_LINE> <INDENT> self.done = True <NEW_LINE> <DEDENT> elif event.type == pg.MOUSEBUTTONDOWN: <NEW_LINE> <INDENT> if event.button == 3: <NEW_LINE> <INDENT> self.paused = not self.paused <NEW_LINE> <DEDENT> elif event.button == 1: <NEW_LINE> <INDENT> mouse = pg.mouse.get_pos() <NEW_LINE> self.gol.grid.flip_cell(mouse)
Handles pygame events, pausing etc; along with timing the code
6259904ad6c5a102081e3503
class VCFSeq(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.name = '' <NEW_LINE> self.header = [] <NEW_LINE> self.speciesL = [] <NEW_LINE> self.nSpecies = 0 <NEW_LINE> self.baseL = [] <NEW_LINE> self.nBases = 0 <NEW_LINE> <DEDENT> def get_header_line_string(self, indiv): <NEW_LINE> <INDENT> string = '' <NEW_LINE> for s in hdList: <NEW_LINE> <INDENT> string += s + '\t' <NEW_LINE> <DEDENT> for i in indiv: <NEW_LINE> <INDENT> string += i + '\t' <NEW_LINE> <DEDENT> return string[:-1] <NEW_LINE> <DEDENT> def print_header_line(self, indiv): <NEW_LINE> <INDENT> print(self.get_header_line_string(indiv)) <NEW_LINE> <DEDENT> def print_info(self, maxB=50, printHeader=False): <NEW_LINE> <INDENT> if printHeader is True: <NEW_LINE> <INDENT> print(self.header) <NEW_LINE> <DEDENT> self.print_header_line(self.speciesL) <NEW_LINE> if self.nBases < maxB: <NEW_LINE> <INDENT> maxB = self.nBases <NEW_LINE> <DEDENT> for i in range(0, maxB): <NEW_LINE> <INDENT> self.baseL[i].print_info() <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> def append_nuc_base(self, base): <NEW_LINE> <INDENT> self.baseL.append(base) <NEW_LINE> self.nBases += 1 <NEW_LINE> return <NEW_LINE> <DEDENT> def has_base(self, chrom, pos): <NEW_LINE> <INDENT> for i in range(0, self.nBases): <NEW_LINE> <INDENT> if pos == self.baseL[i].pos and chrom == self.baseL[i].chrom: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> def get_nuc_base(self, chrom, pos): <NEW_LINE> <INDENT> for i in range(0, self.nBases): <NEW_LINE> <INDENT> if pos == self.baseL[i].pos and chrom == self.baseL[i].chrom: <NEW_LINE> <INDENT> return self.baseL[i] <NEW_LINE> <DEDENT> <DEDENT> raise sb.SequenceDataError('Base at position ' + str(pos) + ' on chromosome ' + str(chrom) + ' not found.')
Store data retrieved from a VCF file. Initialized with :func:`open_seq`. :ivar str name: Sequence name. :ivar str header: Sequence header. :ivar [str] speciesL: List with species / individuals. :ivar int nSpecies: Number of species / individuals. :ivar [NucBase] baseL: List with stored :class:`NucBase` objects. :ivar int nBases: Number of :class:`NucBase` objects stored.
6259904a21a7993f00c67350
@register(OSType.BOOLEAN) <NEW_LINE> class Bool(BooleanElement): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def read(cls, fp): <NEW_LINE> <INDENT> return cls(read_fmt('?', fp)[0]) <NEW_LINE> <DEDENT> def write(self, fp): <NEW_LINE> <INDENT> return write_fmt(fp, '?', self.value)
Bool structure. .. py:attribute:: value
6259904a15baa72349463379
class TwoLayerNet(object): <NEW_LINE> <INDENT> def __init__(self, input_dim=3*32*32, hidden_dim=100, num_classes=10, weight_scale=1e-3, reg=0.0): <NEW_LINE> <INDENT> self.params = {} <NEW_LINE> self.reg = reg <NEW_LINE> self.params['W1'] = np.random.normal(scale=weight_scale, size=(input_dim, hidden_dim)) <NEW_LINE> self.params['W2'] = np.random.normal(scale=weight_scale, size=(hidden_dim, num_classes)) <NEW_LINE> self.params['b1'] = np.zeros(hidden_dim) <NEW_LINE> self.params['b2'] = np.zeros(num_classes) <NEW_LINE> <DEDENT> def loss(self, X, y=None): <NEW_LINE> <INDENT> scores = None <NEW_LINE> W1, W2 = self.params['W1'], self.params['W2'] <NEW_LINE> b1, b2 = self.params['b1'], self.params['b2'] <NEW_LINE> out_af1, cache_af1 = affine_forward(X, W1, b1) <NEW_LINE> out_relu, cache_relu = relu_forward(out_af1) <NEW_LINE> out_af2, cache_af2 = affine_forward(out_relu, W2, b2) <NEW_LINE> scores = out_af2 <NEW_LINE> if y is None: <NEW_LINE> <INDENT> return scores <NEW_LINE> <DEDENT> loss, grads = 0, {} <NEW_LINE> loss, dscores = softmax_loss(scores, y) <NEW_LINE> loss += np.sum(0.5 * self.reg * W1 * W1) + np.sum(0.5 * self.reg * W2 * W2) <NEW_LINE> daf2, grads['W2'], grads['b2'] = affine_backward(dscores, cache_af2) <NEW_LINE> drelu = relu_backward(daf2, cache_relu) <NEW_LINE> dx, grads['W1'], grads['b1'] = affine_backward(drelu, cache_af1) <NEW_LINE> grads['W1'] += self.reg * W1 <NEW_LINE> grads['W2'] += self.reg * W2 <NEW_LINE> return loss, grads
A two-layer fully-connected neural network with ReLU nonlinearity and softmax loss that uses a modular layer design. We assume an input dimension of D, a hidden dimension of H, and perform classification over C classes. The architecure should be affine - relu - affine - softmax. Note that this class does not implement gradient descent; instead, it will interact with a separate Solver object that is responsible for running optimization. The learnable parameters of the model are stored in the dictionary self.params that maps parameter names to numpy arrays.
6259904aa79ad1619776b467
class TestSeriesValidate(object): <NEW_LINE> <INDENT> s = Series([1, 2, 3, 4, 5]) <NEW_LINE> def test_validate_bool_args(self): <NEW_LINE> <INDENT> invalid_values = [1, "True", [1, 2, 3], 5.0] <NEW_LINE> for value in invalid_values: <NEW_LINE> <INDENT> with pytest.raises(ValueError): <NEW_LINE> <INDENT> self.s.reset_index(inplace=value) <NEW_LINE> <DEDENT> with pytest.raises(ValueError): <NEW_LINE> <INDENT> self.s._set_name(name='hello', inplace=value) <NEW_LINE> <DEDENT> with pytest.raises(ValueError): <NEW_LINE> <INDENT> self.s.sort_values(inplace=value) <NEW_LINE> <DEDENT> with pytest.raises(ValueError): <NEW_LINE> <INDENT> self.s.sort_index(inplace=value) <NEW_LINE> <DEDENT> with pytest.raises(ValueError): <NEW_LINE> <INDENT> self.s.sort_index(inplace=value) <NEW_LINE> <DEDENT> with pytest.raises(ValueError): <NEW_LINE> <INDENT> self.s.rename(inplace=value) <NEW_LINE> <DEDENT> with pytest.raises(ValueError): <NEW_LINE> <INDENT> self.s.dropna(inplace=value)
Tests for error handling related to data types of method arguments.
6259904a498bea3a75a58f07