code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class BookList(APIView): <NEW_LINE> <INDENT> def get(self, request, format=None): <NEW_LINE> <INDENT> books = Book.objects.all() <NEW_LINE> serializer = BookSerializer(books, many=True) <NEW_LINE> return Response(serializer.data) <NEW_LINE> <DEDENT> def post(self, request, format=None): <NEW_LINE> <INDENT> serializer = BookSerializer(data=request.data) <NEW_LINE> if serializer.is_valid(): <NEW_LINE> <INDENT> serializer.save() <NEW_LINE> return Response(serializer.data, status=status.HTTP_201_CREATED) <NEW_LINE> <DEDENT> return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
List all books or creates a new one
62598fb6a17c0f6771d5c332
class TokenAuthSupportQueryString(TokenAuthentication): <NEW_LINE> <INDENT> def authenticate(self, request): <NEW_LINE> <INDENT> if 'token' in request.query_params and 'HTTP_AUTHORIZATION' not in request.META: <NEW_LINE> <INDENT> return self.authenticate_credentials(request.query_params.get('token')) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return super(TokenAuthSupportQueryString, self).authenticate(request)
Extend the TokenAuthentication class to support querystring authentication in the form of "http://www.example.com/?token=<token_key>" needed for google spreadsheets =importcsv()
62598fb6cc40096d6161a257
class BiddingStrategyType(enum.IntEnum): <NEW_LINE> <INDENT> UNSPECIFIED = 0 <NEW_LINE> UNKNOWN = 1 <NEW_LINE> COMMISSION = 16 <NEW_LINE> ENHANCED_CPC = 2 <NEW_LINE> MANUAL_CPC = 3 <NEW_LINE> MANUAL_CPM = 4 <NEW_LINE> MANUAL_CPV = 13 <NEW_LINE> MAXIMIZE_CONVERSIONS = 10 <NEW_LINE> MAXIMIZE_CONVERSION_VALUE = 11 <NEW_LINE> PAGE_ONE_PROMOTED = 5 <NEW_LINE> PERCENT_CPC = 12 <NEW_LINE> TARGET_CPA = 6 <NEW_LINE> TARGET_CPM = 14 <NEW_LINE> TARGET_IMPRESSION_SHARE = 15 <NEW_LINE> TARGET_OUTRANK_SHARE = 7 <NEW_LINE> TARGET_ROAS = 8 <NEW_LINE> TARGET_SPEND = 9
Enum describing possible bidding strategy types. Attributes: UNSPECIFIED (int): Not specified. UNKNOWN (int): Used for return value only. Represents value unknown in this version. COMMISSION (int): Commission is an automatic bidding strategy in which the advertiser pays a certain portion of the conversion value. ENHANCED_CPC (int): Enhanced CPC is a bidding strategy that raises bids for clicks that seem more likely to lead to a conversion and lowers them for clicks where they seem less likely. MANUAL_CPC (int): Manual click based bidding where user pays per click. MANUAL_CPM (int): Manual impression based bidding where user pays per thousand impressions. MANUAL_CPV (int): A bidding strategy that pays a configurable amount per video view. MAXIMIZE_CONVERSIONS (int): A bidding strategy that automatically maximizes number of conversions given a daily budget. MAXIMIZE_CONVERSION_VALUE (int): An automated bidding strategy that automatically sets bids to maximize revenue while spending your budget. PAGE_ONE_PROMOTED (int): Page-One Promoted bidding scheme, which sets max cpc bids to target impressions on page one or page one promoted slots on google.com. PERCENT_CPC (int): Percent Cpc is bidding strategy where bids are a fraction of the advertised price for some good or service. TARGET_CPA (int): Target CPA is an automated bid strategy that sets bids to help get as many conversions as possible at the target cost-per-acquisition (CPA) you set. TARGET_CPM (int): Target CPM is an automated bid strategy that sets bids to help get as many impressions as possible at the target cost per one thousand impressions (CPM) you set. TARGET_IMPRESSION_SHARE (int): An automated bidding strategy that sets bids so that a certain percentage of search ads are shown at the top of the first page (or other targeted location). TARGET_OUTRANK_SHARE (int): Target Outrank Share is an automated bidding strategy that sets bids based on the target fraction of auctions where the advertiser should outrank a specific competitor. TARGET_ROAS (int): Target ROAS is an automated bidding strategy that helps you maximize revenue while averaging a specific target Return On Average Spend (ROAS). TARGET_SPEND (int): Target Spend is an automated bid strategy that sets your bids to help get as many clicks as possible within your budget.
62598fb67047854f4633f4d5
class Node(object): <NEW_LINE> <INDENT> def __init__(self, microdescriptor, routerstatus): <NEW_LINE> <INDENT> assert(microdescriptor and routerstatus) <NEW_LINE> logger.debug("Initializing node with fpr %s", routerstatus.fingerprint) <NEW_LINE> self.microdescriptor = microdescriptor <NEW_LINE> self.routerstatus = routerstatus <NEW_LINE> <DEDENT> def get_hex_fingerprint(self): <NEW_LINE> <INDENT> return self.routerstatus.fingerprint <NEW_LINE> <DEDENT> def get_hsdir_index(self, srv, period_num): <NEW_LINE> <INDENT> from onionbalance.hs_v3.onionbalance import my_onionbalance <NEW_LINE> if 'HSDir' not in self.routerstatus.protocols or 2 not in self.routerstatus.protocols['HSDir'] or 'HSDir' not in self.routerstatus.flags: <NEW_LINE> <INDENT> raise NoHSDir <NEW_LINE> <DEDENT> if 'ed25519' not in self.microdescriptor.identifiers: <NEW_LINE> <INDENT> raise NoEd25519Identity <NEW_LINE> <DEDENT> ed25519_node_identity_b64 = self.microdescriptor.identifiers['ed25519'] <NEW_LINE> missing_padding = len(ed25519_node_identity_b64) % 4 <NEW_LINE> ed25519_node_identity_b64 += '=' * missing_padding <NEW_LINE> ed25519_node_identity = base64.b64decode(ed25519_node_identity_b64) <NEW_LINE> period_num_int_8 = period_num.to_bytes(8, 'big') <NEW_LINE> period_length = my_onionbalance.consensus.get_time_period_length() <NEW_LINE> period_length_int_8 = period_length.to_bytes(8, 'big') <NEW_LINE> hash_body = b"%s%s%s%s%s" % (b"node-idx", ed25519_node_identity, srv, period_num_int_8, period_length_int_8) <NEW_LINE> hsdir_index = hashlib.sha3_256(hash_body).digest() <NEW_LINE> return hsdir_index
Represents a Tor node. A Node instance gets created for each node of a consensus. When we fetch a new consensus, we create new Node instances for the routers found inside. The 'microdescriptor' and 'routerstatus' fields of this object are immutable: They are set once when we receive the consensus based on the state of the network at that point, and they stay like that until we get a new consensus.
62598fb663d6d428bbee28aa
class ExternalAPIException(RESTException): <NEW_LINE> <INDENT> code = 503 <NEW_LINE> description = 'External API replied with an error.' <NEW_LINE> def __init__(self, response=None, **kwargs): <NEW_LINE> <INDENT> super(ExternalAPIException, self).__init__(**kwargs) <NEW_LINE> if response is not None: <NEW_LINE> <INDENT> self.description = 'External API replied with an error:\n{0}\n{1}' .format(response.status_code, response.content)
External API replied with an error.
62598fb67b25080760ed75af
class MultilayerPerceptronClassificationModel(JavaProbabilisticClassificationModel, JavaMLWritable, JavaMLReadable): <NEW_LINE> <INDENT> @property <NEW_LINE> @since("1.6.0") <NEW_LINE> def layers(self): <NEW_LINE> <INDENT> return self._call_java("javaLayers") <NEW_LINE> <DEDENT> @property <NEW_LINE> @since("2.0.0") <NEW_LINE> def weights(self): <NEW_LINE> <INDENT> return self._call_java("weights")
Model fitted by MultilayerPerceptronClassifier. .. versionadded:: 1.6.0
62598fb67d43ff2487427481
class HTTPTokenAuth(requests.auth.AuthBase): <NEW_LINE> <INDENT> def __init__(self, token): <NEW_LINE> <INDENT> self.token = token <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.token == other.token <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return self.token != other.token <NEW_LINE> <DEDENT> def __call__(self, req): <NEW_LINE> <INDENT> req.headers["Authorization"] = "Token {}".format(self.token) <NEW_LINE> return req
Attaches HTTP Token Authentication to the given Request object.
62598fb6be7bc26dc9251eda
class Bytes(bytes): <NEW_LINE> <INDENT> def __new__(cls, data): <NEW_LINE> <INDENT> if data == None: <NEW_LINE> <INDENT> return str.__new__(cls, "-") <NEW_LINE> <DEDENT> return str.__new__(cls, data.encode("hex"))
String class to allow us to encode binary data
62598fb601c39578d7f12e76
class RegistrationForm(FlaskForm): <NEW_LINE> <INDENT> username = StringField('username_label', validators=[InputRequired(message="Username is required !!"), Length(min=4, max=25, message="Username must be between" "4 to 25 characters.")]) <NEW_LINE> password = PasswordField('password_label', validators=[InputRequired(message="Password is required !!"), Length(min=4, max=25, message="Password must be between" "4 to 25 characters.")]) <NEW_LINE> confirm_pswd = PasswordField('confirm_pswd_label', validators=[InputRequired(message="Password is required !!"), EqualTo('password', message="Password must match !")]) <NEW_LINE> submit_btn = SubmitField('Create') <NEW_LINE> def validate_username(self, username): <NEW_LINE> <INDENT> user_object = User.query.filter_by(username=username.data).first() <NEW_LINE> if user_object: <NEW_LINE> <INDENT> raise ValidationError("Username already exists. Please select another username.")
Registration Form
62598fb692d797404e388be1
class SimplePatient(object): <NEW_LINE> <INDENT> def __init__(self, viruses, maxPop): <NEW_LINE> <INDENT> self.viruses = viruses <NEW_LINE> self.maxPop = maxPop <NEW_LINE> <DEDENT> def getTotalPop(self): <NEW_LINE> <INDENT> return len(self.viruses) <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> survivedVirus = [] <NEW_LINE> for virus in self.viruses: <NEW_LINE> <INDENT> if not virus.doesClear(): <NEW_LINE> <INDENT> survivedVirus.append(virus) <NEW_LINE> <DEDENT> <DEDENT> self.viruses = survivedVirus <NEW_LINE> popDensity = float(len(self.viruses))/self.maxPop <NEW_LINE> children = [] <NEW_LINE> for virus in self.viruses: <NEW_LINE> <INDENT> children.append(virus) <NEW_LINE> try: <NEW_LINE> <INDENT> child = virus.reproduce(popDensity) <NEW_LINE> children.append(child) <NEW_LINE> <DEDENT> except NoChildException: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> self.viruses = children <NEW_LINE> return self.getTotalPop()
Representation of a simplified patient. The patient does not take any drugs and his/her virus populations have no drug resistance.
62598fb64527f215b58e9fd2
class OSMesaPlatform(Platform): <NEW_LINE> <INDENT> def __init__(self, viewport_width, viewport_height): <NEW_LINE> <INDENT> super(OSMesaPlatform, self).__init__(viewport_width, viewport_height) <NEW_LINE> self._context = None <NEW_LINE> self._buffer = None <NEW_LINE> <DEDENT> def init_context(self): <NEW_LINE> <INDENT> from OpenGL import arrays <NEW_LINE> from OpenGL.osmesa import ( OSMesaCreateContextAttribs, OSMESA_FORMAT, OSMESA_RGBA, OSMESA_PROFILE, OSMESA_CORE_PROFILE, OSMESA_CONTEXT_MAJOR_VERSION, OSMESA_CONTEXT_MINOR_VERSION, OSMESA_DEPTH_BITS ) <NEW_LINE> attrs = arrays.GLintArray.asArray([ OSMESA_FORMAT, OSMESA_RGBA, OSMESA_DEPTH_BITS, 24, OSMESA_PROFILE, OSMESA_CORE_PROFILE, OSMESA_CONTEXT_MAJOR_VERSION, 3, OSMESA_CONTEXT_MINOR_VERSION, 3, 0 ]) <NEW_LINE> self._context = OSMesaCreateContextAttribs(attrs, None) <NEW_LINE> self._buffer = arrays.GLubyteArray.zeros( (self.viewport_height, self.viewport_width, 4) ) <NEW_LINE> <DEDENT> def make_current(self): <NEW_LINE> <INDENT> from OpenGL import GL as gl <NEW_LINE> from OpenGL.osmesa import OSMesaMakeCurrent <NEW_LINE> assert(OSMesaMakeCurrent( self._context, self._buffer, gl.GL_UNSIGNED_BYTE, self.viewport_width, self.viewport_height )) <NEW_LINE> <DEDENT> def delete_context(self): <NEW_LINE> <INDENT> from OpenGL.osmesa import OSMesaDestroyContext <NEW_LINE> OSMesaDestroyContext(self._context) <NEW_LINE> self._context = None <NEW_LINE> self._buffer = None <NEW_LINE> <DEDENT> def supports_framebuffers(self): <NEW_LINE> <INDENT> return False
Renders into a software buffer using OSMesa. Requires special versions of OSMesa to be installed, plus PyOpenGL upgrade.
62598fb60fa83653e46f4fdd
class Meta: <NEW_LINE> <INDENT> model = models.Topic <NEW_LINE> fields = ( 'name', 'identifier', 'description', 'threads_last_day', 'threads', )
Meta options for topic serializer Defines which model to represent and which fields to display
62598fb63539df3088ecc3a9
class Game: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pygame.init() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def w_game_init(): <NEW_LINE> <INDENT> icone = pygame.image.load(cs.IMAGE_ICONE) <NEW_LINE> pygame.display.set_icon(icone) <NEW_LINE> pygame.display.set_caption(cs.WINDOW_TITLE) <NEW_LINE> pygame.key.set_repeat(100, 30) <NEW_LINE> pygame.time.Clock().tick(30)
The class for the window game setting.
62598fb64a966d76dd5eefd4
@pulumi.output_type <NEW_LINE> class GetCertificateResult: <NEW_LINE> <INDENT> def __init__(__self__, certificates=None, id=None, url=None, verify_chain=None): <NEW_LINE> <INDENT> if certificates and not isinstance(certificates, list): <NEW_LINE> <INDENT> raise TypeError("Expected argument 'certificates' to be a list") <NEW_LINE> <DEDENT> pulumi.set(__self__, "certificates", certificates) <NEW_LINE> if id and not isinstance(id, str): <NEW_LINE> <INDENT> raise TypeError("Expected argument 'id' to be a str") <NEW_LINE> <DEDENT> pulumi.set(__self__, "id", id) <NEW_LINE> if url and not isinstance(url, str): <NEW_LINE> <INDENT> raise TypeError("Expected argument 'url' to be a str") <NEW_LINE> <DEDENT> pulumi.set(__self__, "url", url) <NEW_LINE> if verify_chain and not isinstance(verify_chain, bool): <NEW_LINE> <INDENT> raise TypeError("Expected argument 'verify_chain' to be a bool") <NEW_LINE> <DEDENT> pulumi.set(__self__, "verify_chain", verify_chain) <NEW_LINE> <DEDENT> @property <NEW_LINE> @pulumi.getter <NEW_LINE> def certificates(self) -> Sequence['outputs.GetCertificateCertificateResult']: <NEW_LINE> <INDENT> return pulumi.get(self, "certificates") <NEW_LINE> <DEDENT> @property <NEW_LINE> @pulumi.getter <NEW_LINE> def id(self) -> str: <NEW_LINE> <INDENT> return pulumi.get(self, "id") <NEW_LINE> <DEDENT> @property <NEW_LINE> @pulumi.getter <NEW_LINE> def url(self) -> str: <NEW_LINE> <INDENT> return pulumi.get(self, "url") <NEW_LINE> <DEDENT> @property <NEW_LINE> @pulumi.getter(name="verifyChain") <NEW_LINE> def verify_chain(self) -> Optional[bool]: <NEW_LINE> <INDENT> return pulumi.get(self, "verify_chain")
A collection of values returned by getCertificate.
62598fb6442bda511e95c556
class GetValueListSelection_String_args: <NEW_LINE> <INDENT> thrift_spec = ( None, (1, TType.STRUCT, '_id', (RemoteValueID, RemoteValueID.thrift_spec), None, ), ) <NEW_LINE> def __init__(self, _id=None,): <NEW_LINE> <INDENT> self._id = _id <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.STRUCT: <NEW_LINE> <INDENT> self._id = RemoteValueID() <NEW_LINE> self._id.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('GetValueListSelection_String_args') <NEW_LINE> if self._id is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('_id', TType.STRUCT, 1) <NEW_LINE> self._id.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other)
Attributes: - _id
62598fb697e22403b383b003
class Encoder(simplejson.JSONEncoder): <NEW_LINE> <INDENT> def default(self, o): <NEW_LINE> <INDENT> if hasattr(o, "to_jsonable") and callable(o.to_jsonable): <NEW_LINE> <INDENT> return o.to_jsonable() <NEW_LINE> <DEDENT> if desktop.lib.thrift_util.is_thrift_struct(o): <NEW_LINE> <INDENT> return desktop.lib.thrift_util.thrift2json(o) <NEW_LINE> <DEDENT> if isinstance(o, models.Model): <NEW_LINE> <INDENT> x = serializers.serialize("python", [o]) <NEW_LINE> assert len(x) == 1 <NEW_LINE> return x[0] <NEW_LINE> <DEDENT> return simplejson.JSONEncoder.default(self, o)
Automatically encodes JSON for Django models and Thrift objects, as well as objects that have "to_json" operations.
62598fb6f9cc0f698b1c534b
class PhoneBook(dict): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.phonebook = {} <NEW_LINE> <DEDENT> def add_contact(self, name, number=None): <NEW_LINE> <INDENT> self.phonebook[name] = number <NEW_LINE> return self.phonebook <NEW_LINE> <DEDENT> def view_contact(self, name=False): <NEW_LINE> <INDENT> print(self.phonebook) <NEW_LINE> <DEDENT> def update_contact(self, name, number): <NEW_LINE> <INDENT> self.phonebook[name] = number <NEW_LINE> return self.phonebook <NEW_LINE> <DEDENT> def delete_contact(self, name): <NEW_LINE> <INDENT> self.phonebook.pop(name, 'Name not found')
Subclassed to dict, holds methods that manage a phone book
62598fb666673b3332c304cc
class Results: <NEW_LINE> <INDENT> def __init__(self, w): <NEW_LINE> <INDENT> self.top = Tkinter.Toplevel(w, name="results") <NEW_LINE> self.top.transient(w) <NEW_LINE> self.top.bind('<Return>', self.hide) <NEW_LINE> self.top.bind('<Escape>', self.hide) <NEW_LINE> self.text = Tkinter.Text(self.top, name="text") <NEW_LINE> self.text.grid() <NEW_LINE> self.text.bind('<Double-Button-1>', self.showFile) <NEW_LINE> close = Tkinter.Button(self.top, name="close", default=Tkinter.ACTIVE, command=self.hide) <NEW_LINE> close.grid() <NEW_LINE> self.text.update_idletasks() <NEW_LINE> <DEDENT> def show(self, text): <NEW_LINE> <INDENT> self.text.delete("0.1", "end") <NEW_LINE> self.text.insert("0.1", text) <NEW_LINE> self.top.deiconify() <NEW_LINE> self.top.lift() <NEW_LINE> <DEDENT> def hide(self, *unused): <NEW_LINE> <INDENT> self.top.withdraw() <NEW_LINE> <DEDENT> def line(self): <NEW_LINE> <INDENT> return split(self.text.index(Tkinter.CURRENT), ".")[0] <NEW_LINE> <DEDENT> def showFile(self, unused): <NEW_LINE> <INDENT> import re <NEW_LINE> line = self.line() <NEW_LINE> text = self.text.get(line + ".0", line + ".end") <NEW_LINE> text = rstrip(text) <NEW_LINE> result = re.search("(.*):([0-9]+):", text) <NEW_LINE> if result: <NEW_LINE> <INDENT> path, line = result.groups() <NEW_LINE> edit(path, int(line)) <NEW_LINE> self.text.after(0, self.selectLine) <NEW_LINE> <DEDENT> <DEDENT> def selectLine(self): <NEW_LINE> <INDENT> line = self.line() <NEW_LINE> self.text.tag_remove(Tkinter.SEL, "1.0", Tkinter.END) <NEW_LINE> self.text.tag_add(Tkinter.SEL, line + ".0", line + ".end")
Display the warnings produced by checker
62598fb68a349b6b43686339
class MongoInstance(Startable): <NEW_LINE> <INDENT> def __init__(self, prefab, addr=None, private_port=27021, public_port=None, type_="shard", replica='', configdb='', dbdir=None): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.prefab = prefab <NEW_LINE> if not addr: <NEW_LINE> <INDENT> self.addr = prefab.executor.addr <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.addr = addr <NEW_LINE> <DEDENT> self.private_port = private_port <NEW_LINE> self.public_port = public_port <NEW_LINE> self.type_ = type_ <NEW_LINE> self.replica = replica <NEW_LINE> self.configdb = configdb <NEW_LINE> if dbdir is None: <NEW_LINE> <INDENT> dbdir = "$VARDIR/data/db" <NEW_LINE> <DEDENT> if public_port is None: <NEW_LINE> <INDENT> public_port = private_port <NEW_LINE> <DEDENT> self.dbdir = dbdir <NEW_LINE> self.logger.info(prefab, private_port, public_port, type_, replica, configdb, dbdir) <NEW_LINE> <DEDENT> def _install(self): <NEW_LINE> <INDENT> super()._install() <NEW_LINE> self.prefab.core.dir_ensure(self.dbdir) <NEW_LINE> return self.prefab.apps.mongodb.build(start=False) <NEW_LINE> <DEDENT> def _gen_service_name(self): <NEW_LINE> <INDENT> name = "ourmongos" if self.type_ == "mongos" else "ourmongod" <NEW_LINE> if self.type_ == "cfg": <NEW_LINE> <INDENT> name += "_cfg" <NEW_LINE> <DEDENT> return name <NEW_LINE> <DEDENT> def _gen_service_cmd(self): <NEW_LINE> <INDENT> cmd = "mongos" if self.type_ == "mongos" else "mongod" <NEW_LINE> args = "" <NEW_LINE> if self.type_ == "cfg": <NEW_LINE> <INDENT> args += " --configsvr" <NEW_LINE> <DEDENT> if self.type_ != "mongos": <NEW_LINE> <INDENT> args += " --dbpath %s" % (self.dbdir) <NEW_LINE> <DEDENT> if self.private_port: <NEW_LINE> <INDENT> args += " --port %s" % (self.private_port) <NEW_LINE> <DEDENT> if self.replica: <NEW_LINE> <INDENT> args += " --replSet %s" % (self.replica) <NEW_LINE> <DEDENT> if self.configdb: <NEW_LINE> <INDENT> args += " --configdb %s" % (self.configdb) <NEW_LINE> <DEDENT> return '$BINDIR/' + cmd + args <NEW_LINE> <DEDENT> @Startable.ensure_installed <NEW_LINE> def _start(self): <NEW_LINE> <INDENT> super()._start() <NEW_LINE> self.logger.info("starting: ", self._gen_service_name(), self._gen_service_cmd()) <NEW_LINE> pm = self.prefab.system.processmanager.get() <NEW_LINE> pm.ensure(self._gen_service_name(), self._gen_service_cmd()) <NEW_LINE> return a <NEW_LINE> <DEDENT> @Startable.ensure_started <NEW_LINE> def execute(self, cmd): <NEW_LINE> <INDENT> for i in range(5): <NEW_LINE> <INDENT> rc, out, err = self.prefab.core.run( "LC_ALL=C $BINDIR/mongo --port %s --eval '%s'" % (self.private_port, cmd.replace( "\\", "\\\\").replace( "'", "\\'")), die=False) <NEW_LINE> if not rc and out.find('errmsg') == -1: <NEW_LINE> <INDENT> self.logger.info('command executed %s' % (cmd)) <NEW_LINE> break <NEW_LINE> <DEDENT> sleep(5) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.logger.info('cannot execute command %s' % (cmd)) <NEW_LINE> <DEDENT> return rc, out <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "%s:%s" % (self.addr, self.public_port) <NEW_LINE> <DEDENT> __str__ = __repr__
This class represents a mongo instance
62598fb6a8370b77170f04db
class Application(object): <NEW_LINE> <INDENT> deserialized_types = { 'application_id': 'str' } <NEW_LINE> attribute_map = { 'application_id': 'applicationId' } <NEW_LINE> supports_multiple_types = False <NEW_LINE> def __init__(self, application_id=None): <NEW_LINE> <INDENT> self.__discriminator_value = None <NEW_LINE> self.application_id = application_id <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.deserialized_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x.value if isinstance(x, Enum) else x, value )) <NEW_LINE> <DEDENT> elif isinstance(value, Enum): <NEW_LINE> <INDENT> result[attr] = value.value <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else (item[0], item[1].value) if isinstance(item[1], Enum) else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, Application): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
An object containing an application ID. This is used to verify that the request was intended for your service. :param application_id: A string representing the application identifier for your skill. :type application_id: (optional) str
62598fb65fdd1c0f98e5e08c
class EntryModeSet(Reply): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def parse(cls, packet): <NEW_LINE> <INDENT> arg0, _ = super(EntryModeSet, cls).parse(packet) <NEW_LINE> return arg0
@brief DIRECT EntryModeSet reply packet parser @see PATO_DIRECT_EMS
62598fb63d592f4c4edbafbf
class TruncatedNormalInitializer(Initializer): <NEW_LINE> <INDENT> def __init__(self, loc=0.0, scale=1.0, seed=0): <NEW_LINE> <INDENT> assert loc is not None <NEW_LINE> assert scale is not None <NEW_LINE> assert seed is not None <NEW_LINE> super(TruncatedNormalInitializer, self).__init__() <NEW_LINE> self._mean = loc <NEW_LINE> self._std_dev = scale <NEW_LINE> self._seed = seed <NEW_LINE> <DEDENT> def __call__(self, var, block): <NEW_LINE> <INDENT> assert isinstance(var, framework.Variable) <NEW_LINE> assert isinstance(block, framework.Block) <NEW_LINE> if self._seed == 0: <NEW_LINE> <INDENT> self._seed = block.program.random_seed <NEW_LINE> <DEDENT> op = block._prepend_op( type="truncated_gaussian_random", outputs={"Out": var}, attrs={ "shape": var.shape, "dtype": int(var.dtype), "mean": self._mean, "std": self._std_dev, "seed": self._seed }) <NEW_LINE> var.op = op <NEW_LINE> return op
Implements the Random TruncatedNormal(Gaussian) distribution initializer Args: loc (float): mean of the normal distribution scale (float): standard deviation of the normal distribution seed (int): random seed Examples: .. code-block:: python fc = fluid.layers.fc(input=x, size=10, param_attr=fluid.initializer.TruncatedNormal(loc=0.0, scale=2.0))
62598fb61b99ca400228f5af
class SpecialoffersListView(ChunkListView, SpecialoffersParamsValidatorMixin): <NEW_LINE> <INDENT> CATEGORY_MODEL = SpecialoffersCategory <NEW_LINE> CHUNK_MODEL = Specialoffers <NEW_LINE> GENERAL_LINK = GENERAL_LINK <NEW_LINE> GENERAL_LABEL = GENERAL_LABEL <NEW_LINE> APP_NAME = APP_NAME <NEW_LINE> APP_LABEL = APP_LABEL
Specialoffers List View.
62598fb65fdd1c0f98e5e08d
class cached(object): <NEW_LINE> <INDENT> def __init__(self, key=NoDefault, expire="never", type=None, query_args=None, cache_headers=('content-type', 'content-length'), invalidate_on_startup=False, cache_response=True, **b_kwargs): <NEW_LINE> <INDENT> self.key = key <NEW_LINE> self.expire = expire <NEW_LINE> self.type = type <NEW_LINE> self.cache_headers = cache_headers <NEW_LINE> self.invalidate_on_startup = invalidate_on_startup <NEW_LINE> self.cache_response = cache_response <NEW_LINE> self.beaker_options = b_kwargs <NEW_LINE> <DEDENT> def __call__(self, func): <NEW_LINE> <INDENT> decoration = Decoration.get_decoration(func) <NEW_LINE> def controller_wrapper(next_caller): <NEW_LINE> <INDENT> if self.invalidate_on_startup: <NEW_LINE> <INDENT> starttime = time.time() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> starttime = None <NEW_LINE> <DEDENT> def cached_call_controller(tg_config, controller, remainder, params): <NEW_LINE> <INDENT> req = request._current_obj() <NEW_LINE> if self.key: <NEW_LINE> <INDENT> key_dict = req.args_params <NEW_LINE> if self.key != NoDefault: <NEW_LINE> <INDENT> if isinstance(self.key, (list, tuple)): <NEW_LINE> <INDENT> key_dict = dict((k, key_dict[k]) for k in key_dict) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> key_dict = {self.key: key_dict[self.key]} <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> key_dict = {} <NEW_LINE> <DEDENT> namespace, cache_key = create_cache_key(func, key_dict, req.controller_state.controller) <NEW_LINE> req._fast_setattr('caching', Bunch(namespace=namespace, key=cache_key)) <NEW_LINE> return _cached_call(next_caller, (tg_config, controller, remainder, params), {}, namespace, cache_key, expire=self.expire, type=self.type, starttime=starttime, cache_headers=self.cache_headers, cache_response=self.cache_response, cache_extra_args=self.beaker_options) <NEW_LINE> <DEDENT> return cached_call_controller <NEW_LINE> <DEDENT> decoration._register_controller_wrapper(controller_wrapper) <NEW_LINE> return func
Decorator to cache the controller. The namespace and cache key used to cache the controller are available as ``request.caching.namespace`` and ``request.caching.key``. This only caches the controller, not the template, validation or the hooks associated to the controller. If you also want to cache template remember to return ``tg_cache`` option with the same cache key from the controller. The following parameters are accepted: ``key`` - Specifies the controller parameters used to generate the cache key. NoDefault - Uses function name and parameters (excluding args) as the key (default) None - No variable key, uses only function name as key string - Use function name and only "key" parameter list - Use function name and all parameters listed ``expire`` Time in seconds before cache expires, or the string "never". Defaults to "never" ``type`` Type of cache to use: dbm, memory, file, memcached, or None for Beaker's default ``cache_headers`` A tuple of header names indicating response headers that will also be cached. ``invalidate_on_startup`` If True, the cache will be invalidated each time the application starts or is restarted. ``cache_response`` Determines whether the response at the time the cache is used should be cached or not, defaults to True. .. note:: When cache_response is set to False, the cache_headers argument is ignored as none of the response is cached.
62598fb6379a373c97d99114
class ListChatsCommand: <NEW_LINE> <INDENT> name = settings.GET_CHATS <NEW_LINE> @login_required_db <NEW_LINE> def update(self, proto, msg, *args, **kwargs): <NEW_LINE> <INDENT> user = db.User.by_name(msg.user_account_name) <NEW_LINE> proto.write( Message.success( 202, **{ settings.LIST_INFO: [{ 'name': c.name, 'owner': c.owner.username if c.owner else None, 'avatar': c.avatar, 'is_personal': c.is_personal, 'members': [i.username for i in c.members], } for c in user.chats], settings.ACTION: settings.GET_CHATS, })) <NEW_LINE> logger.info(f'User {user.username} get list chats') <NEW_LINE> proto.notify(f'done_{self.name}')
Обрабатывает запросы на получение списка контактов пользователя.
62598fb6be8e80087fbbf166
class EnumValidator(EnumValidatorBase): <NEW_LINE> <INDENT> def __init__(self, values, errorMsgKey): <NEW_LINE> <INDENT> super(EnumValidator,self).__init__( errorMsgKey) <NEW_LINE> self.__values = values <NEW_LINE> <DEDENT> def getValueLabelList(self, req): <NEW_LINE> <INDENT> return self.__values
Validates that the value passed in is one of the values passed to the constructor.
62598fb699cbb53fe6830fd4
class TestValidateSchemas(unittest.TestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setupClass(cls): <NEW_LINE> <INDENT> args = cls._makeArgs() <NEW_LINE> cls.schemaProcessor = compile_schemas.SchemaProcessor(args) <NEW_LINE> cls.schemaProcessor.run() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def tearDownClass(cls): <NEW_LINE> <INDENT> cls.schemaProcessor.cleanup() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def getClasses(cls): <NEW_LINE> <INDENT> return cls.schemaProcessor.getClasses() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _makeArgs(self): <NEW_LINE> <INDENT> class FakeArgs(object): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> args = FakeArgs() <NEW_LINE> args.version = "test" <NEW_LINE> args.avro_tools_jar = None <NEW_LINE> return args <NEW_LINE> <DEDENT> def testSchemaProperties(self): <NEW_LINE> <INDENT> for schemaClass in self.getClasses(): <NEW_LINE> <INDENT> self._checkProperties(schemaClass) <NEW_LINE> <DEDENT> <DEDENT> def _checkProperties(self, schemaClass): <NEW_LINE> <INDENT> if isinstance(schemaClass.schema, avro.schema.RecordSchema): <NEW_LINE> <INDENT> for field in schemaClass.getFields(): <NEW_LINE> <INDENT> if isinstance(field.type, avro.schema.UnionSchema): <NEW_LINE> <INDENT> t0 = field.type.schemas[0] <NEW_LINE> if not (isinstance(t0, avro.schema.PrimitiveSchema) and t0.type == "null"): <NEW_LINE> <INDENT> msg = "Schema union assumptions violated: {}.{}" <NEW_LINE> raise Exception(msg.format( schemaClass.name, field.name))
Ensure the schemas conform to certain rules
62598fb63317a56b869be5cc
class Authorizer(wsgi.Middleware): <NEW_LINE> <INDENT> def __init__(self, application): <NEW_LINE> <INDENT> super(Authorizer, self).__init__(application) <NEW_LINE> self.action_roles = { 'CloudController': { 'DescribeAvailabilityZones': ['all'], 'DescribeRegions': ['all'], 'DescribeSnapshots': ['all'], 'DescribeKeyPairs': ['all'], 'CreateKeyPair': ['all'], 'DeleteKeyPair': ['all'], 'DescribeSecurityGroups': ['all'], 'ImportKeyPair': ['all'], 'AuthorizeSecurityGroupIngress': ['netadmin'], 'RevokeSecurityGroupIngress': ['netadmin'], 'CreateSecurityGroup': ['netadmin'], 'DeleteSecurityGroup': ['netadmin'], 'GetConsoleOutput': ['projectmanager', 'sysadmin'], 'DescribeVolumes': ['projectmanager', 'sysadmin'], 'CreateVolume': ['projectmanager', 'sysadmin'], 'AttachVolume': ['projectmanager', 'sysadmin'], 'DetachVolume': ['projectmanager', 'sysadmin'], 'DescribeInstances': ['all'], 'DescribeAddresses': ['all'], 'AllocateAddress': ['netadmin'], 'ReleaseAddress': ['netadmin'], 'AssociateAddress': ['netadmin'], 'DisassociateAddress': ['netadmin'], 'RunInstances': ['projectmanager', 'sysadmin'], 'TerminateInstances': ['projectmanager', 'sysadmin'], 'RebootInstances': ['projectmanager', 'sysadmin'], 'UpdateInstance': ['projectmanager', 'sysadmin'], 'StartInstances': ['projectmanager', 'sysadmin'], 'StopInstances': ['projectmanager', 'sysadmin'], 'DeleteVolume': ['projectmanager', 'sysadmin'], 'DescribeImages': ['all'], 'DeregisterImage': ['projectmanager', 'sysadmin'], 'RegisterImage': ['projectmanager', 'sysadmin'], 'DescribeImageAttribute': ['all'], 'ModifyImageAttribute': ['projectmanager', 'sysadmin'], 'UpdateImage': ['projectmanager', 'sysadmin'], 'CreateImage': ['projectmanager', 'sysadmin'], }, 'AdminController': { }, } <NEW_LINE> <DEDENT> @webob.dec.wsgify(RequestClass=wsgi.Request) <NEW_LINE> def __call__(self, req): <NEW_LINE> <INDENT> context = req.environ['nova.context'] <NEW_LINE> controller = req.environ['ec2.request'].controller.__class__.__name__ <NEW_LINE> action = req.environ['ec2.request'].action <NEW_LINE> allowed_roles = self.action_roles[controller].get(action, ['none']) <NEW_LINE> if self._matches_any_role(context, allowed_roles): <NEW_LINE> <INDENT> return self.application <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> LOG.info(_LI('Unauthorized request for controller=%(controller)s ' 'and action=%(action)s'), {'controller': controller, 'action': action}, context=context) <NEW_LINE> raise webob.exc.HTTPUnauthorized() <NEW_LINE> <DEDENT> <DEDENT> def _matches_any_role(self, context, roles): <NEW_LINE> <INDENT> if context.is_admin: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if 'all' in roles: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if 'none' in roles: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return any(role in context.roles for role in roles)
Authorize an EC2 API request. Return a 401 if ec2.controller and ec2.action in WSGI environ may not be executed in nova.context.
62598fb69f288636728188c3
@attrs(auto_attribs=True, frozen=True) <NEW_LINE> class JSONDeserializerWithRequestIdRequired(Deserializer): <NEW_LINE> <INDENT> schema: marshmallow.Schema <NEW_LINE> request_id_field: str = 'request_id' <NEW_LINE> status_field: str = 'status' <NEW_LINE> error_field: str = 'error' <NEW_LINE> _status_error: str = 'ERROR' <NEW_LINE> def deserialize(self, message: Any) -> Mapping[str, Any]: <NEW_LINE> <INDENT> data = message.data.decode('utf-8') <NEW_LINE> deserialized, _ = self.schema.loads(data) <NEW_LINE> return deserialized <NEW_LINE> <DEDENT> def build_error_result(self, message: Any, error: Exception) -> Mapping[str, Any]: <NEW_LINE> <INDENT> attributes = json.loads(message.data) <NEW_LINE> try: <NEW_LINE> <INDENT> return { self.request_id_field: attributes[self.request_id_field], self.status_field: self._status_error, self.error_field: repr(error), } <NEW_LINE> <DEDENT> except KeyError as e: <NEW_LINE> <INDENT> return { self.request_id_field: '', self.status_field: self._status_error, self.error_field: f'{repr(e)}: ' f'Message contains no {self.request_id_field}', }
Deserializer for Google Pub/Sub messages which expects a message of certain schema to be written in `message.data` as JSON encoded into binary data with utf-8. Schema used with this serializer must define some field which is used as request id (you can specify which one in constructor). If `JSONDeserializerWithRequestIdRequired` fails to deserialize some message, you can use `build_error_result` to fetch request id and provide error message.
62598fb6a219f33f346c6903
class BinExprNode(ExprNode): <NEW_LINE> <INDENT> def __init__(self, operator, operand_1, operand_2): <NEW_LINE> <INDENT> assert(isinstance(operator, str)) <NEW_LINE> assert(isinstance(operand_1, SingleExprNode)) <NEW_LINE> assert(isinstance(operand_2, SingleExprNode)) <NEW_LINE> self.operator = operator <NEW_LINE> self.operand_1 = operand_1 <NEW_LINE> self.operand_2 = operand_2 <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> output = "{operand_1} {operator} {operand_2}". format(operand_1=str(self.operand_1), operator=self.operator, operand_2=str(self.operand_2)) <NEW_LINE> return output
Represents binary expressions such as 'a + 2'
62598fb65166f23b2e2434db
class Image_MovieFrames__GUI(MovieFrames): <NEW_LINE> <INDENT> def __init__(self, seq_plotter): <NEW_LINE> <INDENT> MovieFrames.__init__(self, seq_plotter) <NEW_LINE> self.main_Window = None <NEW_LINE> self.redraw_flag=False <NEW_LINE> <DEDENT> def _setup_figure_and_axes(self, mfs): <NEW_LINE> <INDENT> self.MFS = mfs <NEW_LINE> self.figure = Figure(facecolor='white') <NEW_LINE> self.canvas = FigureCanvas(self.figure) <NEW_LINE> self.canvas.set_size_request( *self.MFS.figsize_points ) <NEW_LINE> for box in self.MFS.axes_boxes: <NEW_LINE> <INDENT> self.ax.append( self.figure.add_axes(box) ) <NEW_LINE> <DEDENT> <DEDENT> def __erase_axes(self): <NEW_LINE> <INDENT> for A in self.ax: <NEW_LINE> <INDENT> A.set_frame_on(False) <NEW_LINE> A.xaxis.set_visible(False) <NEW_LINE> A.yaxis.set_visible(False) <NEW_LINE> <DEDENT> <DEDENT> def plot(self,**kwargs): <NEW_LINE> <INDENT> MovieFrames.plot(self,**kwargs) <NEW_LINE> self.__erase_axes() <NEW_LINE> <DEDENT> def replot(self,**kwargs): <NEW_LINE> <INDENT> MovieFrames.plot(self,animated=True,**kwargs) <NEW_LINE> self.__erase_axes() <NEW_LINE> <DEDENT> def animation_update(self,i_frame): <NEW_LINE> <INDENT> for P,A in zip(self.seq_plotter,self.ax): <NEW_LINE> <INDENT> P.animation_update( A, i_frame ) <NEW_LINE> <DEDENT> <DEDENT> def set_animated(self,val): <NEW_LINE> <INDENT> for P in self.seq_plotter: <NEW_LINE> <INDENT> P.set_animated(val) <NEW_LINE> <DEDENT> <DEDENT> def set_main_window(self,window): <NEW_LINE> <INDENT> self.main_Window=window
Base class for GUI version of Movie Frames ---> needs matplotlib.backends.backend_gtkagg! do not clear axes each time for the next animation frame ------------- Contains: ------------- self.redraw_flag -- nedeed by MovieEngine
62598fb64428ac0f6e658621
class ListInstancesAsyncPager: <NEW_LINE> <INDENT> def __init__(self, method: Callable[..., Awaitable[cloud_redis.ListInstancesResponse]], request: cloud_redis.ListInstancesRequest, response: cloud_redis.ListInstancesResponse, *, metadata: Sequence[Tuple[str, str]] = ()): <NEW_LINE> <INDENT> self._method = method <NEW_LINE> self._request = cloud_redis.ListInstancesRequest(request) <NEW_LINE> self._response = response <NEW_LINE> self._metadata = metadata <NEW_LINE> <DEDENT> def __getattr__(self, name: str) -> Any: <NEW_LINE> <INDENT> return getattr(self._response, name) <NEW_LINE> <DEDENT> @property <NEW_LINE> async def pages(self) -> AsyncIterator[cloud_redis.ListInstancesResponse]: <NEW_LINE> <INDENT> yield self._response <NEW_LINE> while self._response.next_page_token: <NEW_LINE> <INDENT> self._request.page_token = self._response.next_page_token <NEW_LINE> self._response = await self._method(self._request, metadata=self._metadata) <NEW_LINE> yield self._response <NEW_LINE> <DEDENT> <DEDENT> def __aiter__(self) -> AsyncIterator[cloud_redis.Instance]: <NEW_LINE> <INDENT> async def async_generator(): <NEW_LINE> <INDENT> async for page in self.pages: <NEW_LINE> <INDENT> for response in page.instances: <NEW_LINE> <INDENT> yield response <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return async_generator() <NEW_LINE> <DEDENT> def __repr__(self) -> str: <NEW_LINE> <INDENT> return '{0}<{1!r}>'.format(self.__class__.__name__, self._response)
A pager for iterating through ``list_instances`` requests. This class thinly wraps an initial :class:`google.cloud.redis_v1.types.ListInstancesResponse` object, and provides an ``__aiter__`` method to iterate through its ``instances`` field. If there are more pages, the ``__aiter__`` method will make additional ``ListInstances`` requests and continue to iterate through the ``instances`` field on the corresponding responses. All the usual :class:`google.cloud.redis_v1.types.ListInstancesResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup.
62598fb6a79ad1619776a16d
class FacticalWeatherInfo(BoxWithSchema): <NEW_LINE> <INDENT> SCHEMA = vol.Schema({ vol.Required("temp"): number, vol.Required("feels_like"): number, vol.Optional("temp_water"): number, vol.Required("icon"): Icon.validate, vol.Required("condition"): Condition.validate, vol.Required("wind_speed"): number, vol.Required("wind_gust"): number, vol.Required("wind_dir"): WindDir.validate, vol.Required("pressure_mm"): number, vol.Required("pressure_pa"): number, vol.Required("humidity"): number, vol.Required("daytime"): Daytime.validate, vol.Required("polar"): bool, vol.Required("season"): Season.validate, vol.Required("obs_time"): number, vol.Optional("prec_type"): number, vol.Optional("prec_strength"): number, vol.Optional("cloudness"): number, }, extra=vol.ALLOW_EXTRA)
Объект fact Объект содержит информацию о погоде на данный момент.
62598fb6091ae35668704d1f
class Dict(dict): <NEW_LINE> <INDENT> def __init__(self, names=(), values=(), **kw): <NEW_LINE> <INDENT> super(Dict, self).__init__(**kw) <NEW_LINE> for k, v in zip(names, values): <NEW_LINE> <INDENT> self[k] = v <NEW_LINE> <DEDENT> <DEDENT> def __getattr__(self, key): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self[key] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise AttributeError(r"'Dict' object has no attribute '%s'" % key) <NEW_LINE> <DEDENT> <DEDENT> def __setattr__(self, key, value): <NEW_LINE> <INDENT> self[key] = value
字典类,改写构造方法,增加getattr、setattr魔法方法
62598fb69c8ee823130401f3
class Invertible1x1Conv(nn.Module): <NEW_LINE> <INDENT> def __init__(self, n_channels=3, lu_factorize=False): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.lu_factorize = lu_factorize <NEW_LINE> w = torch.randn(n_channels, n_channels) <NEW_LINE> w = torch.qr(w)[0] <NEW_LINE> if lu_factorize: <NEW_LINE> <INDENT> p, l, u = torch.btriunpack(*w.unsqueeze(0).btrifact()) <NEW_LINE> self.p, self.l, self.u = nn.Parameter(p.squeeze()), nn.Parameter(l.squeeze()), nn.Parameter(u.squeeze()) <NEW_LINE> s = self.u.diag() <NEW_LINE> self.log_s = nn.Parameter(s.abs().log()) <NEW_LINE> self.register_buffer('sign_s', s.sign()) <NEW_LINE> self.register_buffer('l_mask', torch.tril(torch.ones_like(self.l), -1)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.w = nn.Parameter(w) <NEW_LINE> <DEDENT> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> B,C,H,W = x.shape <NEW_LINE> if self.lu_factorize: <NEW_LINE> <INDENT> l = self.l * self.l_mask + torch.eye(C).to(self.l.device) <NEW_LINE> u = self.u * self.l_mask.t() + torch.diag(self.sign_s * self.log_s.exp()) <NEW_LINE> self.w = self.p @ l @ u <NEW_LINE> logdet = self.log_s.sum() * H * W <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logdet = torch.slogdet(self.w)[-1] * H * W <NEW_LINE> <DEDENT> return F.conv2d(x, self.w.view(C,C,1,1)), logdet <NEW_LINE> <DEDENT> def inverse(self, z): <NEW_LINE> <INDENT> B,C,H,W = z.shape <NEW_LINE> if self.lu_factorize: <NEW_LINE> <INDENT> l = torch.inverse(self.l * self.l_mask + torch.eye(C).to(self.l.device)) <NEW_LINE> u = torch.inverse(self.u * self.l_mask.t() + torch.diag(self.sign_s * self.log_s.exp())) <NEW_LINE> w_inv = u @ l @ self.p.inverse() <NEW_LINE> logdet = - self.log_s.sum() * H * W <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> w_inv = self.w.inverse() <NEW_LINE> logdet = - torch.slogdet(self.w)[-1] * H * W <NEW_LINE> <DEDENT> return F.conv2d(z, w_inv.view(C,C,1,1)), logdet
Invertible 1x1 convolution layer; cf Glow section 3.2
62598fb6009cb60464d01622
class RelatedChannelIdField(serializers.PrimaryKeyRelatedField): <NEW_LINE> <INDENT> def get_queryset(self): <NEW_LINE> <INDENT> if self.context is None or 'request' not in self.context: <NEW_LINE> <INDENT> return mpmodels.Channel.objects.none() <NEW_LINE> <DEDENT> user = self.context['request'].user <NEW_LINE> return mpmodels.Channel.objects.all().editable_by_user(user)
Related field serializer for media items or playlists which asserts that the channel field can only be set to a channel which the current user has edit permissions on. If there is no user, the empty queryset is returned.
62598fb6be383301e02538fc
class InterfacePlayGameTest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.bot = unitility.AutoBot() <NEW_LINE> self.interface = interface.Interface(self.bot) <NEW_LINE> self.interface.do_stats = unitility.ProtoObject() <NEW_LINE> <DEDENT> def testAgain(self): <NEW_LINE> <INDENT> self.bot.replies = ['win', 'y', 'loss', 'n', '!'] <NEW_LINE> self.interface.play_game(unitility.TestGame, '') <NEW_LINE> self.assertEqual(2, len(self.bot.results)) <NEW_LINE> <DEDENT> def testCheat(self): <NEW_LINE> <INDENT> self.bot.replies = ["& setattr(self, 'flags', 2)", 'win', 'n', '!'] <NEW_LINE> self.interface.play_game(unitility.TestGame, '') <NEW_LINE> check = '\nStatistics were calculated with the following options: cheat.\n' <NEW_LINE> self.assertIn(check, self.bot.info) <NEW_LINE> <DEDENT> def testGipf(self): <NEW_LINE> <INDENT> self.bot.replies = ["& setattr(self, 'flags', 8)", 'win', 'n', '!'] <NEW_LINE> self.interface.play_game(unitility.TestGame, '') <NEW_LINE> check = '\nStatistics were calculated with the following options: gipf.\n' <NEW_LINE> self.assertIn(check, self.bot.info) <NEW_LINE> <DEDENT> def testMultiFilter(self): <NEW_LINE> <INDENT> self.bot.replies = ["& setattr(self, 'flags', 130)", 'win', 'n', '!'] <NEW_LINE> self.interface.play_game(unitility.TestGame, 'cheat xyzzy') <NEW_LINE> check = '\nStatistics were calculated with the following options: cheat xyzzy.\n' <NEW_LINE> self.assertIn(check, self.bot.info) <NEW_LINE> <DEDENT> def testNoFilter(self): <NEW_LINE> <INDENT> self.bot.replies = ['win', 'n', '!'] <NEW_LINE> self.interface.play_game(unitility.TestGame, '') <NEW_LINE> self.assertEqual(('Unit / ',), self.interface.do_stats.args) <NEW_LINE> <DEDENT> def testNotAgain(self): <NEW_LINE> <INDENT> self.bot.replies = ['win', 'n', '!'] <NEW_LINE> self.interface.play_game(unitility.TestGame, '') <NEW_LINE> self.assertEqual(1, len(self.bot.results)) <NEW_LINE> <DEDENT> def testOptionError(self): <NEW_LINE> <INDENT> self.bot.replies = ['win', 'n', '!'] <NEW_LINE> self.assertFalse(self.interface.play_game(unitility.TestGame, 'error')) <NEW_LINE> <DEDENT> def testXyzzy(self): <NEW_LINE> <INDENT> self.bot.replies = ["& setattr(self, 'flags', 128)", 'win', 'n', '!'] <NEW_LINE> self.interface.play_game(unitility.TestGame, '') <NEW_LINE> check = '\nStatistics were calculated with the following options: xyzzy.\n' <NEW_LINE> self.assertIn(check, self.bot.info)
Tests playing a game through the interface. (unittest.TestCase)
62598fb6e1aae11d1e7ce8a4
class FileOption(_OptionBase[str, _StrDefault]): <NEW_LINE> <INDENT> option_type: Any = custom_types.file_option
A file option.
62598fb6236d856c2adc94bf
class AbstractInstrumentSimulator: <NEW_LINE> <INDENT> neutron_coordinates_transformer = None <NEW_LINE> def run(self, neutrons, instrument, geometer, context = None): <NEW_LINE> <INDENT> nneutrons = len(neutrons) <NEW_LINE> self.context = context <NEW_LINE> from mcni.seeder import feed <NEW_LINE> feed() <NEW_LINE> components = instrument.components <NEW_LINE> runnable = self.makeRunnable( components, geometer, context = context, ) <NEW_LINE> runnable.setInput('neutrons', neutrons) <NEW_LINE> runnable.getOutput( 'neutrons' ) <NEW_LINE> self.recordNumberOfMCSamples(nneutrons) <NEW_LINE> return <NEW_LINE> <DEDENT> def recordNumberOfMCSamples(self, n): <NEW_LINE> <INDENT> context = self.context <NEW_LINE> outdir = context.getOutputDirInProgress() <NEW_LINE> if outdir is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> import os <NEW_LINE> p = os.path.join(outdir, 'number_of_mc_samples') <NEW_LINE> open(p, 'w').write(str(n)) <NEW_LINE> return <NEW_LINE> <DEDENT> def makeRunnable( self, components, geometer, context = None, ): <NEW_LINE> <INDENT> neutron_coordinates_transformer = self.neutron_coordinates_transformer <NEW_LINE> from SimulationChain import SimulationChain <NEW_LINE> chain = SimulationChain( components, geometer, neutron_coordinates_transformer, context = context, ) <NEW_LINE> return chain <NEW_LINE> <DEDENT> pass
run simulation of an instrument
62598fb68e7ae83300ee919f
class IndicatorADX(Indicator): <NEW_LINE> <INDENT> def __init__(self, equityDataFrame, tickerCode): <NEW_LINE> <INDENT> tableName = "Indicator_ADX" <NEW_LINE> tickerCode = tickerCode <NEW_LINE> insertQuery = "insert or replace into %s (Date, Code, ADX, ADX_ROC) values (?,?,?,?)" % (tableName) <NEW_LINE> indicatorDataFrame = equityDataFrame.ix[:,'Code':] <NEW_LINE> indicatorDataFrame['ADX'] = abstract.ADX(equityDataFrame, timeperiod=14, prices=['High', 'Low', 'Close']) <NEW_LINE> indicatorDataFrame['ADX_ROC'] = abstract.ROC(indicatorDataFrame, timeperiod=5, price='ADX') <NEW_LINE> Indicator.__init__(self, tableName, tickerCode, insertQuery, equityDataFrame, indicatorDataFrame)
Average Directional Indicator(s). 14 Day
62598fb6b7558d589546372d
class Scoreboard(): <NEW_LINE> <INDENT> def __init__(self, ai_settings, screen, stats): <NEW_LINE> <INDENT> self.screen = screen <NEW_LINE> self.screen_rect = screen.get_rect() <NEW_LINE> self.ai_settings = ai_settings <NEW_LINE> self.stats = stats <NEW_LINE> self.text_color = 30, 30, 30 <NEW_LINE> self.font = pygame.font.SysFont(None, 48) <NEW_LINE> self.prep_score() <NEW_LINE> self.prep_high_score() <NEW_LINE> self.prep_level() <NEW_LINE> self.prep_ships() <NEW_LINE> <DEDENT> def prep_score(self): <NEW_LINE> <INDENT> rounded_score = int(round(self.stats.score, -1)) <NEW_LINE> score_str = "{:,}".format(rounded_score) <NEW_LINE> self.score_image = self.font.render(score_str, True, self.text_color, self.ai_settings.bg_color) <NEW_LINE> self.score_rect = self.score_image.get_rect() <NEW_LINE> self.score_rect.right = self.screen_rect.right - 20 <NEW_LINE> self.score_rect.top = 20 <NEW_LINE> <DEDENT> def prep_high_score(self): <NEW_LINE> <INDENT> high_score = int(round(self.stats.high_score, -1)) <NEW_LINE> high_score_str = "{:,}".format(high_score) <NEW_LINE> self.high_score_image = self.font.render(high_score_str, True, self.text_color, self.ai_settings.bg_color) <NEW_LINE> self.high_score_rect = self.high_score_image.get_rect() <NEW_LINE> self.high_score_rect.right = self.screen_rect.centerx <NEW_LINE> self.high_score_rect.top = self.score_rect.top <NEW_LINE> <DEDENT> def prep_level(self): <NEW_LINE> <INDENT> self.level_image = self.font.render(str(self.stats.level), True, self.text_color, self.ai_settings.bg_color) <NEW_LINE> self.level_rect = self.level_image.get_rect() <NEW_LINE> self.level_rect.right = self.score_rect.right <NEW_LINE> self.level_rect.top = self.score_rect.bottom + 10 <NEW_LINE> <DEDENT> def prep_ships(self): <NEW_LINE> <INDENT> self.ships = Group() <NEW_LINE> for ship_number in range(self.stats.ships_left): <NEW_LINE> <INDENT> ship = Ship(self.ai_settings, self.screen) <NEW_LINE> ship.rect.x = 10 + ship_number * ship.rect.width <NEW_LINE> ship.rect.y = 10 <NEW_LINE> self.ships.add(ship) <NEW_LINE> <DEDENT> <DEDENT> def show_score(self): <NEW_LINE> <INDENT> self.screen.blit(self.score_image, self.score_rect) <NEW_LINE> self.screen.blit(self.high_score_image, self.high_score_rect) <NEW_LINE> self.screen.blit(self.level_image, self.level_rect) <NEW_LINE> self.ships.draw(self.screen)
A class to report scoring information
62598fb6e5267d203ee6b9ff
class PricingAggregate(Choices): <NEW_LINE> <INDENT> _ = Choices.Choice <NEW_LINE> sum = _("Sum") << {'function': db.Sum} <NEW_LINE> average = _("Average") << {'function': db.Avg} <NEW_LINE> min = _("Minimum") << {'function': db.Min} <NEW_LINE> max = _("Maximum") << {'function': db.Max}
The way to aggregate values of a variable.
62598fb62c8b7c6e89bd38c4
class BaseVolumeuint16(_object): <NEW_LINE> <INDENT> __swig_setmethods__ = {} <NEW_LINE> __setattr__ = lambda self, name, value: _swig_setattr(self, BaseVolumeuint16, name, value) <NEW_LINE> __swig_getmethods__ = {} <NEW_LINE> __getattr__ = lambda self, name: _swig_getattr(self, BaseVolumeuint16, name) <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> raise AttributeError("No constructor defined") <NEW_LINE> <DEDENT> __repr__ = _swig_repr <NEW_LINE> def getBorderValue(self) -> "PolyVox::BaseVolume< unsigned short >::VoxelType": <NEW_LINE> <INDENT> return _PolyVoxCore.BaseVolumeuint16_getBorderValue(self) <NEW_LINE> <DEDENT> def getEnclosingRegion(self) -> "PolyVox::Region const &": <NEW_LINE> <INDENT> return _PolyVoxCore.BaseVolumeuint16_getEnclosingRegion(self) <NEW_LINE> <DEDENT> def getWidth(self) -> "int32_t": <NEW_LINE> <INDENT> return _PolyVoxCore.BaseVolumeuint16_getWidth(self) <NEW_LINE> <DEDENT> def getHeight(self) -> "int32_t": <NEW_LINE> <INDENT> return _PolyVoxCore.BaseVolumeuint16_getHeight(self) <NEW_LINE> <DEDENT> def getDepth(self) -> "int32_t": <NEW_LINE> <INDENT> return _PolyVoxCore.BaseVolumeuint16_getDepth(self) <NEW_LINE> <DEDENT> def getLongestSideLength(self) -> "int32_t": <NEW_LINE> <INDENT> return _PolyVoxCore.BaseVolumeuint16_getLongestSideLength(self) <NEW_LINE> <DEDENT> def getShortestSideLength(self) -> "int32_t": <NEW_LINE> <INDENT> return _PolyVoxCore.BaseVolumeuint16_getShortestSideLength(self) <NEW_LINE> <DEDENT> def getDiagonalLength(self) -> "float": <NEW_LINE> <INDENT> return _PolyVoxCore.BaseVolumeuint16_getDiagonalLength(self) <NEW_LINE> <DEDENT> def getVoxel(self, *args) -> "PolyVox::BaseVolume< unsigned short >::VoxelType": <NEW_LINE> <INDENT> return _PolyVoxCore.BaseVolumeuint16_getVoxel(self, *args) <NEW_LINE> <DEDENT> def getVoxelAt(self, *args) -> "PolyVox::BaseVolume< unsigned short >::VoxelType": <NEW_LINE> <INDENT> return _PolyVoxCore.BaseVolumeuint16_getVoxelAt(self, *args) <NEW_LINE> <DEDENT> def getVoxelWithWrapping(self, *args) -> "PolyVox::BaseVolume< unsigned short >::VoxelType": <NEW_LINE> <INDENT> return _PolyVoxCore.BaseVolumeuint16_getVoxelWithWrapping(self, *args) <NEW_LINE> <DEDENT> def setBorderValue(self, tBorder: 'PolyVox::BaseVolume< unsigned short >::VoxelType const &') -> "void": <NEW_LINE> <INDENT> return _PolyVoxCore.BaseVolumeuint16_setBorderValue(self, tBorder) <NEW_LINE> <DEDENT> def setVoxelAt(self, *args) -> "bool": <NEW_LINE> <INDENT> return _PolyVoxCore.BaseVolumeuint16_setVoxelAt(self, *args) <NEW_LINE> <DEDENT> def calculateSizeInBytes(self) -> "uint32_t": <NEW_LINE> <INDENT> return _PolyVoxCore.BaseVolumeuint16_calculateSizeInBytes(self)
Proxy of C++ PolyVox::BaseVolume<(uint16_t)> class.
62598fb6a17c0f6771d5c336
class TestMetricStatus(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 testMetricStatus(self): <NEW_LINE> <INDENT> pass
MetricStatus unit test stubs
62598fb663d6d428bbee28ae
class lineStyle(): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def set(lineWidth=1.0, lineColor=color.defined('black'), fillColor=None, lineJoin='round', lineCap='round', markerStart=None, markerMid=None, markerEnd=None, strokeDashArray=None): <NEW_LINE> <INDENT> if fillColor is None: <NEW_LINE> <INDENT> fillColor = 'none' <NEW_LINE> opacityFill = '1.0' <NEW_LINE> <DEDENT> if lineColor is None: <NEW_LINE> <INDENT> lineColor = 'none' <NEW_LINE> opacityStroke = '1.0' <NEW_LINE> <DEDENT> if fillColor.startswith('#'): <NEW_LINE> <INDENT> [fillColor,alphaFill] = color.splitColorAlpha(fillColor) <NEW_LINE> opacityFill = str(int(alphaFill, 16)/255.0) <NEW_LINE> <DEDENT> if lineColor.startswith('#'): <NEW_LINE> <INDENT> [lineColor, alphaLine] = color.splitColorAlpha(lineColor) <NEW_LINE> opacityStroke = str(int(alphaLine, 16)/255.0) <NEW_LINE> <DEDENT> if not strokeDashArray: <NEW_LINE> <INDENT> strokeDashArray = 'none' <NEW_LINE> <DEDENT> lineStyle = {'stroke': lineColor, 'stroke-width': str(lineWidth), 'stroke-dasharray': strokeDashArray, 'fill': fillColor,'fill-opacity':opacityFill,'stroke-opacity':opacityStroke} <NEW_LINE> lineStyle['stroke-linecap'] = lineCap <NEW_LINE> lineStyle['stroke-linejoin'] = lineJoin <NEW_LINE> if markerStart: <NEW_LINE> <INDENT> lineStyle['marker-start'] = 'url(#' + markerStart + ')' <NEW_LINE> <DEDENT> if markerMid: <NEW_LINE> <INDENT> lineStyle['marker-mid'] = 'url(#' + markerMid + ')' <NEW_LINE> <DEDENT> if markerEnd: <NEW_LINE> <INDENT> lineStyle['marker-end'] = 'url(#' + markerEnd + ')' <NEW_LINE> <DEDENT> return lineStyle <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def createDashedLinePattern(dashLength=5.0,gapLength=10.0): <NEW_LINE> <INDENT> return '%f,%f' % (dashLength,gapLength) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def setSimpleBlack(lineWidth=1.0): <NEW_LINE> <INDENT> return lineStyle.set(lineWidth)
Class to manipulate line styles. This class is used to define line styles. It is capable of setting stroke and filling colors, line width, linejoin and linecap, markers (start, mid, and end) and stroke dash array The base method of this class is :meth:`lineStyle.set` that can create custom line types. .. note:: This class contains only static methods so that your plugin class don't have to inherit it.
62598fb667a9b606de5460d0
class Element(object): <NEW_LINE> <INDENT> def __init__(self,name,abbrv=None): <NEW_LINE> <INDENT> self.name=name <NEW_LINE> if abbrv==None: <NEW_LINE> <INDENT> self.abbrv=name[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.abbrv=abbrv <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.abbrv <NEW_LINE> <DEDENT> def description(self): <NEW_LINE> <INDENT> return "<{}>".format(self.name) <NEW_LINE> <DEDENT> def meet(self,hero): <NEW_LINE> <INDENT> raise NotImplementedError("Not implemented yet")
Élement de base pour la construction du roquelike
62598fb692d797404e388be3
class APIValueError(APIError): <NEW_LINE> <INDENT> def __init__(self, field, message=''): <NEW_LINE> <INDENT> super(APIValueError, self).__init__('value:invalid', field, message)
Indicate the input value has error or invalid. Hte data specifies the error field of input form.
62598fb63317a56b869be5cd
class Project(): <NEW_LINE> <INDENT> def __init__(self, project_dict): <NEW_LINE> <INDENT> self.pid = project_dict['id'] <NEW_LINE> self.blurb = project_dict['blurb'].lower() <NEW_LINE> self.deadline = project_dict['deadline'] <NEW_LINE> self.category_id = project_dict['category']['id'] <NEW_LINE> self.category_desc = re.sub('/.*', '', project_dict['category']['slug']) <NEW_LINE> self.reward_backer_tup = project_dict['reward_backer_tup'] <NEW_LINE> self.text = project_dict['full_description'].lower() + " " + project_dict['risk'].lower() <NEW_LINE> self.tokens = np.array(wordpunct_tokenize(self.text)) <NEW_LINE> self.name = project_dict['name'] <NEW_LINE> self.url = project_dict['url'] <NEW_LINE> self.launched_at = project_dict['launched_at'] <NEW_LINE> self.pledged = project_dict['pledged'] <NEW_LINE> self.title = project_dict['title'] <NEW_LINE> self.no_dollars_raised = project_dict['no_dollars_raised'] <NEW_LINE> self.currency = project_dict['currency'] <NEW_LINE> self.no_backers = project_dict['no_backers'] <NEW_LINE> self.state = project_dict['state'] <NEW_LINE> self.deadline = project_dict['deadline'] <NEW_LINE> self.location = project_dict['location'] <NEW_LINE> self.backers_count = project_dict['backers_count'] <NEW_LINE> self.creator_url = project_dict['creator_url'] <NEW_LINE> self.backers_count = project_dict['backers_count'] <NEW_LINE> self.spotlight = project_dict['spotlight'] <NEW_LINE> self.goal = project_dict['goal'] <NEW_LINE> self.author = project_dict['author'] <NEW_LINE> <DEDENT> def pre_process(self, list_text): <NEW_LINE> <INDENT> sentence = "" <NEW_LINE> for sent in list_text: <NEW_LINE> <INDENT> sentence += " " + sent.lower() <NEW_LINE> <DEDENT> return sentence <NEW_LINE> <DEDENT> def tf(self, wordlist): <NEW_LINE> <INDENT> count = np.zeros(len(wordlist)) <NEW_LINE> if len(self.tokens) > 0: <NEW_LINE> <INDENT> for wid, word in np.ndenumerate(wordlist): <NEW_LINE> <INDENT> count[wid] = (self.tokens == word).sum() <NEW_LINE> <DEDENT> <DEDENT> return count <NEW_LINE> <DEDENT> def word_exists(self, wordlist): <NEW_LINE> <INDENT> is_word = np.zeros(len(wordlist)) <NEW_LINE> for wid, word in np.ndenumerate(wordlist): <NEW_LINE> <INDENT> if word in self.tokens: <NEW_LINE> <INDENT> is_word[wid] = 1 <NEW_LINE> <DEDENT> <DEDENT> return is_word <NEW_LINE> <DEDENT> def token_clean(self,length): <NEW_LINE> <INDENT> self.tokens = np.array([t for t in self.tokens if (t.isalpha() and len(t) > length)]) <NEW_LINE> <DEDENT> def stopword_remove(self, stopwords): <NEW_LINE> <INDENT> self.tokens = np.array([t for t in self.tokens if t not in stopwords]) <NEW_LINE> <DEDENT> def stem(self): <NEW_LINE> <INDENT> self.tokens = np.array([PorterStemmer().stem(t) for t in self.tokens])
The Doc class rpresents a class of individula documents
62598fb667a9b606de5460d1
@dataclass <NEW_LINE> class PerceiverDecoderOutput(ModelOutput): <NEW_LINE> <INDENT> logits: torch.FloatTensor = None <NEW_LINE> cross_attentions: Optional[Tuple[torch.FloatTensor]] = None
Base class for Perceiver decoder outputs, with potential cross-attentions. Args: logits (`torch.FloatTensor` of shape `(batch_size, num_labels)`): Output of the basic decoder. cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads.
62598fb62c8b7c6e89bd38c5
class LandingPageViewServiceGrpcTransport(object): <NEW_LINE> <INDENT> _OAUTH_SCOPES = () <NEW_LINE> def __init__(self, channel=None, credentials=None, address='googleads.googleapis.com:443'): <NEW_LINE> <INDENT> if channel is not None and credentials is not None: <NEW_LINE> <INDENT> raise ValueError( 'The `channel` and `credentials` arguments are mutually ' 'exclusive.', ) <NEW_LINE> <DEDENT> if channel is None: <NEW_LINE> <INDENT> channel = self.create_channel( address=address, credentials=credentials, ) <NEW_LINE> <DEDENT> self._channel = channel <NEW_LINE> self._stubs = { 'landing_page_view_service_stub': landing_page_view_service_pb2_grpc.LandingPageViewServiceStub(channel), } <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def create_channel( cls, address='googleads.googleapis.com:443', credentials=None, **kwargs): <NEW_LINE> <INDENT> return google.api_core.grpc_helpers.create_channel( address, credentials=credentials, scopes=cls._OAUTH_SCOPES, **kwargs ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def channel(self): <NEW_LINE> <INDENT> return self._channel <NEW_LINE> <DEDENT> @property <NEW_LINE> def get_landing_page_view(self): <NEW_LINE> <INDENT> return self._stubs['landing_page_view_service_stub'].GetLandingPageView
gRPC transport class providing stubs for google.ads.googleads.v1.services LandingPageViewService API. The transport provides access to the raw gRPC stubs, which can be used to take advantage of advanced features of gRPC.
62598fb6167d2b6e312b7074
class STALTAFilterF(InPlaceFilterF): <NEW_LINE> <INDENT> __swig_setmethods__ = {} <NEW_LINE> for _s in [InPlaceFilterF]: __swig_setmethods__.update(getattr(_s,'__swig_setmethods__',{})) <NEW_LINE> __setattr__ = lambda self, name, value: _swig_setattr(self, STALTAFilterF, name, value) <NEW_LINE> __swig_getmethods__ = {} <NEW_LINE> for _s in [InPlaceFilterF]: __swig_getmethods__.update(getattr(_s,'__swig_getmethods__',{})) <NEW_LINE> __getattr__ = lambda self, name: _swig_getattr(self, STALTAFilterF, name) <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> def __init__(self, lenSTA=2, lenLTA=50, fsamp=1.): <NEW_LINE> <INDENT> this = _Math.new_STALTAFilterF(lenSTA, lenLTA, fsamp) <NEW_LINE> try: self.this.append(this) <NEW_LINE> except: self.this = this <NEW_LINE> <DEDENT> def setSaveIntermediate(self, *args): <NEW_LINE> <INDENT> return _Math.STALTAFilterF_setSaveIntermediate(self, *args) <NEW_LINE> <DEDENT> def apply(self, *args): <NEW_LINE> <INDENT> return _Math.STALTAFilterF_apply(self, *args) <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> return _Math.STALTAFilterF_reset(self) <NEW_LINE> <DEDENT> def changed(self): <NEW_LINE> <INDENT> return _Math.STALTAFilterF_changed(self) <NEW_LINE> <DEDENT> def setSamplingFrequency(self, *args): <NEW_LINE> <INDENT> return _Math.STALTAFilterF_setSamplingFrequency(self, *args) <NEW_LINE> <DEDENT> def setParameters(self, *args): <NEW_LINE> <INDENT> return _Math.STALTAFilterF_setParameters(self, *args) <NEW_LINE> <DEDENT> def clone(self): <NEW_LINE> <INDENT> return _Math.STALTAFilterF_clone(self) <NEW_LINE> <DEDENT> def getSTA(self): <NEW_LINE> <INDENT> return _Math.STALTAFilterF_getSTA(self) <NEW_LINE> <DEDENT> def getLTA(self): <NEW_LINE> <INDENT> return _Math.STALTAFilterF_getLTA(self) <NEW_LINE> <DEDENT> __swig_destroy__ = _Math.delete_STALTAFilterF <NEW_LINE> __del__ = lambda self : None;
Proxy of C++ Seiscomp::Math::Filtering::STALTA<(float)> class
62598fb64428ac0f6e658623
class ContactSummary(BrowserView): <NEW_LINE> <INDENT> def __call__(self): <NEW_LINE> <INDENT> self.request.response.setHeader('X-Theme-Disabled', 'True') <NEW_LINE> return super(ContactSummary, self).__call__() <NEW_LINE> <DEDENT> def get_review_state(self): <NEW_LINE> <INDENT> return api.content.get_state(obj=self.context, default='') <NEW_LINE> <DEDENT> def safe_html(self, text): <NEW_LINE> <INDENT> return safe_html(text) <NEW_LINE> <DEDENT> @property <NEW_LINE> def img_tag(self): <NEW_LINE> <INDENT> return portrait_img_tag(self.context)
Contactsummary view
62598fb6091ae35668704d21
class ResPartnerBank(models.Model): <NEW_LINE> <INDENT> _inherit = 'res.partner.bank' <NEW_LINE> codigo_da_empresa = fields.Char( u'Código da empresa', size=20, help=u"Será informado pelo banco depois do cadastro do beneficiário " u"na agência")
Adiciona campos necessários para o cadastramentos de contas bancárias no Brasil.
62598fb6a8370b77170f04df
class ISCSITestCase(DriverTestCase): <NEW_LINE> <INDENT> driver_name = "cinder.volume.driver.ISCSIDriver" <NEW_LINE> def _attach_volume(self): <NEW_LINE> <INDENT> volume_id_list = [] <NEW_LINE> for index in xrange(3): <NEW_LINE> <INDENT> vol = {} <NEW_LINE> vol['size'] = 0 <NEW_LINE> vol_ref = db.volume_create(self.context, vol) <NEW_LINE> self.volume.create_volume(self.context, vol_ref['id']) <NEW_LINE> vol_ref = db.volume_get(self.context, vol_ref['id']) <NEW_LINE> mountpoint = "/dev/sd" + chr((ord('b') + index)) <NEW_LINE> instance_uuid = '12345678-1234-5678-1234-567812345678' <NEW_LINE> db.volume_attached(self.context, vol_ref['id'], instance_uuid, mountpoint) <NEW_LINE> volume_id_list.append(vol_ref['id']) <NEW_LINE> <DEDENT> return volume_id_list <NEW_LINE> <DEDENT> def test_check_for_export_with_no_volume(self): <NEW_LINE> <INDENT> self.stream.truncate(0) <NEW_LINE> instance_uuid = '12345678-1234-5678-1234-567812345678' <NEW_LINE> self.volume.check_for_export(self.context, instance_uuid) <NEW_LINE> self.assertEqual(self.stream.getvalue(), '') <NEW_LINE> <DEDENT> def test_check_for_export_with_all_volume_exported(self): <NEW_LINE> <INDENT> volume_id_list = self._attach_volume() <NEW_LINE> self.mox.StubOutWithMock(self.volume.driver.tgtadm, 'show_target') <NEW_LINE> for i in volume_id_list: <NEW_LINE> <INDENT> tid = db.volume_get_iscsi_target_num(self.context, i) <NEW_LINE> self.volume.driver.tgtadm.show_target(tid) <NEW_LINE> <DEDENT> self.stream.truncate(0) <NEW_LINE> self.mox.ReplayAll() <NEW_LINE> instance_uuid = '12345678-1234-5678-1234-567812345678' <NEW_LINE> self.volume.check_for_export(self.context, instance_uuid) <NEW_LINE> self.assertEqual(self.stream.getvalue(), '') <NEW_LINE> self.mox.UnsetStubs() <NEW_LINE> self._detach_volume(volume_id_list) <NEW_LINE> <DEDENT> def test_check_for_export_with_some_volume_missing(self): <NEW_LINE> <INDENT> volume_id_list = self._attach_volume() <NEW_LINE> instance_uuid = '12345678-1234-5678-1234-567812345678' <NEW_LINE> tid = db.volume_get_iscsi_target_num(self.context, volume_id_list[0]) <NEW_LINE> self.mox.StubOutWithMock(self.volume.driver.tgtadm, 'show_target') <NEW_LINE> self.volume.driver.tgtadm.show_target(tid).AndRaise( exception.ProcessExecutionError()) <NEW_LINE> self.mox.ReplayAll() <NEW_LINE> self.assertRaises(exception.ProcessExecutionError, self.volume.check_for_export, self.context, instance_uuid) <NEW_LINE> msg = _("Cannot confirm exported volume id:%s.") % volume_id_list[0] <NEW_LINE> self.assertTrue(0 <= self.stream.getvalue().find(msg)) <NEW_LINE> self.mox.UnsetStubs() <NEW_LINE> self._detach_volume(volume_id_list)
Test Case for ISCSIDriver
62598fb6d58c6744b42dc35b
class SitoFileToDir(BaseModel): <NEW_LINE> <INDENT> input_uri: UriT <NEW_LINE> output_dir: Optional[Union[DirectoryPath, str]] <NEW_LINE> options: OptionsT
Single file in, directory of files out.
62598fb630bbd722464699fa
class target(parser.target): <NEW_LINE> <INDENT> def __init__(self, sString): <NEW_LINE> <INDENT> parser.target.__init__(self, sString)
unique_id = concurrent_simple_signal_assignment : target
62598fb62ae34c7f260ab1de
class LanguageResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'documents': {'required': True}, 'errors': {'required': True}, 'model_version': {'required': True}, } <NEW_LINE> _attribute_map = { 'documents': {'key': 'documents', 'type': '[DocumentLanguage]'}, 'errors': {'key': 'errors', 'type': '[DocumentError]'}, 'statistics': {'key': 'statistics', 'type': 'RequestStatistics'}, 'model_version': {'key': 'modelVersion', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(LanguageResult, self).__init__(**kwargs) <NEW_LINE> self.documents = kwargs['documents'] <NEW_LINE> self.errors = kwargs['errors'] <NEW_LINE> self.statistics = kwargs.get('statistics', None) <NEW_LINE> self.model_version = kwargs['model_version']
LanguageResult. All required parameters must be populated in order to send to Azure. :ivar documents: Required. Response by document. :vartype documents: list[~azure.ai.textanalytics.v3_0.models.DocumentLanguage] :ivar errors: Required. Errors by document id. :vartype errors: list[~azure.ai.textanalytics.v3_0.models.DocumentError] :ivar statistics: if showStats=true was specified in the request this field will contain information about the request payload. :vartype statistics: ~azure.ai.textanalytics.v3_0.models.RequestStatistics :ivar model_version: Required. This field indicates which model is used for scoring. :vartype model_version: str
62598fb6e5267d203ee6ba01
class DisplayInterface(metaclass=abc.ABCMeta): <NEW_LINE> <INDENT> @abc.abstractmethod <NEW_LINE> def set_brightness(self, value): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def set_day(self, month, day, rgb): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def show(self): <NEW_LINE> <INDENT> pass
Abstract interface for a display of the calendar
62598fb65fc7496912d482fc
class TWriter(TWorker): <NEW_LINE> <INDENT> stashed = pyqtSignal(TStashResponse) <NEW_LINE> def __init__( self, request: TStashRequest, path: Path = None, parent: QObject = None ): <NEW_LINE> <INDENT> super().__init__(path, parent) <NEW_LINE> self.request = request
Provides the base class for all different database writers
62598fb663d6d428bbee28b0
class TelnetConsole(Adapter): <NEW_LINE> <INDENT> def __init__(self, device=None, auth_token=None): <NEW_LINE> <INDENT> self.logger = logging.getLogger(self.__class__.__name__) <NEW_LINE> if device is None: <NEW_LINE> <INDENT> from droidbot.device import Device <NEW_LINE> device = Device() <NEW_LINE> <DEDENT> self.device = device <NEW_LINE> self.auth_token = auth_token <NEW_LINE> self.console = None <NEW_LINE> self.__lock__ = threading.Lock() <NEW_LINE> <DEDENT> def connect(self): <NEW_LINE> <INDENT> if self.device.serial and self.device.serial.startswith("emulator-"): <NEW_LINE> <INDENT> host = "localhost" <NEW_LINE> port = int(self.device.serial[9:]) <NEW_LINE> from telnetlib import Telnet <NEW_LINE> self.console = Telnet(host, port) <NEW_LINE> if self.auth_token is not None: <NEW_LINE> <INDENT> self.run_cmd("auth %s" % self.auth_token) <NEW_LINE> <DEDENT> if self.check_connectivity(): <NEW_LINE> <INDENT> self.logger.debug("telnet successfully initiated, the port is %d" % port) <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> raise TelnetException() <NEW_LINE> <DEDENT> def run_cmd(self, args): <NEW_LINE> <INDENT> if self.console is None: <NEW_LINE> <INDENT> self.logger.warning("telnet is not connected!") <NEW_LINE> return None <NEW_LINE> <DEDENT> if isinstance(args, list): <NEW_LINE> <INDENT> cmd_line = " ".join(args) <NEW_LINE> <DEDENT> elif isinstance(args, str): <NEW_LINE> <INDENT> cmd_line = args <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.logger.warning("unsupported command format:" + args) <NEW_LINE> return None <NEW_LINE> <DEDENT> self.logger.debug('command:') <NEW_LINE> self.logger.debug(cmd_line) <NEW_LINE> cmd_line += '\n' <NEW_LINE> self.__lock__.acquire() <NEW_LINE> self.console.write(cmd_line) <NEW_LINE> r = self.console.read_until('OK', 5) <NEW_LINE> self.console.read_until('NEVER MATCH', 1) <NEW_LINE> self.__lock__.release() <NEW_LINE> self.logger.debug('return:') <NEW_LINE> self.logger.debug(r) <NEW_LINE> return r <NEW_LINE> <DEDENT> def check_connectivity(self): <NEW_LINE> <INDENT> if self.console is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.run_cmd("help") <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> def disconnect(self): <NEW_LINE> <INDENT> if self.console is not None: <NEW_LINE> <INDENT> self.console.close() <NEW_LINE> <DEDENT> print("[CONNECTION] %s is disconnected" % self.__class__.__name__)
interface of telnet console, see: http://developer.android.com/tools/devices/emulator.html
62598fb656ac1b37e63022ed
class Config: <NEW_LINE> <INDENT> NEWS_API_BASE_URL ='https://newsapi.org/v2/sources?category&apiKey={}' <NEW_LINE> NEWS_API_ARTI_URL ='https://newsapi.org/v2/everything?sources={}&apiKey={}' <NEW_LINE> NEWS_API_KEY = os.environ.get('NEWS_API_KEY') <NEW_LINE> SECRET_KEY = os.environ.get('SECRET_KEY')
General configuration parent class
62598fb6f548e778e596b6a7
class Entmax15Function(Function): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def forward(ctx, input, dim=-1): <NEW_LINE> <INDENT> ctx.dim = dim <NEW_LINE> max_val, _ = input.max(dim=dim, keepdim=True) <NEW_LINE> input = input - max_val <NEW_LINE> input = input / 2 <NEW_LINE> tau_star, _ = Entmax15Function._threshold_and_support(input, dim) <NEW_LINE> output = torch.clamp(input - tau_star, min=0) ** 2 <NEW_LINE> ctx.save_for_backward(output) <NEW_LINE> return output <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def backward(ctx, grad_output): <NEW_LINE> <INDENT> (Y,) = ctx.saved_tensors <NEW_LINE> gppr = Y.sqrt() <NEW_LINE> dX = grad_output * gppr <NEW_LINE> q = dX.sum(ctx.dim) / gppr.sum(ctx.dim) <NEW_LINE> q = q.unsqueeze(ctx.dim) <NEW_LINE> dX -= q * gppr <NEW_LINE> return dX, None <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _threshold_and_support(input, dim=-1): <NEW_LINE> <INDENT> Xsrt, _ = torch.sort(input, descending=True, dim=dim) <NEW_LINE> rho = _make_ix_like(input, dim) <NEW_LINE> mean = Xsrt.cumsum(dim) / rho <NEW_LINE> mean_sq = (Xsrt**2).cumsum(dim) / rho <NEW_LINE> ss = rho * (mean_sq - mean**2) <NEW_LINE> delta = (1 - ss) / rho <NEW_LINE> delta_nz = torch.clamp(delta, 0) <NEW_LINE> tau = mean - torch.sqrt(delta_nz) <NEW_LINE> support_size = (tau <= Xsrt).sum(dim).unsqueeze(dim) <NEW_LINE> tau_star = tau.gather(dim, support_size - 1) <NEW_LINE> return tau_star, support_size
An implementation of exact Entmax with alpha=1.5 (B. Peters, V. Niculae, A. Martins). See :cite:`https://arxiv.org/abs/1905.05702 for detailed description. Source: https://github.com/deep-spin/entmax
62598fb6377c676e912f6def
class PurchaseViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> serializer_class = serializers.HistorySerializer <NEW_LINE> queryset = Purchase.objects.all()
Purchase viewset of the shop.
62598fb6fff4ab517ebcd8ea
class ScoreBoard: <NEW_LINE> <INDENT> def __init__(self, window): <NEW_LINE> <INDENT> self.window = window <NEW_LINE> self.current_score = 0 <NEW_LINE> self.highest_score = self.read_highest_score() <NEW_LINE> self.current_level = 1 <NEW_LINE> self.font_36 = pygame.font.Font("fonts/wawa.ttf", constants.FONT_SIZE_36) <NEW_LINE> <DEDENT> def draw_current_score(self): <NEW_LINE> <INDENT> current_score_text = "当前得分:{}".format(self.current_score) <NEW_LINE> current_score_surface = self.font_36.render(current_score_text, True, constants.WHITE_COLOR) <NEW_LINE> self.current_score_rect = current_score_surface.get_rect() <NEW_LINE> self.current_score_rect.left = constants.MARGIN <NEW_LINE> self.current_score_rect.top = constants.MARGIN <NEW_LINE> self.window.blit(current_score_surface, self.current_score_rect) <NEW_LINE> <DEDENT> def draw_highest_score(self): <NEW_LINE> <INDENT> highest_score_text = "最高得分:{}".format(self.highest_score) <NEW_LINE> highest_score_surface = self.font_36.render(highest_score_text, True, constants.WHITE_COLOR) <NEW_LINE> self.highest_score_rect = highest_score_surface.get_rect() <NEW_LINE> self.highest_score_rect.left = constants.MARGIN <NEW_LINE> self.highest_score_rect.top = self.current_score_rect.bottom + constants.MARGIN <NEW_LINE> self.window.blit(highest_score_surface, self.highest_score_rect) <NEW_LINE> <DEDENT> def draw_current_level(self): <NEW_LINE> <INDENT> current_level_text = "当前关数:{}".format(self.current_level) <NEW_LINE> current_level_surface = self.font_36.render(current_level_text, True, constants.WHITE_COLOR) <NEW_LINE> current_level_rect = current_level_surface.get_rect() <NEW_LINE> current_level_rect.left = constants.MARGIN <NEW_LINE> current_level_rect.top = self.highest_score_rect.bottom + constants.MARGIN <NEW_LINE> self.window.blit(current_level_surface, current_level_rect) <NEW_LINE> <DEDENT> def read_highest_score(self): <NEW_LINE> <INDENT> with open('txts/highest_score.txt') as file: <NEW_LINE> <INDENT> return int(file.read()) <NEW_LINE> <DEDENT> <DEDENT> def save_current_score(self): <NEW_LINE> <INDENT> with open('txts/highest_score.txt', 'w') as file: <NEW_LINE> <INDENT> file.write(str(self.current_score)) <NEW_LINE> <DEDENT> <DEDENT> def update_current_level(self): <NEW_LINE> <INDENT> if self.current_score > constants.LEVEL1_SCORE_MAX and self.current_level == 1: <NEW_LINE> <INDENT> self.current_level = 2 <NEW_LINE> <DEDENT> elif self.current_score > constants.LEVEL2_SCORE_MAX and self.current_level == 2: <NEW_LINE> <INDENT> self.current_level = 3 <NEW_LINE> <DEDENT> elif self.current_score > constants.LEVEL3_SCORE_MAX and self.current_level == 3: <NEW_LINE> <INDENT> self.current_level = 4 <NEW_LINE> <DEDENT> elif self.current_score > constants.LEVEL4_SCORE_MAX and self.current_level == 4: <NEW_LINE> <INDENT> self.current_level = 5
得分板类
62598fb63539df3088ecc3af
@injected <NEW_LINE> class GatewayErrorHandler(HandlerProcessorProceed): <NEW_LINE> <INDENT> nameStatus = 'status' <NEW_LINE> nameAllow = 'allow' <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> assert isinstance(self.nameStatus, str), 'Invalid status name %s' % self.nameStatus <NEW_LINE> assert isinstance(self.nameAllow, str), 'Invalid allow name %s' % self.nameAllow <NEW_LINE> super().__init__() <NEW_LINE> <DEDENT> def process(self, request:Request, response:Response, **keyargs): <NEW_LINE> <INDENT> assert isinstance(request, Request), 'Invalid request %s' % request <NEW_LINE> assert isinstance(response, Response), 'Invalid response %s' % response <NEW_LINE> if response.isSuccess is not False: return <NEW_LINE> assert isinstance(response.status, int), 'Invalid response status %s' % response.status <NEW_LINE> if request.parameters is None: request.parameters = [] <NEW_LINE> request.parameters.insert(0, (self.nameStatus, response.status)) <NEW_LINE> if response.status == METHOD_NOT_AVAILABLE.status and response.allows is not None: <NEW_LINE> <INDENT> for allow in response.allows: request.parameters.append((self.nameAllow, allow))
Implementation for a handler that populates the gateway error parameters.
62598fb6be7bc26dc9251edd
class ReviewPage(Page): <NEW_LINE> <INDENT> search_fields = Page.search_fields + [ index.SearchField('introduction'), index.SearchField('body'), ] <NEW_LINE> image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+', help_text='Image to be used where this review is listed' ) <NEW_LINE> rating = models.IntegerField("Album rating", validators=[ MinValueValidator(0), MaxValueValidator(5)], help_text="Your rating needs to be between 0 - 5") <NEW_LINE> introduction = models.TextField( blank=True, help_text="Text to show at the review page") <NEW_LINE> listing_introduction = models.CharField( max_length=250, blank=True, help_text="Text shown on review, and other, listing pages, if empty will" " show 'Introduction' field content" ) <NEW_LINE> body = StreamField( SimplifiedBlock(), blank=True, verbose_name="Review body") <NEW_LINE> content_panels = Page.content_panels + [ InlinePanel('review_album_relationship', label="Album", min_num=1, max_num=1), InlinePanel( 'related_pages', label="Related pages", help_text="Other pages from across the site that relate to this " "review") ] <NEW_LINE> review_panels = [ FieldPanel('rating'), MultiFieldPanel( [ FieldPanel('introduction'), FieldPanel('listing_introduction'), ], heading="Introduction", classname="collapsible" ), StreamFieldPanel('body'), InlinePanel('review_author_relationship', label="Author", min_num=1), ] <NEW_LINE> edit_handler = TabbedInterface([ ObjectList(content_panels, heading="Album details", classname="content"), ObjectList(review_panels, heading="Review"), ObjectList(Page.promote_panels, heading="Promote"), ObjectList(Page.settings_panels, heading="Settings", classname="settings"), ]) <NEW_LINE> subpage_types = [] <NEW_LINE> parent_page_types = [ 'ReviewIndexPage' ] <NEW_LINE> @property <NEW_LINE> def albums(self): <NEW_LINE> <INDENT> albums = [ n.album for n in self.review_album_relationship.all() ] <NEW_LINE> return albums <NEW_LINE> <DEDENT> @property <NEW_LINE> def authors(self): <NEW_LINE> <INDENT> authors = [ n.author for n in self.review_author_relationship.all() ] <NEW_LINE> return authors
This is a page for an album review
62598fb6baa26c4b54d4f3bc
class Cutadapt: <NEW_LINE> <INDENT> quality_cutoff = IntegerField( label="Reads quality cutoff", required=False, description="Trim low-quality bases from 3' end of each read before " "adapter removal. The use of this option will override the use " "of NextSeq/NovaSeq-specific trim option.", )
Cutadapt filtering.
62598fb666673b3332c304d2
class ProviderBillingSource(models.Model): <NEW_LINE> <INDENT> uuid = models.UUIDField(default=uuid4, editable=False, unique=True, null=False) <NEW_LINE> bucket = models.CharField(max_length=63, null=True) <NEW_LINE> data_source = JSONField(null=True, default=dict) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> constraints = [ CheckConstraint( check=~models.Q(models.Q(bucket=None) & models.Q(data_source={})), name='bucket_and_data_source_both_null' ), CheckConstraint( check=~models.Q(~models.Q(bucket=None) & ~models.Q(data_source={})), name='bucket_and_data_source_both_not_null' ), ]
A Koku Provider Billing Source. Used for accessing cost providers billing sourece like AWS Account S3.
62598fb64a966d76dd5eefdb
class EntityMeta(type): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def __prepare__(cls, name, bases): <NEW_LINE> <INDENT> return collections.OrderedDict() <NEW_LINE> <DEDENT> def __init__(cls, name, bases, attr_dict): <NEW_LINE> <INDENT> super().__init__(name, bases, attr_dict) <NEW_LINE> cls._field_names = [] <NEW_LINE> for key, attr in attr_dict.items(): <NEW_LINE> <INDENT> if isinstance(attr, Validated): <NEW_LINE> <INDENT> type_name = type(attr).__name__ <NEW_LINE> attr.storage_name = '_{}#{}'.format(type_name, key) <NEW_LINE> cls._field_names.append(key)
Metaclass for business entities with validated fields
62598fb62ae34c7f260ab1e0
class ArrayMixin: <NEW_LINE> <INDENT> def assertArraysEqual(self, a, b): <NEW_LINE> <INDENT> self.assertEquals(a.shape, b.shape) <NEW_LINE> self.assertEquals(a.dtype, b.dtype) <NEW_LINE> if (a != b).any(): <NEW_LINE> <INDENT> self.fail("a != b\na = %r\nb = %r" % (a, b))
Mixin for TestCase subclasses which make assertions about numpy arrays.
62598fb6aad79263cf42e8d7
class NotEnoughMoney(TException): <NEW_LINE> <INDENT> thrift_spec = ( None, (1, TType.I64, 'moneyAvailable', None, None, ), (2, TType.I64, 'moneyRequested', None, None, ), ) <NEW_LINE> def __init__(self, moneyAvailable=None, moneyRequested=None,): <NEW_LINE> <INDENT> self.moneyAvailable = moneyAvailable <NEW_LINE> self.moneyRequested = moneyRequested <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.I64: <NEW_LINE> <INDENT> self.moneyAvailable = iprot.readI64(); <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 2: <NEW_LINE> <INDENT> if ftype == TType.I64: <NEW_LINE> <INDENT> self.moneyRequested = iprot.readI64(); <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('NotEnoughMoney') <NEW_LINE> if self.moneyAvailable is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('moneyAvailable', TType.I64, 1) <NEW_LINE> oprot.writeI64(self.moneyAvailable) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.moneyRequested is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('moneyRequested', TType.I64, 2) <NEW_LINE> oprot.writeI64(self.moneyRequested) <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 __str__(self): <NEW_LINE> <INDENT> return repr(self) <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: - moneyAvailable - moneyRequested
62598fb6e5267d203ee6ba03
class VerificationError(Exception): <NEW_LINE> <INDENT> pass
Attestation verification errors
62598fb64c3428357761a3bf
class TestResults(object): <NEW_LINE> <INDENT> def __init__(self, steps=0, matches=0, mismatches=0, missing=0, exact_matches=0, strict_matches=0, content_matches=0, layout_matches=0, none_matches=0, status=None, ): <NEW_LINE> <INDENT> self.steps = steps <NEW_LINE> self.matches = matches <NEW_LINE> self.mismatches = mismatches <NEW_LINE> self.missing = missing <NEW_LINE> self.exact_matches = exact_matches <NEW_LINE> self.strict_matches = strict_matches <NEW_LINE> self.content_matches = content_matches <NEW_LINE> self.layout_matches = layout_matches <NEW_LINE> self.none_matches = none_matches <NEW_LINE> self._status = status <NEW_LINE> self.is_new = None <NEW_LINE> self.url = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def status(self): <NEW_LINE> <INDENT> return TestResultsStatus.get_status(self._status) <NEW_LINE> <DEDENT> @status.setter <NEW_LINE> def status(self, status_): <NEW_LINE> <INDENT> self._status = status_ <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_passed(self): <NEW_LINE> <INDENT> return (self.status is not None) and self.status.lower() == TestResultsStatus.Passed.lower() <NEW_LINE> <DEDENT> def _to_dict(self): <NEW_LINE> <INDENT> return dict(steps=self.steps, matches=self.matches, mismatches=self.mismatches, missing=self.missing, exact_matches=self.exact_matches, strict_matches=self.strict_matches, content_matches=self.content_matches, layout_matches=self.layout_matches, none_matches=self.none_matches, is_new=self.is_new, url=self.url, status=self.status) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> if self.is_new is not None: <NEW_LINE> <INDENT> is_new = "New test" if self.is_new else "Existing test" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> is_new = "" <NEW_LINE> <DEDENT> return "%s [ steps: %d, matches: %d, mismatches: %d, missing: %d ], URL: %s" % (is_new, self.steps, self.matches, self.mismatches, self.missing, self.url)
Eyes test results. # TODO: update regarding JAVA SDK
62598fb656ac1b37e63022ef
class MovingUnit(DoppelgangerUnit): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def get_data_format_members(cls, game_version): <NEW_LINE> <INDENT> data_format = [ (READ_GEN, None, None, IncludeMembers(cls=DoppelgangerUnit)), (READ_GEN, "move_graphics", StorageType.ID_MEMBER, "int16_t"), (READ_GEN, "run_graphics", StorageType.ID_MEMBER, "int16_t"), (READ_GEN, "turn_speed", StorageType.FLOAT_MEMBER, "float"), (SKIP, "old_size_class", StorageType.ID_MEMBER, "int8_t"), (READ_GEN, "trail_unit_id", StorageType.ID_MEMBER, "int16_t"), (READ_GEN, "trail_opsions", StorageType.ID_MEMBER, "uint8_t"), (READ_GEN, "trail_spacing", StorageType.FLOAT_MEMBER, "float"), (SKIP, "old_move_algorithm", StorageType.ID_MEMBER, "int8_t"), ] <NEW_LINE> if game_version[0].game_id not in ("ROR", "AOE1DE"): <NEW_LINE> <INDENT> data_format.extend([ (READ_GEN, "turn_radius", StorageType.FLOAT_MEMBER, "float"), (READ_GEN, "turn_radius_speed", StorageType.FLOAT_MEMBER, "float"), (READ_GEN, "max_yaw_per_sec_moving", StorageType.FLOAT_MEMBER, "float"), (READ_GEN, "stationary_yaw_revolution_time", StorageType.FLOAT_MEMBER, "float"), (READ_GEN, "max_yaw_per_sec_stationary", StorageType.FLOAT_MEMBER, "float"), ]) <NEW_LINE> if game_version[0].game_id == "AOE2DE": <NEW_LINE> <INDENT> data_format.extend([ (READ_GEN, "min_collision_size_multiplier", StorageType.FLOAT_MEMBER, "float"), ]) <NEW_LINE> <DEDENT> <DEDENT> return data_format
type_id >= 30 Moving master object
62598fb6fff4ab517ebcd8eb
class TextUtils: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def break_into_lines(text): <NEW_LINE> <INDENT> return text.split("\n") <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def filter_text(text): <NEW_LINE> <INDENT> text = text.replace('\n', '<br>') <NEW_LINE> control_chars = ''.join(map(unichr, range(0, 32) + range(127, 160))) <NEW_LINE> control_char_re = re.compile('[%s]' % re.escape(control_chars)) <NEW_LINE> return str(control_char_re.sub('', text)) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_pretty_text(text): <NEW_LINE> <INDENT> return str(pprint.pformat(text))
Utility class containing methods for manipulation of multi-line text.
62598fb6f548e778e596b6a9
class Pgl2A(object): <NEW_LINE> <INDENT> def __init__(self, d=2, m=np.zeros([3, 3]), special=False): <NEW_LINE> <INDENT> if np.array_equal(m.shape, [d + 1] * 2): <NEW_LINE> <INDENT> self.matrix = m <NEW_LINE> self.dim = d <NEW_LINE> self.special = special <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise IOError <NEW_LINE> <DEDENT> if special is True and not np.abs(np.trace(m)) < 1e-4: <NEW_LINE> <INDENT> raise IOError('input matrix is not in the special projective group') <NEW_LINE> <DEDENT> <DEDENT> def shape(self): <NEW_LINE> <INDENT> return self.matrix.shape <NEW_LINE> <DEDENT> shape = property(shape) <NEW_LINE> def centering(self, c): <NEW_LINE> <INDENT> h = self.matrix[:] <NEW_LINE> h_prime = np.zeros_like(self.matrix) <NEW_LINE> d = self.dim <NEW_LINE> if isinstance(c, list): <NEW_LINE> <INDENT> c = np.array(c) <NEW_LINE> <DEDENT> den = 1 - h[d, :-1].dot(c) <NEW_LINE> h_prime[:-1, :-1] = (h[:-1, :-1] + np.kron(c.reshape(1, 2), h[d, :-1].reshape(2, 1)))/den <NEW_LINE> h_prime[d, :-1] = (h[d, :-1])/den <NEW_LINE> h_prime[:-1, 2] = (-(h[:-1, :-1]).dot(c) - h[d, :-1].dot(c) * c + c)/den <NEW_LINE> h_prime[d, d] = 0 <NEW_LINE> self.matrix = h_prime <NEW_LINE> <DEDENT> def ode_solution(self, init_cond=np.array([0, 0, 1]), affine_coordinates=True): <NEW_LINE> <INDENT> s = linalg.expm(self.matrix).dot(init_cond) <NEW_LINE> if affine_coordinates: <NEW_LINE> <INDENT> return s[0:self.dim]/s[self.dim] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return s
Classes for projective real Lie algebra, general and special, of dimension d. Default value d=2. https://en.wikipedia.org/wiki/Projective_linear_group Real projective general/special linear Lie algebra of dimension d. Each element is a (d+1)x(d+1) real matrix defined up to a constant. Its exponential is given through the numerical approximation expm. If special trace must be zero.
62598fb656ac1b37e63022f0
class ServerError(RPCError): <NEW_LINE> <INDENT> code = 500 <NEW_LINE> message = 'INTERNAL' <NEW_LINE> def __init__(self, message): <NEW_LINE> <INDENT> super().__init__(message) <NEW_LINE> self.message = message
An internal server error occurred while a request was being processed for example, there was a disruption while accessing a database or file storage.
62598fb6283ffb24f3cf3992
class Filter(object): <NEW_LINE> <INDENT> def __init__(self, gains): <NEW_LINE> <INDENT> self._num_states = len(gains) <NEW_LINE> self._gains = gains <NEW_LINE> self.state = 0.0, (0.0,)*self._num_states <NEW_LINE> self.signal = None <NEW_LINE> <DEDENT> state = state_property("_time", "_state") <NEW_LINE> @state.setter <NEW_LINE> def state(self, t_x): <NEW_LINE> <INDENT> self._time, self._state = t_x <NEW_LINE> self._xndot = sum(-q*d for (q,d) in zip(self._state, self._gains)) <NEW_LINE> <DEDENT> def output(self): <NEW_LINE> <INDENT> return self._state + (self._xndot + self._gains[0]*self.signal(),) <NEW_LINE> <DEDENT> def __call__(self): <NEW_LINE> <INDENT> return self._state[1:] + (self._xndot + self._gains[0]*self.signal(),)
A linear filter of arbitrary order. It also provides derivative estimates for otherwise nondifferentiable inputs. The `output` function returns to the complete signal, including derivatives. The signal is drawn from another subsystem with the `signal` callback. Make sure to set this before using the filter.
62598fb666656f66f7d5a4f6
class Rectangle: <NEW_LINE> <INDENT> pass
Rectangle class with height and width attributes
62598fb6ec188e330fdf8995
class UnsupportedOperation(MLManageException): <NEW_LINE> <INDENT> pass
This exception class is for exceptions that arise from attempts to use the API in ways that are not yet defined.
62598fb69f288636728188c9
class TestTripApi(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.api = mbtaapi.apis.trip_api.TripApi() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_api_web_trip_controller_index(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_api_web_trip_controller_show(self): <NEW_LINE> <INDENT> pass
TripApi unit test stubs
62598fb623849d37ff8511b7
class Gene_Info(object): <NEW_LINE> <INDENT> def __init__(self, Start, End, Length, Id, Chromosome): <NEW_LINE> <INDENT> self.Start = Start <NEW_LINE> self.End = End <NEW_LINE> self.Length = Length <NEW_LINE> self.Id = Id <NEW_LINE> self.Chromosome = Chromosome
Class for showing some information about a given human gene
62598fb6796e427e5384e899
class GenericObject(object): <NEW_LINE> <INDENT> pass
Generic object into which we can stuff whichever attributes we want.
62598fb67c178a314d78d5a2
class UnknownUsageTypeUploadFreqError(Exception): <NEW_LINE> <INDENT> pass
Raised when UsageTypeUploadFreq contains a choice which is not handled in this module (see: `_get_max_expected_date` function).
62598fb65fdd1c0f98e5e094
class LifoMemoryQueue(FifoMemoryQueue): <NEW_LINE> <INDENT> def pop(self) -> Optional[Any]: <NEW_LINE> <INDENT> return self.q.pop() if self.q else None <NEW_LINE> <DEDENT> def peek(self) -> Optional[Any]: <NEW_LINE> <INDENT> return self.q[-1] if self.q else None
In-memory LIFO queue, API compliant with LifoDiskQueue.
62598fb6bf627c535bcb15a7
class WithTypeHints(object): <NEW_LINE> <INDENT> def __init__(self, *unused_args, **unused_kwargs): <NEW_LINE> <INDENT> self._type_hints = IOTypeHints() <NEW_LINE> <DEDENT> def _get_or_create_type_hints(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self._type_hints <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> self._type_hints = IOTypeHints() <NEW_LINE> return self._type_hints <NEW_LINE> <DEDENT> <DEDENT> def get_type_hints(self): <NEW_LINE> <INDENT> return (self._get_or_create_type_hints() .with_defaults(self.default_type_hints()) .with_defaults(get_type_hints(self.__class__))) <NEW_LINE> <DEDENT> def default_type_hints(self): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> def with_input_types(self, *arg_hints, **kwarg_hints): <NEW_LINE> <INDENT> self._get_or_create_type_hints().set_input_types(*arg_hints, **kwarg_hints) <NEW_LINE> return self <NEW_LINE> <DEDENT> def with_output_types(self, *arg_hints, **kwarg_hints): <NEW_LINE> <INDENT> self._get_or_create_type_hints().set_output_types(*arg_hints, **kwarg_hints) <NEW_LINE> return self
A mixin class that provides the ability to set and retrieve type hints.
62598fb68e7ae83300ee91a5
class PluginManager(object): <NEW_LINE> <INDENT> def __init__(self, *extra_packages): <NEW_LINE> <INDENT> def packages(): <NEW_LINE> <INDENT> for package_name in extra_packages: <NEW_LINE> <INDENT> yield sys.modules[package_name] <NEW_LINE> <DEDENT> cfg.CONF.import_opt('plugin_dirs', 'conveyor.conveyorheat.common.config') <NEW_LINE> yield plugin_loader.create_subpackage( cfg.CONF.plugin_dirs, 'conveyor.conveyorheat.engine') <NEW_LINE> <DEDENT> def modules(): <NEW_LINE> <INDENT> pkg_modules = six.moves.map(plugin_loader.load_modules, packages()) <NEW_LINE> return itertools.chain.from_iterable(pkg_modules) <NEW_LINE> <DEDENT> self.modules = list(modules()) <NEW_LINE> <DEDENT> def map_to_modules(self, function): <NEW_LINE> <INDENT> return six.moves.map(function, self.modules)
A class for managing plugin modules.
62598fb61b99ca400228f5b3
class UploadOptionsTests(SynchronousTestCase): <NEW_LINE> <INDENT> def test_must_be_release_version(self): <NEW_LINE> <INDENT> options = UploadOptions() <NEW_LINE> self.assertRaises( NotARelease, options.parseOptions, ['--flocker-version', '0.3.0+444.gf05215b']) <NEW_LINE> <DEDENT> def test_documentation_release_fails(self): <NEW_LINE> <INDENT> options = UploadOptions() <NEW_LINE> self.assertRaises( DocumentationRelease, options.parseOptions, ['--flocker-version', '0.3.0.post1'])
Tests for :class:`UploadOptions`.
62598fb65fc7496912d482fe
class Switch(Widget): <NEW_LINE> <INDENT> active = BooleanProperty(False) <NEW_LINE> touch_control = ObjectProperty(None, allownone=True) <NEW_LINE> touch_distance = NumericProperty(0) <NEW_LINE> active_norm_pos = NumericProperty(0) <NEW_LINE> def on_touch_down(self, touch): <NEW_LINE> <INDENT> if self.touch_control is not None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if not self.collide_point(*touch.pos): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> touch.grab(self) <NEW_LINE> self.touch_distance = 0 <NEW_LINE> self.touch_control = touch <NEW_LINE> return True <NEW_LINE> <DEDENT> def on_touch_move(self, touch): <NEW_LINE> <INDENT> if touch.grab_current is not self: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.touch_distance = touch.x - touch.ox <NEW_LINE> return True <NEW_LINE> <DEDENT> def on_touch_up(self, touch): <NEW_LINE> <INDENT> if touch.grab_current is not self: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> touch.ungrab(self) <NEW_LINE> if abs(touch.ox - touch.x) < 5: <NEW_LINE> <INDENT> self.active = not self.active <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.active = self.active_norm_pos > 0.5 <NEW_LINE> <DEDENT> Animation(active_norm_pos=int(self.active), t='out_quad', d=.2).start(self) <NEW_LINE> self.touch_control = None <NEW_LINE> return True
Switch class. See module documentation for more information.
62598fb6e5267d203ee6ba05
class TokenBlacklist(BaseMixin, db.Model): <NEW_LINE> <INDENT> __tablename__ = "tokens_blacklist" <NEW_LINE> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> token = db.Column(db.String(255), nullable=False) <NEW_LINE> blacklisted_on = db.Column( db.DateTime, default=datetime.datetime.now, nullable=False ) <NEW_LINE> def __init__(self, token): <NEW_LINE> <INDENT> self.token = token <NEW_LINE> self.blacklisted_on = datetime.datetime.now() <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<token :{}>".format(self.token)
For storing Blacklisted tokens on user logout
62598fb6a17c0f6771d5c33c
class CustomJSONWebTokenClient(JSONWebTokenClient): <NEW_LINE> <INDENT> def authenticate(self, user): <NEW_LINE> <INDENT> self._credentials = { jwt_settings.JWT_AUTH_HEADER_NAME: "{0} {1}".format( jwt_settings.JWT_AUTH_HEADER_PREFIX, get_token(user, userId=user.id) ), }
Test client with a custom authentication method.
62598fb67d847024c075c4c1
class ReGenerator(AbstractGenerator): <NEW_LINE> <INDENT> def __init__(self, pattern): <NEW_LINE> <INDENT> if not pattern: <NEW_LINE> <INDENT> raise ValueError("Pattern cannot be empty") <NEW_LINE> <DEDENT> self._pattern = pattern <NEW_LINE> self._parser = parser() <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "pattern: %s\n" % (self._pattern) <NEW_LINE> <DEDENT> __repr__ = __str__ <NEW_LINE> def igenerate(self): <NEW_LINE> <INDENT> for charset in Randomizer(self._parser.parseString(self._pattern)): <NEW_LINE> <INDENT> for c in charset: <NEW_LINE> <INDENT> yield c <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def generate(self): <NEW_LINE> <INDENT> return ''.join([c for c in self.igenerate()])
Regex-like Pattern Generator This generator uses regex-like patterns to generate random string which can be used as a random password or username Args: pattern (str): pattern used to generate string
62598fb6009cb60464d01629
class FactoryPattern(object): <NEW_LINE> <INDENT> def __init__(self, constructor, ignore_warnings=False): <NEW_LINE> <INDENT> self._constructor = constructor <NEW_LINE> self._constructor_args = inspect.getargspec(constructor.__init__).args[1:] <NEW_LINE> self._product = ClassPattern(constructor) <NEW_LINE> <DEDENT> def reflects_class(self, possible_class): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def create(self, universe, aliases, known_parameters): <NEW_LINE> <INDENT> return Factory(self._constructor, self._constructor_args, self._product, universe, known_parameters) <NEW_LINE> <DEDENT> def matches(self, requirements, aliases): <NEW_LINE> <INDENT> is_factory = requirements.type == 'factory' <NEW_LINE> has_parameters = self.has_parameters(requirements.parameters) <NEW_LINE> product_matches = (requirements.product is None) or (self._product.matches(requirements.product, aliases)) <NEW_LINE> return is_factory and has_parameters and product_matches <NEW_LINE> <DEDENT> def has_parameters(self, parameters): <NEW_LINE> <INDENT> return all([x in self._constructor_args for x in parameters]) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> result = str(self._constructor)+" factory(" <NEW_LINE> result += ', '.join(self._constructor_args) <NEW_LINE> result += ")" <NEW_LINE> return result
WRITEME
62598fb667a9b606de5460d6
class TruncateDataset(Dataset): <NEW_LINE> <INDENT> def __init__(self, dataset: Dataset, max_num: int = 100): <NEW_LINE> <INDENT> self.dataset = dataset <NEW_LINE> self.max_num = min(max_num, len(self.dataset)) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return self.max_num <NEW_LINE> <DEDENT> def __getitem__(self, item): <NEW_LINE> <INDENT> return self.dataset[item] <NEW_LINE> <DEDENT> def __getattr__(self, item): <NEW_LINE> <INDENT> return getattr(self.dataset, item)
Truncate dataset to certain num
62598fb64a966d76dd5eefde
class ToTensor(object): <NEW_LINE> <INDENT> def __call__(self, sample): <NEW_LINE> <INDENT> image, segment = sample['image'], sample['segment'] <NEW_LINE> image = image.transpose((2, 0, 1)) <NEW_LINE> return {'image': torch.from_numpy(image), 'segment': torch.from_numpy(segment)}
Convert ndarrays in sample to Tensors.
62598fb666656f66f7d5a4f8
class datemap: <NEW_LINE> <INDENT> def __init__(self, mapping): <NEW_LINE> <INDENT> self._mapping = {date: mapping[date] for date in sorted(mapping)} <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self._mapping) <NEW_LINE> <DEDENT> def __contains__(self, value): <NEW_LINE> <INDENT> return value in self._mapping <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return iter(self._mapping.values()) <NEW_LINE> <DEDENT> def __getitem__(self, value): <NEW_LINE> <INDENT> if isinstance(value, (datetime.date, datetime.datetime)): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self._mapping[value] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise KeyError(f"{value} not in datemap") <NEW_LINE> <DEDENT> <DEDENT> return [self[v] for v in value]
Read-only sorted dictionary mapping dates to values Example ------- .. code-block:: >>> import doubledate as dtwo >>> import datetime >>> holidays = [ ... datetime.date(2022, 1, 17), ... datetime.date(2022, 5, 30), ... datetime.date(2022, 6, 4), ... datetime.date(2022, 9, 5), ... datetime.date(2022, 11, 11), ... datetime.date(2022, 12, 24), ... datetime.date(2022, 12, 26) ... ] >>> mapping = dtwo.datemap({d:i for d, i in enumerate(holidays)}) <doubledate.utils.datemap at 0x7fd0fa4cfa60>
62598fb667a9b606de5460d7
class MajorityVoteClassifier(BaseEstimator, ClassifierMixin): <NEW_LINE> <INDENT> def __init__(self, classifiers, vote='classlabel', weights=None): <NEW_LINE> <INDENT> self.classifiers = classifiers <NEW_LINE> self.named_classifiers = {key: value for key, value in _name_estimators(classifiers)} <NEW_LINE> self.vote = vote <NEW_LINE> self.weights = weights <NEW_LINE> <DEDENT> def fit(self, X, y): <NEW_LINE> <INDENT> if self.vote not in ('probability', 'classlabel'): <NEW_LINE> <INDENT> raise ValueError("vote must be 'probability' or 'classlabel'" "; got (vote=%r)" % self.vote) <NEW_LINE> <DEDENT> if self.weights and len(self.weights) != len(self.classifiers): <NEW_LINE> <INDENT> raise ValueError('Number of classifiers and weights must be equal' '; got %d weights, %d classifiers' % (len(self.weights), len(self.classifiers))) <NEW_LINE> <DEDENT> self.lablenc_ = LabelEncoder() <NEW_LINE> self.lablenc_.fit(y) <NEW_LINE> self.classes_ = self.lablenc_.classes_ <NEW_LINE> self.classifiers_ = [] <NEW_LINE> for clf in self.classifiers: <NEW_LINE> <INDENT> fitted_clf = clone(clf).fit(X, self.lablenc_.transform(y)) <NEW_LINE> self.classifiers_.append(fitted_clf) <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> def predict(self, X): <NEW_LINE> <INDENT> if self.vote == 'probability': <NEW_LINE> <INDENT> maj_vote = np.argmax(self.predict_proba(X), axis=1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> predictions = np.asarray([clf.predict(X) for clf in self.classifiers_]).T <NEW_LINE> maj_vote = np.apply_along_axis( lambda x: np.argmax(np.bincount(x, weights=self.weights)), axis=1, arr=predictions) <NEW_LINE> <DEDENT> maj_vote = self.lablenc_.inverse_transform(maj_vote) <NEW_LINE> return maj_vote <NEW_LINE> <DEDENT> def predict_proba(self, X): <NEW_LINE> <INDENT> probas = [] <NEW_LINE> for clf in self.classifiers_: <NEW_LINE> <INDENT> if hasattr(clf, "predict_proba"): <NEW_LINE> <INDENT> array = np.array(clf.predict_proba(X)) <NEW_LINE> probas.append(array) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> array = np.array(clf.predict(X)[0]) <NEW_LINE> probas.append(array) <NEW_LINE> <DEDENT> <DEDENT> avg_proba = np.average(probas, axis=0, weights=self.weights) <NEW_LINE> return avg_proba <NEW_LINE> <DEDENT> def get_params(self, deep=True): <NEW_LINE> <INDENT> if not deep: <NEW_LINE> <INDENT> return super(MajorityVoteClassifier, self).get_params(deep=False) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> out = self.named_classifiers.copy() <NEW_LINE> for name, step in six.iteritems(self.named_classifiers): <NEW_LINE> <INDENT> for key, value in six.iteritems(step.get_params(deep=True)): <NEW_LINE> <INDENT> out['%s__%s' % (name, key)] = value <NEW_LINE> <DEDENT> <DEDENT> return out
A majority vote ensemble classifier Parameters ---------- classifiers : array-like, shape = [n_classifiers] Different classifiers for the ensemble vote : str, {'classlabel', 'probability'} (default='label') If 'classlabel' the prediction is based on the argmax of class labels. Else if 'probability', the argmax of the sum of probabilities is used to predict the class label (recommended for calibrated classifiers). weights : array-like, shape = [n_classifiers], optional (default=None) If a list of `int` or `float` values are provided, the classifiers are weighted by importance; Uses uniform weights if `weights=None`.
62598fb6442bda511e95c560
class ApiClient(AbstractApi): <NEW_LINE> <INDENT> def __init__(self, base_url=None): <NEW_LINE> <INDENT> base_url = base_url or os.environ.get('API_URL', 'http://localhost:5000/api') <NEW_LINE> super(ApiClient, self).__init__(base_url=base_url, auth_header_name=auth_header_name, auth_header_val=os.environ.get(auth_header_env)) <NEW_LINE> <DEDENT> def predict(self, pros='', cons=''): <NEW_LINE> <INDENT> payload = { 'pros': pros, 'cons': cons } <NEW_LINE> try: <NEW_LINE> <INDENT> resp = self.post('/predict', payload=payload) <NEW_LINE> resp_data = resp.json <NEW_LINE> <DEDENT> except BaseException as e: <NEW_LINE> <INDENT> print('Error while fetching prediction: {}'.format(e)) <NEW_LINE> exit(1) <NEW_LINE> <DEDENT> if not resp.ok: <NEW_LINE> <INDENT> print('Got error response from API: {}, with code: {}.'.format(resp_data.get('error'), resp.status)) <NEW_LINE> exit(1) <NEW_LINE> <DEDENT> return resp_data.get('prediction')
Glassdoor-NLP API client class
62598fb660cbc95b06364445
class Loan(WorkItem): <NEW_LINE> <INDENT> def __init__(self, loan_request): <NEW_LINE> <INDENT> WorkItem.__init__(self) <NEW_LINE> if not RuleManager.get_instance().check_rule('should_be_instance_of_loan_request', loan_request): <NEW_LINE> <INDENT> raise AssociationError('Loan Request instance expected, instead %s passed' % type(loan_request)) <NEW_LINE> <DEDENT> self.loan_request = loan_request <NEW_LINE> self.datetime = datetime.now()
A Loan is generated from a Loan Request
62598fb65fdd1c0f98e5e096
class Question(models.Model): <NEW_LINE> <INDENT> cmap = models.ForeignKey(CareerMap) <NEW_LINE> text = models.TextField(default="", blank=True, null=True) <NEW_LINE> layer = models.ForeignKey(Layer, blank=True, null=True) <NEW_LINE> basemap = models.ForeignKey(BaseMap, blank=True, null=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> order_with_respect_to = 'cmap' <NEW_LINE> <DEDENT> def dir(self): <NEW_LINE> <INDENT> return dir(self) <NEW_LINE> <DEDENT> def edit_form(self, request=None): <NEW_LINE> <INDENT> return QuestionForm(request, instance=self)
These are just "did you know" questions
62598fb64428ac0f6e658629