code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class ProjectUsersAdvSearch(SingleListResource): <NEW_LINE> <INDENT> exclude_fields = ['project', 'project_group_user'] <NEW_LINE> dynamic_fields = ['is_ongoing', 'is_referred'] <NEW_LINE> input_cls = Project <NEW_LINE> def queryset(self, id): <NEW_LINE> <INDENT> from ercc.ercc_bps.project.forms import SearchMemberForm <NEW_LINE> project = Project.objects.get_or_404(id=id) <NEW_LINE> form = SearchMemberForm.from_json(request.args) <NEW_LINE> if form.validate(): <NEW_LINE> <INDENT> search_q = form.search() <NEW_LINE> return project.queryset_project_user.filter(**search_q) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> current_app.logger.debug(form.errors) <NEW_LINE> abort(400)
project내 사용자 목록(상세검색용)
62598fb73d592f4c4edbafe8
class TestBcvSeqLibWithVariantMinCountFilter(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> prefix = "variant_mincount" <NEW_LINE> cfg = load_config_data(CFG_FILE, CFG_DIR) <NEW_LINE> cfg["fastq"]["reads"] = "{}/{}.fq".format(READS_DIR, prefix) <NEW_LINE> cfg["barcodes"]["map file"] = "{}/barcode_map.txt".format(READS_DIR) <NEW_LINE> cfg["variants"]["min count"] = 2 <NEW_LINE> self.test_component = HDF5TestComponent( store_constructor=BcvSeqLib, cfg=cfg, result_dir=RESULT_DIR, file_ext=FILE_EXT, file_sep=FILE_SEP, save=False, verbose=False, libtype=prefix, scoring_method="", logr_method="", coding="coding", ) <NEW_LINE> self.test_component.setUp() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> self.test_component.tearDown() <NEW_LINE> <DEDENT> def test_all_hdf5_dataframes(self): <NEW_LINE> <INDENT> self.test_component.runTest()
Test that variants with less than a count of 2 are removed.
62598fb7d486a94d0ba2c0f5
class Driver: <NEW_LINE> <INDENT> app_driver = None <NEW_LINE> @classmethod <NEW_LINE> def get_app_driver(cls): <NEW_LINE> <INDENT> if not cls.app_driver: <NEW_LINE> <INDENT> desired_caps = { 'platformName': 'Android', 'platformVersion': '5.1', 'deviceName': 'sanxing', 'appPackage': 'com.android.settings', 'appActivity': '.Settings' } <NEW_LINE> cls.app_driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps) <NEW_LINE> return cls.app_driver <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return cls.app_driver <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def quit_app_driver(cls): <NEW_LINE> <INDENT> if cls.app_driver: <NEW_LINE> <INDENT> cls.app_driver.quit() <NEW_LINE> cls.app_driver = None
声明web 或者 app的驱动对象
62598fb7fff4ab517ebcd910
class RevisionHealthState(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): <NEW_LINE> <INDENT> HEALTHY = "Healthy" <NEW_LINE> UNHEALTHY = "Unhealthy" <NEW_LINE> NONE = "None"
Current health State of the revision
62598fb792d797404e388bf7
class HealthcareRelation(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'relation_type': {'required': True}, 'entities': {'required': True}, } <NEW_LINE> _attribute_map = { 'relation_type': {'key': 'relationType', 'type': 'str'}, 'entities': {'key': 'entities', 'type': '[HealthcareRelationEntity]'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(HealthcareRelation, self).__init__(**kwargs) <NEW_LINE> self.relation_type = kwargs['relation_type'] <NEW_LINE> self.entities = kwargs['entities']
Every relation is an entity graph of a certain relationType, where all entities are connected and have specific roles within the relation context. All required parameters must be populated in order to send to Azure. :ivar relation_type: Required. Type of relation. Examples include: ``DosageOfMedication`` or 'FrequencyOfMedication', etc. Possible values include: "Abbreviation", "DirectionOfBodyStructure", "DirectionOfCondition", "DirectionOfExamination", "DirectionOfTreatment", "DosageOfMedication", "FormOfMedication", "FrequencyOfMedication", "FrequencyOfTreatment", "QualifierOfCondition", "RelationOfExamination", "RouteOfMedication", "TimeOfCondition", "TimeOfEvent", "TimeOfExamination", "TimeOfMedication", "TimeOfTreatment", "UnitOfCondition", "UnitOfExamination", "ValueOfCondition", "ValueOfExamination". :vartype relation_type: str or ~azure.ai.textanalytics.v3_1.models.RelationType :ivar entities: Required. The entities in the relation. :vartype entities: list[~azure.ai.textanalytics.v3_1.models.HealthcareRelationEntity]
62598fb77d847024c075c4e4
class ReadFile: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.filter = None <NEW_LINE> self.is_reading = False <NEW_LINE> <DEDENT> def load(self, loader): <NEW_LINE> <INDENT> loader.add_option( "rfile", typing.Optional[str], None, "Read flows from file." ) <NEW_LINE> loader.add_option( "readfile_filter", typing.Optional[str], None, "Read only matching flows." ) <NEW_LINE> <DEDENT> def configure(self, updated): <NEW_LINE> <INDENT> if "readfile_filter" in updated: <NEW_LINE> <INDENT> filt = None <NEW_LINE> if ctx.options.readfile_filter: <NEW_LINE> <INDENT> filt = flowfilter.parse(ctx.options.readfile_filter) <NEW_LINE> if not filt: <NEW_LINE> <INDENT> raise exceptions.OptionsError( "Invalid readfile filter: %s" % ctx.options.readfile_filter ) <NEW_LINE> <DEDENT> <DEDENT> self.filter = filt <NEW_LINE> <DEDENT> <DEDENT> async def load_flows(self, fo: typing.IO[bytes]) -> int: <NEW_LINE> <INDENT> cnt = 0 <NEW_LINE> freader = io.FlowReader(fo) <NEW_LINE> try: <NEW_LINE> <INDENT> for flow in freader.stream(): <NEW_LINE> <INDENT> if self.filter and not self.filter(flow): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> await ctx.master.load_flow(flow) <NEW_LINE> cnt += 1 <NEW_LINE> <DEDENT> <DEDENT> except (OSError, exceptions.FlowReadException) as e: <NEW_LINE> <INDENT> if cnt: <NEW_LINE> <INDENT> ctx.log.warn("Flow file corrupted - loaded %i flows." % cnt) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ctx.log.error("Flow file corrupted.") <NEW_LINE> <DEDENT> raise exceptions.FlowReadException(str(e)) from e <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return cnt <NEW_LINE> <DEDENT> <DEDENT> async def load_flows_from_path(self, path: str) -> int: <NEW_LINE> <INDENT> path = os.path.expanduser(path) <NEW_LINE> try: <NEW_LINE> <INDENT> with open(path, "rb") as f: <NEW_LINE> <INDENT> return await self.load_flows(f) <NEW_LINE> <DEDENT> <DEDENT> except OSError as e: <NEW_LINE> <INDENT> ctx.log.error(f"Cannot load flows: {e}") <NEW_LINE> raise exceptions.FlowReadException(str(e)) from e <NEW_LINE> <DEDENT> <DEDENT> async def doread(self, rfile): <NEW_LINE> <INDENT> self.is_reading = True <NEW_LINE> try: <NEW_LINE> <INDENT> await self.load_flows_from_path(ctx.options.rfile) <NEW_LINE> <DEDENT> except exceptions.FlowReadException as e: <NEW_LINE> <INDENT> raise exceptions.OptionsError(e) from e <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> self.is_reading = False <NEW_LINE> <DEDENT> <DEDENT> def running(self): <NEW_LINE> <INDENT> if ctx.options.rfile: <NEW_LINE> <INDENT> asyncio.get_event_loop().create_task(self.doread(ctx.options.rfile)) <NEW_LINE> <DEDENT> <DEDENT> @command.command("readfile.reading") <NEW_LINE> def reading(self) -> bool: <NEW_LINE> <INDENT> return self.is_reading
An addon that handles reading from file on startup.
62598fb7f548e778e596b6cd
class ProposalLayer(KE.Layer): <NEW_LINE> <INDENT> def __init__(self, proposal_count, nms_threshold, anchors, config=None, **kwargs): <NEW_LINE> <INDENT> super(ProposalLayer, self).__init__(**kwargs) <NEW_LINE> self.config = config <NEW_LINE> self.proposal_count = proposal_count <NEW_LINE> self.nms_threshold = nms_threshold <NEW_LINE> self.anchors = anchors.astype(np.float32) <NEW_LINE> <DEDENT> def call(self, inputs): <NEW_LINE> <INDENT> scores = inputs[0][:, :, 1] <NEW_LINE> deltas = inputs[1] <NEW_LINE> deltas = deltas * np.reshape(self.config.RPN_BBOX_STD_DEV, [1, 1, 4]) <NEW_LINE> anchors = self.anchors <NEW_LINE> pre_nms_limit = min(6000, self.anchors.shape[0]) <NEW_LINE> ix = tf.nn.top_k(scores, pre_nms_limit, sorted=True,name="top_anchors").indices <NEW_LINE> scores = utils.batch_slice([scores, ix], lambda x, y: tf.gather(x, y),self.config.IMAGES_PER_GPU) <NEW_LINE> deltas = utils.batch_slice([deltas, ix], lambda x, y: tf.gather(x, y),self.config.IMAGES_PER_GPU) <NEW_LINE> anchors = utils.batch_slice(ix, lambda x: tf.gather(anchors, x), self.config.IMAGES_PER_GPU, names=["pre_nms_anchors"]) <NEW_LINE> boxes = utils.batch_slice([anchors, deltas], lambda x, y: apply_box_deltas_graph(x, y), self.config.IMAGES_PER_GPU, names=["refined_anchors"]) <NEW_LINE> height, width = self.config.IMAGE_SHAPE[:2] <NEW_LINE> window = np.array([0, 0, height, width]).astype(np.float32) <NEW_LINE> boxes = utils.batch_slice(boxes, lambda x: clip_boxes_graph(x, window), self.config.IMAGES_PER_GPU, names=["refined_anchors_clipped"]) <NEW_LINE> normalized_boxes = boxes / np.array([[height, width, height, width]]) <NEW_LINE> def nms(normalized_boxes, scores): <NEW_LINE> <INDENT> indices = tf.image.non_max_suppression( normalized_boxes, scores, self.proposal_count, self.nms_threshold, name="rpn_non_max_suppression") <NEW_LINE> proposals = tf.gather(normalized_boxes, indices) <NEW_LINE> padding = tf.maximum(self.proposal_count - tf.shape(proposals)[0], 0) <NEW_LINE> proposals = tf.pad(proposals, [(0, padding), (0, 0)]) <NEW_LINE> return proposals <NEW_LINE> <DEDENT> proposals = utils.batch_slice([normalized_boxes, scores], nms,self.config.IMAGES_PER_GPU) <NEW_LINE> return proposals
Receives anchor scores and selects a subset to pass as proposals to the second stage. Filtering is done based on anchor scores and non-max suppression to remove overlaps. It also applies bounding box refinement deltas to anchors. Inputs: rpn_probs: [batch, anchors, (bg prob, fg prob)] rpn_bbox: [batch, anchors, (dy, dx, log(dh), log(dw))] Returns: Proposals in normalized coordinates [batch, rois, (y1, x1, y2, x2)]
62598fb74a966d76dd5ef000
class TestLuminanceNewhall1943(unittest.TestCase): <NEW_LINE> <INDENT> def test_luminance_Newhall1943(self): <NEW_LINE> <INDENT> self.assertAlmostEqual( luminance_Newhall1943(3.74629715382), 10.4089874577, places=7) <NEW_LINE> self.assertAlmostEqual( luminance_Newhall1943(8.64728711385), 71.3174801757, places=7) <NEW_LINE> self.assertAlmostEqual( luminance_Newhall1943(1.52569021578), 2.06998750444, places=7) <NEW_LINE> <DEDENT> def test_n_dimensional_luminance_Newhall1943(self): <NEW_LINE> <INDENT> V = 3.74629715382 <NEW_LINE> Y = 10.408987457743208 <NEW_LINE> np.testing.assert_almost_equal( luminance_Newhall1943(V), Y, decimal=7) <NEW_LINE> V = np.tile(V, 6) <NEW_LINE> Y = np.tile(Y, 6) <NEW_LINE> np.testing.assert_almost_equal( luminance_Newhall1943(V), Y, decimal=7) <NEW_LINE> V = np.reshape(V, (2, 3)) <NEW_LINE> Y = np.reshape(Y, (2, 3)) <NEW_LINE> np.testing.assert_almost_equal( luminance_Newhall1943(V), Y, decimal=7) <NEW_LINE> V = np.reshape(V, (2, 3, 1)) <NEW_LINE> Y = np.reshape(Y, (2, 3, 1)) <NEW_LINE> np.testing.assert_almost_equal( luminance_Newhall1943(V), Y, decimal=7) <NEW_LINE> <DEDENT> @ignore_numpy_errors <NEW_LINE> def test_nan_luminance_Newhall1943(self): <NEW_LINE> <INDENT> luminance_Newhall1943( np.array([-1.0, 0.0, 1.0, -np.inf, np.inf, np.nan]))
Defines :func:`colour.colorimetry.luminance.luminance_Newhall1943` definition unit tests methods.
62598fb7be7bc26dc9251ef0
class RequestAttrGetSpiritFacadeType: <NEW_LINE> <INDENT> thrift_spec = ( None, (1, TType.I64, 'actor_', None, None, ), (2, TType.I32, 'type_', None, None, ), ) <NEW_LINE> def __init__(self, actor_=None, type_=None,): <NEW_LINE> <INDENT> self.actor_ = actor_ <NEW_LINE> self.type_ = type_ <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.actor_ = 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.I32: <NEW_LINE> <INDENT> self.type_ = iprot.readI32(); <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('RequestAttrGetSpiritFacadeType') <NEW_LINE> if self.actor_ is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('actor_', TType.I64, 1) <NEW_LINE> oprot.writeI64(self.actor_) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.type_ is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('type_', TType.I32, 2) <NEW_LINE> oprot.writeI32(self.type_) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> if self.actor_ is None: <NEW_LINE> <INDENT> raise TProtocol.TProtocolException(message='Required field actor_ is unset!') <NEW_LINE> <DEDENT> if self.type_ is None: <NEW_LINE> <INDENT> raise TProtocol.TProtocolException(message='Required field type_ is unset!') <NEW_LINE> <DEDENT> 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: - actor_ - type_
62598fb763b5f9789fe85296
class SocialMedia(models.Model): <NEW_LINE> <INDENT> id = models.AutoField(primary_key=True) <NEW_LINE> title = models.CharField(max_length=200, unique=True) <NEW_LINE> url = models.URLField(max_length=200) <NEW_LINE> image = models.ImageField(default='static/img/default.png')
Model created for each social media instance
62598fb791f36d47f2230f3d
class backend: <NEW_LINE> <INDENT> escaped_chars = ( ('"', r'\"',), ("'", r"\'",), ("%", "%%",), ) <NEW_LINE> def identifyer_quotes(self, name): <NEW_LINE> <INDENT> return '"%s"' % name <NEW_LINE> <DEDENT> def string_quotes(self, string): <NEW_LINE> <INDENT> return "'%s'" % string <NEW_LINE> <DEDENT> def escape_string(self, string): <NEW_LINE> <INDENT> for a in self.escaped_chars: <NEW_LINE> <INDENT> string = string.replace(a[0], a[1]) <NEW_LINE> <DEDENT> return string <NEW_LINE> <DEDENT> def backend_encoding(self): <NEW_LINE> <INDENT> raise NotImplementedError()
This class provies all the methods needed for a datasource to work with an SQL backend. This class' instances will work for most SQL92 complient backends that use utf-8 unicode encoding.
62598fb73317a56b869be5e2
class GatewayRouteListResult(Model): <NEW_LINE> <INDENT> _attribute_map = { 'value': {'key': 'value', 'type': '[GatewayRoute]'}, } <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(GatewayRouteListResult, self).__init__(**kwargs) <NEW_LINE> self.value = kwargs.get('value', None)
List of virtual network gateway routes. :param value: List of gateway routes :type value: list[~azure.mgmt.network.v2016_09_01.models.GatewayRoute]
62598fb756ac1b37e6302316
class UUIDListSimple: <NEW_LINE> <INDENT> def __init__(self, project_uuids, class_uri): <NEW_LINE> <INDENT> self.uuids = Manifest.objects.values_list( 'uuid', flat=True) .filter(project_uuid__in=project_uuids, class_uri=class_uri).iterator()
The list of UUIDs used to create an export table.
62598fb7a8370b77170f0508
class MoveSteering(MoveTank): <NEW_LINE> <INDENT> def on_for_rotations(self, steering, speed, rotations, brake=True, block=True): <NEW_LINE> <INDENT> (left_speed, right_speed) = self.get_speed_steering(steering, speed) <NEW_LINE> MoveTank.on_for_rotations(self, SpeedNativeUnits(left_speed), SpeedNativeUnits(right_speed), rotations, brake, block) <NEW_LINE> <DEDENT> def on_for_degrees(self, steering, speed, degrees, brake=True, block=True): <NEW_LINE> <INDENT> (left_speed, right_speed) = self.get_speed_steering(steering, speed) <NEW_LINE> MoveTank.on_for_degrees(self, SpeedNativeUnits(left_speed), SpeedNativeUnits(right_speed), degrees, brake, block) <NEW_LINE> <DEDENT> def on_for_seconds(self, steering, speed, seconds, brake=True, block=True): <NEW_LINE> <INDENT> (left_speed, right_speed) = self.get_speed_steering(steering, speed) <NEW_LINE> MoveTank.on_for_seconds(self, SpeedNativeUnits(left_speed), SpeedNativeUnits(right_speed), seconds, brake, block) <NEW_LINE> <DEDENT> def on(self, steering, speed): <NEW_LINE> <INDENT> (left_speed, right_speed) = self.get_speed_steering(steering, speed) <NEW_LINE> MoveTank.on(self, SpeedNativeUnits(left_speed), SpeedNativeUnits(right_speed)) <NEW_LINE> <DEDENT> def get_speed_steering(self, steering, speed): <NEW_LINE> <INDENT> assert steering >= -100 and steering <= 100, "{} is an invalid steering, must be between -100 and 100 (inclusive)".format(steering) <NEW_LINE> speed = self.left_motor._speed_native_units(speed) <NEW_LINE> left_speed = speed <NEW_LINE> right_speed = speed <NEW_LINE> speed_factor = (50 - abs(float(steering))) / 50 <NEW_LINE> if steering >= 0: <NEW_LINE> <INDENT> right_speed *= speed_factor <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> left_speed *= speed_factor <NEW_LINE> <DEDENT> return (left_speed, right_speed)
Controls a pair of motors simultaneously, via a single "steering" value and a speed. steering [-100, 100]: * -100 means turn left on the spot (right motor at 100% forward, left motor at 100% backward), * 0 means drive in a straight line, and * 100 means turn right on the spot (left motor at 100% forward, right motor at 100% backward). "steering" can be any number between -100 and 100. Example: .. code:: python steering_drive = MoveSteering(OUTPUT_A, OUTPUT_B) # drive in a turn for 10 rotations of the outer motor steering_drive.on_for_rotations(-20, SpeedPercent(75), 10)
62598fb776e4537e8c3ef6d0
class AdaptorEthRecvQueueProfile(ManagedObject): <NEW_LINE> <INDENT> consts = AdaptorEthRecvQueueProfileConsts() <NEW_LINE> naming_props = set([]) <NEW_LINE> mo_meta = MoMeta("AdaptorEthRecvQueueProfile", "adaptorEthRecvQueueProfile", "eth-rcv-q", VersionMeta.Version101e, "InputOutput", 0x7f, [], ["admin", "ls-config-policy", "ls-network", "ls-server-policy"], ['adaptorHostEthIf', 'adaptorHostEthIfProfile', 'adaptorUsnicConnDef', 'adaptorVmmqConnDef'], [], ["Get", "Set"]) <NEW_LINE> prop_meta = { "child_action": MoPropertyMeta("child_action", "childAction", "string", VersionMeta.Version101e, MoPropertyMeta.INTERNAL, 0x2, None, None, r"""((deleteAll|ignore|deleteNonPresent),){0,2}(deleteAll|ignore|deleteNonPresent){0,1}""", [], []), "count": MoPropertyMeta("count", "count", "ushort", VersionMeta.Version101e, MoPropertyMeta.READ_WRITE, 0x4, None, None, None, [], ["1-1000"]), "dn": MoPropertyMeta("dn", "dn", "string", VersionMeta.Version101e, MoPropertyMeta.READ_ONLY, 0x8, 0, 256, None, [], []), "ring_size": MoPropertyMeta("ring_size", "ringSize", "ushort", VersionMeta.Version101e, MoPropertyMeta.READ_WRITE, 0x10, None, None, None, [], ["64-4096"]), "rn": MoPropertyMeta("rn", "rn", "string", VersionMeta.Version101e, MoPropertyMeta.READ_ONLY, 0x20, 0, 256, None, [], []), "sacl": MoPropertyMeta("sacl", "sacl", "string", VersionMeta.Version302c, MoPropertyMeta.READ_ONLY, None, None, None, r"""((none|del|mod|addchild|cascade),){0,4}(none|del|mod|addchild|cascade){0,1}""", [], []), "status": MoPropertyMeta("status", "status", "string", VersionMeta.Version101e, MoPropertyMeta.READ_WRITE, 0x40, None, None, r"""((removed|created|modified|deleted),){0,3}(removed|created|modified|deleted){0,1}""", [], []), } <NEW_LINE> prop_map = { "childAction": "child_action", "count": "count", "dn": "dn", "ringSize": "ring_size", "rn": "rn", "sacl": "sacl", "status": "status", } <NEW_LINE> def __init__(self, parent_mo_or_dn, **kwargs): <NEW_LINE> <INDENT> self._dirty_mask = 0 <NEW_LINE> self.child_action = None <NEW_LINE> self.count = None <NEW_LINE> self.ring_size = None <NEW_LINE> self.sacl = None <NEW_LINE> self.status = None <NEW_LINE> ManagedObject.__init__(self, "AdaptorEthRecvQueueProfile", parent_mo_or_dn, **kwargs)
This is AdaptorEthRecvQueueProfile class.
62598fb710dbd63aa1c70ce2
@python_2_unicode_compatible <NEW_LINE> class Container(Sequence): <NEW_LINE> <INDENT> def __init__(self, separator, sequence=[], esc='\\', separators='\r|~^&'): <NEW_LINE> <INDENT> super(Container, self).__init__(sequence) <NEW_LINE> self.separator = separator <NEW_LINE> self.esc = esc <NEW_LINE> self.separators = separators <NEW_LINE> <DEDENT> def __getitem__(self, item): <NEW_LINE> <INDENT> sequence = super(Container, self).__getitem__(item) <NEW_LINE> if isinstance(item, slice): <NEW_LINE> <INDENT> return self.__class__( self.separator, sequence, self.esc, self.separators ) <NEW_LINE> <DEDENT> return sequence <NEW_LINE> <DEDENT> def __getslice__(self, i, j): <NEW_LINE> <INDENT> return self.__getitem__(slice(i, j)) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.separator.join((six.text_type(x) for x in self))
Abstract root class for the parts of the HL7 message.
62598fb75fc7496912d48310
class SessionTracker(object): <NEW_LINE> <INDENT> __slots__ = ('_app', '__outgoing') <NEW_LINE> @contract_epydoc <NEW_LINE> def __init__(self, app): <NEW_LINE> <INDENT> self._app = app <NEW_LINE> self.__outgoing = {} <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<SessionTracker: {0!r}>' .format({k: OutgoingSessionStatus._to_str.get( v, 'n/a{0!r}'.format(v)) for (k, v) in self.__outgoing}) <NEW_LINE> <DEDENT> def _is_connected_out(self, peer): <NEW_LINE> <INDENT> return (peer in self.__outgoing and self.__outgoing[peer] in (OutgoingSessionStatus.CONNECTED, OutgoingSessionStatus.CONNECTED_VIA_NODE)) <NEW_LINE> <DEDENT> def outgoing_connecting(self, peer, host_through_node=False): <NEW_LINE> <INDENT> OSS = OutgoingSessionStatus <NEW_LINE> if ((peer not in self.__outgoing) or (host_through_node and self.__outgoing[peer] == OSS.CONNECTING) or (not host_through_node and self.__outgoing[peer] == OSS.CONNECTING_VIA_NODE)): <NEW_LINE> <INDENT> logger_status_session.info('Connecting to %r: via_node=%r', peer, host_through_node, extra={'is_outgoing': True, 'peer': peer, 'status': 'connecting', 'via_node': host_through_node}) <NEW_LINE> <DEDENT> if not self._is_connected_out(peer): <NEW_LINE> <INDENT> self.__outgoing[peer] = OSS.CONNECTING_VIA_NODE if host_through_node else OSS.CONNECTING <NEW_LINE> <DEDENT> <DEDENT> def outgoing_connected(self, peer, host_through_node=False): <NEW_LINE> <INDENT> if not self._is_connected_out(peer): <NEW_LINE> <INDENT> logger_status_session.info('Connected to %r: via_node=%r', peer, host_through_node, extra={'is_outgoing': True, 'peer': peer, 'status': 'connected', 'via_node': host_through_node}) <NEW_LINE> <DEDENT> _oss = OutgoingSessionStatus <NEW_LINE> self.__outgoing[peer] = _oss.CONNECTED_VIA_NODE if host_through_node else _oss.CONNECTED <NEW_LINE> <DEDENT> def outgoing_connection_completed(self, peer): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def outgoing_connection_failed(self, peer): <NEW_LINE> <INDENT> if self._is_connected_out(peer): <NEW_LINE> <INDENT> logger_status_session.info('Connection to %r failed', peer, extra={'is_outgoing': True, 'peer': peer, 'status': 'connection_failed', 'via_node': None}) <NEW_LINE> del self.__outgoing[peer] <NEW_LINE> <DEDENT> <DEDENT> def incoming_connected(self, peer): <NEW_LINE> <INDENT> logger_status_session.info('Incoming from %r', peer, extra={'is_outgoing': False, 'peer': peer, 'status': 'connected'})
The class capable of tracking the status of connection sessions established to some peers, whether nodes or hosts. It also keeps an eye on each incoming connection, but does not store the incoming sessions as it is not needed at the moment. The session tracked here are the series of connections establishments/losses to any peer, until some connection is lost for errorneous reasons.
62598fb730dc7b766599f977
class DocumentFairness(db.Model): <NEW_LINE> <INDENT> __tablename__ = "document_fairness" <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> doc_id = Column(Integer, ForeignKey('documents.id', ondelete='CASCADE'), index=True, nullable=False) <NEW_LINE> fairness_id = Column(Integer, ForeignKey('fairness.id'), index=True, default=6, nullable=False) <NEW_LINE> bias_favour_affiliation_id = Column(Integer, ForeignKey('affiliations.id'), index=True, nullable=True) <NEW_LINE> bias_oppose_affiliation_id = Column(Integer, ForeignKey('affiliations.id'), index=True, nullable=True) <NEW_LINE> created_at = Column(DateTime(timezone=True), index=True, unique=False, nullable=False, server_default=func.now()) <NEW_LINE> updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.current_timestamp()) <NEW_LINE> fairness = relationship("Fairness", lazy=False) <NEW_LINE> bias_favour = relationship("Affiliation", lazy=False, foreign_keys=[bias_favour_affiliation_id]) <NEW_LINE> bias_oppose = relationship("Affiliation", lazy=False, foreign_keys=[bias_oppose_affiliation_id]) <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return "<DocumentFairness id=%s, doc=%s, fairness=%s>" % (self.id, self.document, self.fairness)
Fairness/bias description for an article.
62598fb72c8b7c6e89bd38ef
class Component(object): <NEW_LINE> <INDENT> def __init__(self, x, y, w=0, h=0, is_selectable=False): <NEW_LINE> <INDENT> self.x = x <NEW_LINE> self.y = y <NEW_LINE> self.w = w <NEW_LINE> self.h = h <NEW_LINE> self.is_selectable = is_selectable <NEW_LINE> self.focused = False <NEW_LINE> <DEDENT> def publish_change(self, new_value): <NEW_LINE> <INDENT> bus.bus.publish({'source': self.source, 'new_value': new_value}, bus.MENU_MODEL_EVENT) <NEW_LINE> <DEDENT> def set_data(self, data): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def receive(self, event_data): <NEW_LINE> <INDENT> if event_data == Inputs.UP: <NEW_LINE> <INDENT> self.update_selected_index(-1) <NEW_LINE> <DEDENT> elif event_data == Inputs.DOWN: <NEW_LINE> <INDENT> self.update_selected_index(1) <NEW_LINE> <DEDENT> elif event_data == Inputs.LEFT: <NEW_LINE> <INDENT> self.left() <NEW_LINE> <DEDENT> elif event_data == Inputs.RIGHT: <NEW_LINE> <INDENT> self.right() <NEW_LINE> <DEDENT> elif event_data == Inputs.ENTER: <NEW_LINE> <INDENT> self.enter() <NEW_LINE> <DEDENT> elif event_data == Inputs.BACKSPACE: <NEW_LINE> <INDENT> self.backspace() <NEW_LINE> <DEDENT> elif event_data == Inputs.SPACE: <NEW_LINE> <INDENT> self.letter(' ') <NEW_LINE> <DEDENT> elif ord(event_data) >= 63 and ord(event_data) <= 122: <NEW_LINE> <INDENT> self.letter(event_data) <NEW_LINE> <DEDENT> <DEDENT> def left(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def right(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def enter(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def backspace(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def letter(self, c): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def send_next(self): <NEW_LINE> <INDENT> bus.bus.publish(ComponentEvent.NEXT, bus.MENU_ACTION) <NEW_LINE> <DEDENT> def send_previous(self): <NEW_LINE> <INDENT> bus.bus.publish(ComponentEvent.PREVIOUS, bus.MENU_ACTION) <NEW_LINE> <DEDENT> def update_selected_index(self, by): <NEW_LINE> <INDENT> self.leave_focus() <NEW_LINE> if by > 0: <NEW_LINE> <INDENT> self.send_next() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.send_previous() <NEW_LINE> <DEDENT> <DEDENT> def enter_focus(self): <NEW_LINE> <INDENT> self.focused = True <NEW_LINE> <DEDENT> def leave_focus(self): <NEW_LINE> <INDENT> self.focused = False
An abstract class for ui & menu components
62598fb79f288636728188ee
class Result: <NEW_LINE> <INDENT> def __init__(self, status, directive, message): <NEW_LINE> <INDENT> self.status = status <NEW_LINE> self.directive = directive <NEW_LINE> self.message = message <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> result = '%s: ' % self.status <NEW_LINE> if self.directive: <NEW_LINE> <INDENT> result += ('%s:%i: ' % (self.directive.inputfile, self.directive.linenum)) <NEW_LINE> <DEDENT> if self.message: <NEW_LINE> <INDENT> result += self.message <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return ('Result(%r, %r, %r)' % (self.status, self.directive, self.message))
A result of a test: a PASS/FAIL, with a message, and an optional directive that was being tested.
62598fb73d592f4c4edbafeb
class ReleaseTypeViewSet(StrictQueryParamMixin, mixins.ListModelMixin, viewsets.GenericViewSet): <NEW_LINE> <INDENT> queryset = models.ReleaseType.objects.all() <NEW_LINE> serializer_class = ReleaseTypeSerializer <NEW_LINE> filter_class = filters.ReleaseTypeFilter <NEW_LINE> permission_classes = (APIPermission,) <NEW_LINE> def list(self, request, *args, **kwargs): <NEW_LINE> <INDENT> return super(ReleaseTypeViewSet, self).list(request, *args, **kwargs)
##Overview## This page shows the usage of the **Release Types API**, please see the following for more details. ##Test tools## You can use ``curl`` in terminal, with -X _method_ (GET|POST|PUT|PATCH|DELETE), -d _data_ (a json string). or GUI plugins for browsers, such as ``RESTClient``, ``RESTConsole``.
62598fb732920d7e50bc6179
class ResetPassword(APIView): <NEW_LINE> <INDENT> def post(self, request, format=None): <NEW_LINE> <INDENT> data = request.data <NEW_LINE> if data['activity'] == 'token': <NEW_LINE> <INDENT> if check_token(data['email'], data['token']): <NEW_LINE> <INDENT> token = jwt.encode({'email': data['email'], 'random': str( datetime.now().timestamp())}, SECRET_FOR_JWT, algorithm='HS256').decode() <NEW_LINE> return Response({'message': 'success', 'token': token}, status=status.HTTP_200_OK) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Response({'message': 'invalid token'}, status=status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> <DEDENT> elif data['activity'] == 'update': <NEW_LINE> <INDENT> password_hash = sha256(data['password'].encode()).hexdigest() <NEW_LINE> user = User.objects.get(email=data['email']) <NEW_LINE> if user.password_hash == password_hash: <NEW_LINE> <INDENT> if is_token_valid(data['token'], 10): <NEW_LINE> <INDENT> new_password_hash = sha256( data['new_password'].encode()).hexdigest() <NEW_LINE> user.password_hash = new_password_hash <NEW_LINE> user.save() <NEW_LINE> return Response({'message': 'success'}, status=status.HTTP_200_OK) <NEW_LINE> <DEDENT> return Response({'message': 'invalid token'}, status=status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> return Response({'message': 'incorrect password'}, status=status.HTTP_401_UNAUTHORIZED) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Response({'message': 'invalid activity'}, status=status.HTTP_400_BAD_REQUEST)
Endpoint to reset a user's password
62598fb7aad79263cf42e8fe
class LoginPage(object): <NEW_LINE> <INDENT> _username_locator = ".//*[@id='cred_userid_inputtext']" <NEW_LINE> _password_locator = ".//*[@id='cred_password_inputtext']" <NEW_LINE> _signinbutton_locator = ".//*[@id='cred_sign_in_button']" <NEW_LINE> _loginclass_locator = ".//*[text()=\'Power BI\']" <NEW_LINE> _setting_icon = ".//*[@id=\'settingsMenuBtn\']" <NEW_LINE> _navigation_pane = "//div[@class='expanderBtn slideFadeIn']//following::i[@class='glyphicon " "pbi-glyph-globalnavbutton'] " <NEW_LINE> username = ConfigFileParser().powerbiusername() <NEW_LINE> password = ConfigFileParser().powerbipassword() <NEW_LINE> def __init__(context, browser): <NEW_LINE> <INDENT> context.browser = browser <NEW_LINE> <DEDENT> def setusername(context,username): <NEW_LINE> <INDENT> UtilityHelperClass(context.browser).wait_interval(1) <NEW_LINE> context.browser.find_element_by_xpath(context._username_locator).click() <NEW_LINE> context.browser.find_element_by_xpath(context._username_locator).send_keys(username) <NEW_LINE> <DEDENT> def setpassword(context, password): <NEW_LINE> <INDENT> context.browser.find_element_by_xpath(context._password_locator).send_keys(password) <NEW_LINE> <DEDENT> def clicklogin(context): <NEW_LINE> <INDENT> UtilityHelperClass(context.browser).wait_interval(1) <NEW_LINE> context.browser.find_element_by_xpath(context._signinbutton_locator).click() <NEW_LINE> <DEDENT> def getlogintext(context): <NEW_LINE> <INDENT> return context.browser.find_element_by_xpath(context._loginclass_locator).text <NEW_LINE> <DEDENT> def is_setting_icon_visible(context): <NEW_LINE> <INDENT> return context.browser.find_element_by_xpath(context._setting_icon) <NEW_LINE> <DEDENT> def check_navigation_pane_visible(context): <NEW_LINE> <INDENT> return context.browser.find_element_by_xpath(context._navigation_pane) <NEW_LINE> <DEDENT> def login(context): <NEW_LINE> <INDENT> UtilityHelperClass(context.browser).wait_interval(2) <NEW_LINE> try: <NEW_LINE> <INDENT> img = context.browser.find_element_by_xpath(".//*[@alt='Work or school account symbol']") <NEW_LINE> if (img.is_displayed()): <NEW_LINE> <INDENT> context.setpassword(context.password) <NEW_LINE> <DEDENT> <DEDENT> except NoSuchElementException: <NEW_LINE> <INDENT> context.setusername(context.username) <NEW_LINE> context.setpassword(context.password) <NEW_LINE> <DEDENT> context.clicklogin() <NEW_LINE> UtilityHelperClass(context.browser).wait_interval(2)
Login Class
62598fb7379a373c97d99140
@tf_export("data.experimental.service.DispatcherConfig") <NEW_LINE> class DispatcherConfig( collections.namedtuple("DispatcherConfig", [ "port", "protocol", "work_dir", "fault_tolerant_mode", "job_gc_check_interval_ms", "job_gc_timeout_ms" ])): <NEW_LINE> <INDENT> def __new__(cls, port=0, protocol=None, work_dir=None, fault_tolerant_mode=False, job_gc_check_interval_ms=None, job_gc_timeout_ms=None): <NEW_LINE> <INDENT> if protocol is None: <NEW_LINE> <INDENT> protocol = _pywrap_utils.TF_DATA_DefaultProtocol() <NEW_LINE> <DEDENT> if job_gc_check_interval_ms is None: <NEW_LINE> <INDENT> job_gc_check_interval_ms = 10 * 60 * 1000 <NEW_LINE> <DEDENT> if job_gc_timeout_ms is None: <NEW_LINE> <INDENT> job_gc_timeout_ms = 5 * 60 * 1000 <NEW_LINE> <DEDENT> return super(DispatcherConfig, cls).__new__(cls, port, protocol, work_dir, fault_tolerant_mode, job_gc_check_interval_ms, job_gc_timeout_ms)
Configuration class for tf.data service dispatchers. Fields: port: Specifies the port to bind to. A value of 0 indicates that the server may bind to any available port. protocol: The protocol to use for communicating with the tf.data service. Defaults to `"grpc"`. work_dir: A directory to store dispatcher state in. This argument is required for the dispatcher to be able to recover from restarts. fault_tolerant_mode: Whether the dispatcher should write its state to a journal so that it can recover from restarts. Dispatcher state, including registered datasets and created jobs, is synchronously written to the journal before responding to RPCs. If `True`, `work_dir` must also be specified. job_gc_check_interval_ms: How often the dispatcher should scan through to delete old and unused jobs, in milliseconds. If not set, the runtime will select a reasonable default. A higher value will reduce load on the dispatcher, while a lower value will reduce the time it takes for the dispatcher to garbage collect expired jobs. job_gc_timeout_ms: How long a job needs to be unused before it becomes a candidate for garbage collection, in milliseconds. If not set, the runtime will select a reasonable default. A higher value will cause jobs to stay around longer with no consumers. This is useful if there is a large gap in time between when consumers read from the job. A lower value will reduce the time it takes to reclaim the resources from expired jobs.
62598fb74527f215b58ea001
class CountrySerializers(serializers.ModelSerializer): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = Country <NEW_LINE> fields = ('id', 'name')
Country Serializers
62598fb7a219f33f346c6930
class SetExtension(_Action): <NEW_LINE> <INDENT> def __init__(self, extension): <NEW_LINE> <INDENT> _Action.__init__(self, 'SET EXTENSION', quote(extension))
Sets the extension for Asterisk to use upon completion of this AGI instance. No extension-validation is performed; specifying an invalid extension will cause the call to terminate unexpectedly. `AGIAppError` is raised on failure.
62598fb744b2445a339b6a09
class MLPCritic(nn.Module): <NEW_LINE> <INDENT> def __init__(self, obs_size: int, n_actions: int, hidden_size: int = 32): <NEW_LINE> <INDENT> super(MLPCritic, self).__init__() <NEW_LINE> self.net = nn.Sequential( nn.Linear(obs_size, hidden_size), nn.ReLU(), nn.Linear(hidden_size, n_actions), ) <NEW_LINE> <DEDENT> def forward(self, obs): <NEW_LINE> <INDENT> return self.net(obs)
Simple MLP network Args: obs_size: observation/state size of the environment n_actions: number of discrete actions available in the environment hidden_size: size of hidden layers
62598fb7f548e778e596b6d0
class QuotaDefinitionList(): <NEW_LINE> <INDENT> def __init__(self, resources: List['QuotaDefinition']) -> None: <NEW_LINE> <INDENT> self.resources = resources <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_dict(cls, _dict: Dict) -> 'QuotaDefinitionList': <NEW_LINE> <INDENT> args = {} <NEW_LINE> if 'resources' in _dict: <NEW_LINE> <INDENT> args['resources'] = [QuotaDefinition.from_dict(x) for x in _dict.get('resources')] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('Required property \'resources\' not present in QuotaDefinitionList JSON') <NEW_LINE> <DEDENT> return cls(**args) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _from_dict(cls, _dict): <NEW_LINE> <INDENT> return cls.from_dict(_dict) <NEW_LINE> <DEDENT> def to_dict(self) -> Dict: <NEW_LINE> <INDENT> _dict = {} <NEW_LINE> if hasattr(self, 'resources') and self.resources is not None: <NEW_LINE> <INDENT> _dict['resources'] = [x.to_dict() for x in self.resources] <NEW_LINE> <DEDENT> return _dict <NEW_LINE> <DEDENT> def _to_dict(self): <NEW_LINE> <INDENT> return self.to_dict() <NEW_LINE> <DEDENT> def __str__(self) -> str: <NEW_LINE> <INDENT> return json.dumps(self.to_dict(), indent=2) <NEW_LINE> <DEDENT> def __eq__(self, other: 'QuotaDefinitionList') -> bool: <NEW_LINE> <INDENT> if not isinstance(other, self.__class__): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other: 'QuotaDefinitionList') -> bool: <NEW_LINE> <INDENT> return not self == other
A list of quota definitions. :attr List[QuotaDefinition] resources: The list of quota definitions.
62598fb763d6d428bbee28da
class BaseTaskRunner(LoggingMixin): <NEW_LINE> <INDENT> def __init__(self, local_task_job): <NEW_LINE> <INDENT> super(BaseTaskRunner, self).__init__(local_task_job.task_instance) <NEW_LINE> self._task_instance = local_task_job.task_instance <NEW_LINE> popen_prepend = [] <NEW_LINE> cfg_path = None <NEW_LINE> if self._task_instance.run_as_user: <NEW_LINE> <INDENT> self.run_as_user = self._task_instance.run_as_user <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.run_as_user = conf.get('core', 'default_impersonation') <NEW_LINE> <DEDENT> except conf.AirflowConfigException: <NEW_LINE> <INDENT> self.run_as_user = None <NEW_LINE> <DEDENT> <DEDENT> if self.run_as_user and (self.run_as_user != getpass.getuser()): <NEW_LINE> <INDENT> self.log.debug("Planning to run as the %s user", self.run_as_user) <NEW_LINE> cfg_dict = conf.as_dict(display_sensitive=True) <NEW_LINE> cfg_subset = { 'core': cfg_dict.get('core', {}), 'smtp': cfg_dict.get('smtp', {}), 'scheduler': cfg_dict.get('scheduler', {}), 'webserver': cfg_dict.get('webserver', {}), } <NEW_LINE> temp_fd, cfg_path = mkstemp() <NEW_LINE> subprocess.call( ['sudo', 'chown', self.run_as_user, cfg_path] ) <NEW_LINE> subprocess.call( ['sudo', 'chmod', '600', cfg_path] ) <NEW_LINE> with os.fdopen(temp_fd, 'w') as temp_file: <NEW_LINE> <INDENT> json.dump(cfg_subset, temp_file) <NEW_LINE> <DEDENT> popen_prepend = ['sudo', '-H', '-u', self.run_as_user] <NEW_LINE> <DEDENT> self._cfg_path = cfg_path <NEW_LINE> self._command = popen_prepend + self._task_instance.command_as_list( raw=True, pickle_id=local_task_job.pickle_id, mark_success=local_task_job.mark_success, job_id=local_task_job.id, pool=local_task_job.pool, cfg_path=cfg_path, ) <NEW_LINE> self.process = None <NEW_LINE> <DEDENT> def _read_task_logs(self, stream): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> line = stream.readline() <NEW_LINE> if isinstance(line, bytes): <NEW_LINE> <INDENT> line = line.decode('utf-8') <NEW_LINE> <DEDENT> if len(line) == 0: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> self.log.info('Subtask: %s', line.rstrip('\n')) <NEW_LINE> <DEDENT> <DEDENT> def run_command(self, run_with, join_args=False): <NEW_LINE> <INDENT> cmd = [" ".join(self._command)] if join_args else self._command <NEW_LINE> full_cmd = run_with + cmd <NEW_LINE> self.log.info('Running: %s', full_cmd) <NEW_LINE> proc = subprocess.Popen( full_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True ) <NEW_LINE> log_reader = threading.Thread( target=self._read_task_logs, args=(proc.stdout,), ) <NEW_LINE> log_reader.daemon = True <NEW_LINE> log_reader.start() <NEW_LINE> return proc <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def return_code(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def terminate(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def on_finish(self): <NEW_LINE> <INDENT> if self._cfg_path and os.path.isfile(self._cfg_path): <NEW_LINE> <INDENT> subprocess.call(['sudo', 'rm', self._cfg_path])
Runs Airflow task instances by invoking the `airflow run` command with raw mode enabled in a subprocess.
62598fb7283ffb24f3cf39ae
class Money(types.TypeDecorator): <NEW_LINE> <INDENT> impl = types.Numeric(20, 8)
Money amount.
62598fb77b180e01f3e490e7
class Color(DefaultColor): <NEW_LINE> <INDENT> pass
This subclass is required when the user chooses to use 'default' theme. Because the segments require a 'Color' class for every theme.
62598fb7cc0a2c111447b138
class _BaseSearchObject: <NEW_LINE> <INDENT> _NON_STICKY_ATTRS = () <NEW_LINE> def _transfer_attrs(self, obj): <NEW_LINE> <INDENT> for attr in self.__dict__: <NEW_LINE> <INDENT> if attr not in self._NON_STICKY_ATTRS: <NEW_LINE> <INDENT> setattr(obj, attr, self.__dict__[attr])
Abstract class for SearchIO objects.
62598fb776e4537e8c3ef6d2
class Line(Component): <NEW_LINE> <INDENT> def __init__( self, a = 0, b = 1 ): <NEW_LINE> <INDENT> Component.__init__(self, ['a','b']) <NEW_LINE> self.name = 'Line' <NEW_LINE> self.a.free, self.b.free = True, True <NEW_LINE> self.a.value, self.b.value = a, b <NEW_LINE> self.isbackground = True <NEW_LINE> self.convolved = False <NEW_LINE> self.a.grad = self.grad_a <NEW_LINE> self.b.grad = self.grad_b <NEW_LINE> self.start_from = None <NEW_LINE> <DEDENT> def function(self, x): <NEW_LINE> <INDENT> if self.start_from is None: <NEW_LINE> <INDENT> return self.a.value + self.b.value*x <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return np.where(x > self.start_from, self.a.value + self.b.value*x, 0) <NEW_LINE> <DEDENT> <DEDENT> def grad_a(self, x): <NEW_LINE> <INDENT> return np.ones((len(x))) <NEW_LINE> <DEDENT> def grad_b(self, x): <NEW_LINE> <INDENT> if self.start_from is None: <NEW_LINE> <INDENT> return np.where(x > self.start_from, x, 0)
Given an array of the same shape as Spectrum energy_axis, returns it as a component that can be added to a model.
62598fb75fc7496912d48311
@linter(executable='cr') <NEW_LINE> class JSComplexityBear: <NEW_LINE> <INDENT> LANGUAGES = {'JavaScript'} <NEW_LINE> REQUIREMENTS = {NpmRequirement('complexity-report', '2.0.0-alpha')} <NEW_LINE> AUTHORS = {'The coala developers'} <NEW_LINE> AUTHORS_EMAILS = {'coala-devel@googlegroups.com'} <NEW_LINE> LICENSE = 'AGPL-3.0' <NEW_LINE> ASCIINEMA_URL = 'https://asciinema.org/a/39250' <NEW_LINE> CAN_DETECT = {'Complexity'} <NEW_LINE> @staticmethod <NEW_LINE> def create_arguments(filename, file, config_file): <NEW_LINE> <INDENT> return '--format', 'json', filename <NEW_LINE> <DEDENT> def process_output(self, output, filename, file, cc_threshold: int = 10, ): <NEW_LINE> <INDENT> message = '{} has a cyclomatic complexity of {}.' <NEW_LINE> if not output: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> output = json.loads(output) <NEW_LINE> <DEDENT> except JSONDecodeError: <NEW_LINE> <INDENT> output_regex = (r'Fatal error \[getReports\]: .+: ' r'Line (?P<line>\d+): (?P<message>.*)') <NEW_LINE> for match in re.finditer(output_regex, output): <NEW_LINE> <INDENT> groups = match.groupdict() <NEW_LINE> yield Result.from_values( origin=self, message=groups['message'].strip(), file=filename, severity=RESULT_SEVERITY.MAJOR, line=int(groups['line'])) <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> for function in output['reports'][0]['functions']: <NEW_LINE> <INDENT> if function['cyclomatic'] >= cc_threshold: <NEW_LINE> <INDENT> yield Result.from_values( origin=self, message=message.format(function['name'], function['cyclomatic']), file=filename, line=function['line'])
Calculates cyclomatic complexity using ``cr``, the command line utility provided by the NodeJS module ``complexity-report``.
62598fb7498bea3a75a57c4e
@unittest.skipUnless(selinux.is_selinux_enabled() == 1, "SELinux is disabled") <NEW_LINE> class SELinuxContextTestCase(loopbackedtestcase.LoopBackedTestCase): <NEW_LINE> <INDENT> def __init__(self, methodName='runTest'): <NEW_LINE> <INDENT> super(SELinuxContextTestCase, self).__init__(methodName=methodName, deviceSpec=[Size("100 MiB")]) <NEW_LINE> <DEDENT> def setUp(self): <NEW_LINE> <INDENT> self.installer_mode = blivet.flags.installer_mode <NEW_LINE> super(SELinuxContextTestCase, self).setUp() <NEW_LINE> <DEDENT> def testMountingExt2FS(self): <NEW_LINE> <INDENT> LOST_AND_FOUND_CONTEXT = 'system_u:object_r:lost_found_t:s0' <NEW_LINE> an_fs = fs.Ext2FS(device=self.loopDevices[0], label="test") <NEW_LINE> if not an_fs.formattable or not an_fs.mountable: <NEW_LINE> <INDENT> self.skipTest("can not create or mount filesystem %s" % an_fs.name) <NEW_LINE> <DEDENT> self.assertIsNone(an_fs.create()) <NEW_LINE> blivet.flags.installer_mode = False <NEW_LINE> mountpoint = tempfile.mkdtemp("test.selinux") <NEW_LINE> an_fs.mount(mountpoint=mountpoint) <NEW_LINE> lost_and_found = os.path.join(mountpoint, "lost+found") <NEW_LINE> self.assertTrue(os.path.exists(lost_and_found)) <NEW_LINE> lost_and_found_selinux_context = selinux.getfilecon(lost_and_found) <NEW_LINE> an_fs.unmount() <NEW_LINE> os.rmdir(mountpoint) <NEW_LINE> self.assertNotEqual(lost_and_found_selinux_context[1], LOST_AND_FOUND_CONTEXT) <NEW_LINE> blivet.flags.installer_mode = True <NEW_LINE> mountpoint = tempfile.mkdtemp("test.selinux") <NEW_LINE> an_fs.mount(mountpoint=mountpoint) <NEW_LINE> lost_and_found = os.path.join(mountpoint, "lost+found") <NEW_LINE> self.assertTrue(os.path.exists(lost_and_found)) <NEW_LINE> lost_and_found_selinux_context = selinux.getfilecon(lost_and_found) <NEW_LINE> an_fs.unmount() <NEW_LINE> os.rmdir(mountpoint) <NEW_LINE> self.assertEqual(lost_and_found_selinux_context[1], LOST_AND_FOUND_CONTEXT) <NEW_LINE> <DEDENT> def testMountingXFS(self): <NEW_LINE> <INDENT> an_fs = fs.XFS(device=self.loopDevices[0], label="test") <NEW_LINE> if not an_fs.formattable or not an_fs.mountable: <NEW_LINE> <INDENT> self.skipTest("can not create or mount filesystem %s" % an_fs.name) <NEW_LINE> <DEDENT> self.assertIsNone(an_fs.create()) <NEW_LINE> blivet.flags.installer_mode = False <NEW_LINE> mountpoint = tempfile.mkdtemp("test.selinux") <NEW_LINE> an_fs.mount(mountpoint=mountpoint) <NEW_LINE> lost_and_found = os.path.join(mountpoint, "lost+found") <NEW_LINE> self.assertFalse(os.path.exists(lost_and_found)) <NEW_LINE> an_fs.unmount() <NEW_LINE> os.rmdir(mountpoint) <NEW_LINE> blivet.flags.installer_mode = True <NEW_LINE> mountpoint = tempfile.mkdtemp("test.selinux") <NEW_LINE> an_fs.mount(mountpoint=mountpoint) <NEW_LINE> lost_and_found = os.path.join(mountpoint, "lost+found") <NEW_LINE> self.assertFalse(os.path.exists(lost_and_found)) <NEW_LINE> an_fs.unmount() <NEW_LINE> os.rmdir(mountpoint) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> super(SELinuxContextTestCase, self).tearDown() <NEW_LINE> blivet.flags.installer_mode = self.installer_mode
Testing SELinux contexts.
62598fb730dc7b766599f979
class Field_actor_postedtime(acscsv._Field): <NEW_LINE> <INDENT> path = ["actor", "postedTime"] <NEW_LINE> def __init__(self, json_record): <NEW_LINE> <INDENT> super( Field_actor_postedtime , self).__init__(json_record) <NEW_LINE> input_fmt = "%Y-%m-%dT%H:%M:%S.000Z" <NEW_LINE> self.value = datetime.strptime(self.value, input_fmt).strftime(self.default_t_fmt)
Take a dict, assign to self.value the value of actor.postedTime
62598fb72c8b7c6e89bd38f0
class ThumbnailHook(Hook): <NEW_LINE> <INDENT> def execute(self, **kwargs): <NEW_LINE> <INDENT> engine = self.parent.engine <NEW_LINE> engine_name = engine.name <NEW_LINE> return None
Hook that can be used to provide a pre-defined thumbnail for the app
62598fb766673b3332c304fb
class Data_Set(models.Model): <NEW_LINE> <INDENT> indicator = models.ForeignKey( Health_Indicator, on_delete=models.PROTECT, related_name="data_sets" ) <NEW_LINE> year = models.PositiveSmallIntegerField( validators=[ MinValueValidator(1000, message="Years before 1000 C.E. are extremely unlikely..."), MaxValueValidator(9999, message="If it really is later than the year 9999?"), ] ) <NEW_LINE> source_document = models.ForeignKey( Document, on_delete=models.SET_NULL, null=True, related_name='data_sets' ) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return f"Dataset {self.id} for indicator {self.indicator!s} and year {self.year:d}" <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = 'Data set'
A collection of data points for a single year and health indicator, generated from a document
62598fb72c8b7c6e89bd38f1
class IPHandlerTests(SimpleTestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> prep_db() <NEW_LINE> self.factory = RequestFactory() <NEW_LINE> self.user = CRITsUser.objects(username=TUSER_NAME).first() <NEW_LINE> self.user.sources.append(TSRC) <NEW_LINE> self.user.save() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> clean_db() <NEW_LINE> <DEDENT> def testIPAdd(self): <NEW_LINE> <INDENT> data = { 'source_reference': IP_REF, 'source': IP_SRC, 'ip_type': IP_TYPE, 'ip': IPADDR, 'analyst': TUSER_NAME, 'bucket_list': IP_BUCKET, 'ticket': IP_TICKET, } <NEW_LINE> errors = [] <NEW_LINE> (result, errors, retVal) = handlers.add_new_ip(data, rowData={}, request=self.factory, errors="") <NEW_LINE> self.assertTrue(result) <NEW_LINE> self.assertTrue(retVal['success']) <NEW_LINE> <DEDENT> def testIPGet(self): <NEW_LINE> <INDENT> self.assertEqual(IP.objects(ip=IPADDR).count(), 1) <NEW_LINE> ip = IP.objects(ip=IPADDR).first() <NEW_LINE> self.assertEqual(ip.ip, IPADDR) <NEW_LINE> self.assertEqual(set(ip.bucket_list), set(IP_LIST)) <NEW_LINE> self.assertTrue(ip.tickets[0]['ticket_number'] in IP_LIST)
Test IP handlers.
62598fb797e22403b383b032
class pattern: <NEW_LINE> <INDENT> def __init__(self, raw=""): <NEW_LINE> <INDENT> self.name = "" <NEW_LINE> self.solved_problem = "" <NEW_LINE> if raw != "": <NEW_LINE> <INDENT> self.derive = self.process(raw) <NEW_LINE> <DEDENT> <DEDENT> def process(self, raw) -> List[str]: <NEW_LINE> <INDENT> temp = raw.split("->") <NEW_LINE> self.name = temp[0] <NEW_LINE> return [x.replace("\n", "") for x in temp[1].split("|")]
规则类,每一个规则类包含以下属性: 1.规则的开始符 name 2.规则推导出的字符列表 derive
62598fb7d486a94d0ba2c0f9
class Participante(Base): <NEW_LINE> <INDENT> __tablename__ = 'participante' <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> nombre = Column(String, nullable=False) <NEW_LINE> correo_electronico = Column(String, nullable=False) <NEW_LINE> id_competencia = Column(Integer, ForeignKey('competencia.id')) <NEW_LINE> historial_nombres = relationship("HistorialNombres", cascade="save-update, merge, delete") <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return '<Participante(%r, %r)>' % (self.nombre, self.correo_electronico)
Almacena informacion de un participante
62598fb7796e427e5384e8c1
class Error(BaseType): <NEW_LINE> <INDENT> status = False <NEW_LINE> def __init__(self, ok, error_code, description): <NEW_LINE> <INDENT> self.status = ok <NEW_LINE> self.error_code = error_code <NEW_LINE> self.description = description
Error type class.
62598fb726068e7796d4ca85
class User(object): <NEW_LINE> <INDENT> user_path = setting.USER_DIR <NEW_LINE> user_home_path = setting.USER_HOME_DIR <NEW_LINE> def __init__(self, username, password): <NEW_LINE> <INDENT> self.username = username <NEW_LINE> self.password = password <NEW_LINE> <DEDENT> def user_info(self): <NEW_LINE> <INDENT> user_list = [] <NEW_LINE> user_info_list = os.listdir(self.user_path) <NEW_LINE> for user in user_info_list: <NEW_LINE> <INDENT> file_path = os.path.join(self.user_path, user) <NEW_LINE> user_info = pickle.load(open(file_path, 'rb')) <NEW_LINE> user_list.append(user_info) <NEW_LINE> <DEDENT> return user_list <NEW_LINE> <DEDENT> def login(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> user_info_list = self.user_info() <NEW_LINE> for user in os.listdir(self.user_path): <NEW_LINE> <INDENT> if common.create_md5(self.username) == user: <NEW_LINE> <INDENT> user_home_info = os.path.join(self.user_path, user) <NEW_LINE> user_info = pickle.load(open(user_home_info, 'rb')) <NEW_LINE> if self.username == user_info[0]: <NEW_LINE> <INDENT> if common.create_md5(self.password) == user_info[1]: <NEW_LINE> <INDENT> print('\033[32;1m login success\033[0m') <NEW_LINE> return True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> print('\033[31;1m username or password is fail\033[0m') <NEW_LINE> <DEDENT> <DEDENT> except FileNotFoundError: <NEW_LINE> <INDENT> print('user is not exist') <NEW_LINE> <DEDENT> <DEDENT> def register(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> user_list = [] <NEW_LINE> user_info_list = self.user_info() <NEW_LINE> for user in user_info_list: <NEW_LINE> <INDENT> user_list.append(user[0]) <NEW_LINE> <DEDENT> if self.username in user_list: <NEW_LINE> <INDENT> print('用户名已存在') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> md5_password = common.create_md5(self.password) <NEW_LINE> user_info = [self.username, md5_password, self.space_disk()] <NEW_LINE> file_path = os.path.join(self.user_path, common.create_md5(self.username)) <NEW_LINE> pickle.dump(user_info, open(file_path, 'wb')) <NEW_LINE> self.ftp_dir() <NEW_LINE> <DEDENT> <DEDENT> except TypeError: <NEW_LINE> <INDENT> print('注册失败') <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> print('注册失败') <NEW_LINE> <DEDENT> <DEDENT> def space_disk(self): <NEW_LINE> <INDENT> space_size = random.randrange(5, 30, 5) <NEW_LINE> space_size = space_size*1024*1024*1024 <NEW_LINE> return space_size <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_space(cls, username): <NEW_LINE> <INDENT> for user_file in os.listdir(cls.user_path): <NEW_LINE> <INDENT> if common.create_md5(username) == user_file: <NEW_LINE> <INDENT> user_file_path = os.path.join(cls.user_path, user_file) <NEW_LINE> user_info = pickle.load(open(user_file_path, 'rb')) <NEW_LINE> return user_info[2] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def ftp_dir(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> file_path = os.path.join(self.user_home_path, self.username) <NEW_LINE> os.mkdir(file_path) <NEW_LINE> return file_path <NEW_LINE> <DEDENT> except FileNotFoundError: <NEW_LINE> <INDENT> print('用户 %s 家目录创建失败' % self.username)
用户类
62598fb8dc8b845886d536e4
class Model: <NEW_LINE> <INDENT> def __init__(self, logger = None): <NEW_LINE> <INDENT> self.logger = Logger.logger() if logger == None else logger <NEW_LINE> self.channels = { } <NEW_LINE> self.bridges = { } <NEW_LINE> self.trunks = { } <NEW_LINE> self.calls = [ ] <NEW_LINE> self.numbers = { } <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Model(" + hex(id(self)) + ")" <NEW_LINE> <DEDENT> def bridge(self, pbx, uniqueid1, uniqueid2): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def confbridgeend(self, pbx, conference): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def confbridgejoin(self, pbx, uniqueid, conference): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def confbridgeleave(self, pbx, uniqueid, conference): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def confbridgestart(self, pbx, conference): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def dial(self, pbx, uniqueid, destuniqueid): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def end(self, pbx): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def hangup(self, pbx, uniqueid): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def localbridge(self, pbx, uniqueid1, uniqueid2): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def newchannel(self, pbx, uniqueid, channel, calleridnum, channelstate, channelstatedesc): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def newstate(self, pbx, uniqueid, channelstate, channelstatedesc): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def rename(self, pbx, uniqueid, newname): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def sipcallid(self, pbx, uniqueid, value): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def hanguprequest(self, pbx, uniqueid): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def musiconhold(self, pbx, uniqueid): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def musicoffhold(self, pbx, uniqueid): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def newcallerid(self, pbx, uniqueid, channel, calleridnum): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def softhanguprequest(self, pbx, uniqueid, cause): <NEW_LINE> <INDENT> pass
Model describes how Events received from one or more AMI Sources affect the dynamic call state maintained by Hackamore. Model is not concerned with how those Events are received (that's the Controller), nor with how they are displayed (that's the View). There can be more than one kind of Model. This particular Model is just a container database that is the dynamic call state. Its individual methods which represent events and their parameters do not change the database; that's up to derived classes.
62598fb83539df3088ecc3d9
class Solution: <NEW_LINE> <INDENT> def ladderLength(self, start, end, dict): <NEW_LINE> <INDENT> dict.add(end) <NEW_LINE> wordLen = len(start) <NEW_LINE> queue = collections.deque([(start, 1)]) <NEW_LINE> while queue: <NEW_LINE> <INDENT> curr = queue.popleft() <NEW_LINE> currWord = curr[0]; currLen = curr[1] <NEW_LINE> if currWord == end: <NEW_LINE> <INDENT> return currLen <NEW_LINE> <DEDENT> for next_word in self.get_next_words(currWord): <NEW_LINE> <INDENT> if next_word in dict: <NEW_LINE> <INDENT> queue.append((next_word, currLen + 1)) <NEW_LINE> dict.remove(next_word) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return 0 <NEW_LINE> <DEDENT> def get_next_words(self, word): <NEW_LINE> <INDENT> words = [] <NEW_LINE> for i in range(len(word)): <NEW_LINE> <INDENT> left, right = word[:i], word[i + 1:] <NEW_LINE> import string <NEW_LINE> for char in string.ascii_lowercase: <NEW_LINE> <INDENT> if word[i] == char: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> words.append(left + char + right) <NEW_LINE> <DEDENT> <DEDENT> return words
@param: start: a string @param: end: a string @param: dict: a set of string @return: An integer
62598fb8aad79263cf42e900
class AddrPublicationAddRsp(ResponsePacket): <NEW_LINE> <INDENT> def __init__(self, raw_data): <NEW_LINE> <INDENT> __data = {} <NEW_LINE> __data["address_handle"] = barray_pop(raw_data, 2) <NEW_LINE> assert(len(raw_data) == 0) <NEW_LINE> super(AddrPublicationAddRsp, self).__init__("AddrPublicationAdd", 0xA4, __data)
Response to a(n) AddrPublicationAdd command.
62598fb860cbc95b0636446b
class TestNumberAttribute: <NEW_LINE> <INDENT> def test_number_attribute(self): <NEW_LINE> <INDENT> attr = NumberAttribute() <NEW_LINE> assert attr is not None <NEW_LINE> assert attr.attr_type == NUMBER <NEW_LINE> attr = NumberAttribute(default=1) <NEW_LINE> assert attr.default == 1 <NEW_LINE> <DEDENT> def test_number_serialize(self): <NEW_LINE> <INDENT> attr = NumberAttribute() <NEW_LINE> assert attr.serialize(3.141) == '3.141' <NEW_LINE> assert attr.serialize(1) == '1' <NEW_LINE> assert attr.serialize(12345678909876543211234234324234) == '12345678909876543211234234324234' <NEW_LINE> <DEDENT> def test_number_deserialize(self): <NEW_LINE> <INDENT> attr = NumberAttribute() <NEW_LINE> assert attr.deserialize('1') == 1 <NEW_LINE> assert attr.deserialize('3.141') == 3.141 <NEW_LINE> assert attr.deserialize('12345678909876543211234234324234') == 12345678909876543211234234324234 <NEW_LINE> <DEDENT> def test_number_set_deserialize(self): <NEW_LINE> <INDENT> attr = NumberSetAttribute() <NEW_LINE> assert attr.attr_type == NUMBER_SET <NEW_LINE> assert attr.deserialize([json.dumps(val) for val in sorted(set([1, 2]))]) == set([1, 2]) <NEW_LINE> <DEDENT> def test_number_set_serialize(self): <NEW_LINE> <INDENT> attr = NumberSetAttribute() <NEW_LINE> assert attr.serialize(set([1, 2])) == [json.dumps(val) for val in sorted(set([1, 2]))] <NEW_LINE> assert attr.serialize(None) is None <NEW_LINE> <DEDENT> def test_number_set_attribute(self): <NEW_LINE> <INDENT> attr = NumberSetAttribute() <NEW_LINE> assert attr is not None <NEW_LINE> attr = NumberSetAttribute(default=set([1, 2])) <NEW_LINE> assert attr.default == set([1, 2])
Tests number attributes
62598fb8be7bc26dc9251ef2
class GreenLight(QtGui.QWidget): <NEW_LINE> <INDENT> def __init__(self, parent=None): <NEW_LINE> <INDENT> super(GreenLight, self).__init__(parent) <NEW_LINE> self.setFixedSize(22, 22) <NEW_LINE> self.green = QtGui.QColor(44, 173, 9) <NEW_LINE> <DEDENT> def paintEvent(self, e): <NEW_LINE> <INDENT> painter = QtGui.QPainter() <NEW_LINE> painter.begin(self) <NEW_LINE> painter.setRenderHint(QtGui.QPainter.Antialiasing, True) <NEW_LINE> painter.setPen(self.green) <NEW_LINE> painter.setBrush(self.green) <NEW_LINE> painter.drawEllipse(1, 1, 20, 20) <NEW_LINE> painter.end()
Creates a green circle
62598fb80fa83653e46f500e
class CarrierRequest(models.Model): <NEW_LINE> <INDENT> sender = models.ForeignKey(Contractor, on_delete=models.CASCADE, related_name='+', ) <NEW_LINE> loading_address = models.CharField(max_length=256) <NEW_LINE> loading_contacts = models.CharField(max_length=256, blank=True) <NEW_LINE> recipient = models.ForeignKey(Contractor, on_delete=models.CASCADE, related_name='+', ) <NEW_LINE> landing_address = models.CharField(max_length=256) <NEW_LINE> landing_contacts = models.CharField(max_length=256, blank=True) <NEW_LINE> vehicle = models.ForeignKey(Contractor, on_delete=models.CASCADE, related_name='+', ) <NEW_LINE> driver = models.ForeignKey(Contractor, on_delete=models.CASCADE, related_name='+', ) <NEW_LINE> carrier = models.ForeignKey(Contractor, on_delete=models.CASCADE, related_name='+', ) <NEW_LINE> department = models.ForeignKey(Contractor, on_delete=models.CASCADE, related_name='+', ) <NEW_LINE> payment_type = models.ForeignKey(Contractor, on_delete=models.CASCADE, related_name='+', ) <NEW_LINE> cost = models.DecimalField(max_digits=16, decimal_places=9) <NEW_LINE> invoice_number = models.CharField(max_length=20) <NEW_LINE> invoice_date = models.DateField() <NEW_LINE> payment_date = models.DateField() <NEW_LINE> delay = models.BooleanField()
Carrier request / Заявка с перевозчиком
62598fb84428ac0f6e65864e
class Coin(IntervalModule): <NEW_LINE> <INDENT> settings = ( ("format", "format string used for output."), ("coin", "cryptocurrency to fetch"), ("currency", "fiat currency to show fiscal data"), ("symbol", "coin symbol"), ("interval", "update interval in seconds"), ("status_interval", "percent change status in the last: '1h' / '24h' / '7d'") ) <NEW_LINE> symbol = "¤" <NEW_LINE> format = "{symbol} {price}{status}" <NEW_LINE> coin = "ethereum" <NEW_LINE> currency = "USD" <NEW_LINE> interval = 600 <NEW_LINE> status_interval = "24h" <NEW_LINE> def fetch_data(self): <NEW_LINE> <INDENT> response = requests.get("https://api.coinmarketcap.com/v1/ticker/{}/?convert={}".format(self.coin, self.currency)) <NEW_LINE> coin_data = response.json()[0] <NEW_LINE> coin_data["price"] = coin_data.pop("price_{}".format(self.currency.lower())) <NEW_LINE> coin_data["24h_volume"] = coin_data.pop("24h_volume_{}".format(self.currency.lower())) <NEW_LINE> coin_data["market_cap"] = coin_data.pop("market_cap_{}".format(self.currency.lower())) <NEW_LINE> coin_data["symbol"] = self.symbol <NEW_LINE> return coin_data <NEW_LINE> <DEDENT> def set_status(self, change): <NEW_LINE> <INDENT> if change > 10: <NEW_LINE> <INDENT> return '⮅' <NEW_LINE> <DEDENT> elif change > 0: <NEW_LINE> <INDENT> return '⭡' <NEW_LINE> <DEDENT> elif change < -10: <NEW_LINE> <INDENT> return '⮇' <NEW_LINE> <DEDENT> elif change < 0: <NEW_LINE> <INDENT> return '⭣' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> <DEDENT> @require(internet) <NEW_LINE> def run(self): <NEW_LINE> <INDENT> fdict = self.fetch_data() <NEW_LINE> symbols = dict(bitcoin='฿', ethereum='Ξ', litecoin='Ł', dash='Đ') <NEW_LINE> if self.coin in symbols: <NEW_LINE> <INDENT> fdict["symbol"] = symbols[self.coin] <NEW_LINE> <DEDENT> fdict["status"] = self.set_status(float(fdict["percent_change_{}".format(self.status_interval)])) <NEW_LINE> self.data = fdict <NEW_LINE> self.output = {"full_text": self.format.format(**fdict)}
Fetches live data of all cryptocurrencies availible at coinmarketcap <https://coinmarketcap.com/>. Coin setting should be equal to the 'id' field of your coin in <https://api.coinmarketcap.com/v1/ticker/>. Example coin settings: bitcoin, bitcoin-cash, ethereum, litecoin, dash, lisk. Example currency settings: usd, eur, huf. .. rubric:: Available formatters * {symbol} * {price} * {rank} * {24h_volume} * {market_cap} * {available_supply} * {total_supply} * {max_supply} * {percent_change_1h} * {percent_change_24h} * {percent_change_7d} * {last_updated} - time of last update on the API's part * {status}
62598fb84f88993c371f05a3
class LinReg(): <NEW_LINE> <INDENT> def __init__(self, x, y): <NEW_LINE> <INDENT> self.x = x <NEW_LINE> self.X = x[:, np.newaxis] <NEW_LINE> self.y = y <NEW_LINE> self.sklearn_lr = LinearRegression() <NEW_LINE> self.sklearn_lr = self.sklearn_lr.fit(self.X, self.y) <NEW_LINE> self.y_pred = self.sklearn_lr.predict(self.X) <NEW_LINE> self.r2 = r2_score(self.y, self.y_pred) <NEW_LINE> self.sklearn_coef = self.sklearn_lr.coef_ <NEW_LINE> self.sklearn_intercept = self.sklearn_lr.intercept_ <NEW_LINE> self.residuals = self.y - self.y_pred <NEW_LINE> self.st_slope, self.st_intercept, self.st_rvalue, self.st_pvalue, self.st_stderr = st.linregress(self.x,self.y) <NEW_LINE> <DEDENT> def plot(self): <NEW_LINE> <INDENT> fig, ax = plt.subplots(figsize=[7,5]) <NEW_LINE> MyPlot.scatter(ax, self.x, self.y) <NEW_LINE> ax.plot(self.x, self.y_pred, linewidth=1, color="#fcc500") <NEW_LINE> MyPlot.bg(ax) <NEW_LINE> MyPlot.title(ax, "Scatterplot + Linear regression") <NEW_LINE> MyPlot.border(ax) <NEW_LINE> plt.show() <NEW_LINE> <DEDENT> def residuals_distribution(self): <NEW_LINE> <INDENT> univ = Univa(self.residuals) <NEW_LINE> univ.describe() <NEW_LINE> univ.distribution(bins=9)
A class to realize linear regressions.
62598fb84a966d76dd5ef004
class Post(models.Model): <NEW_LINE> <INDENT> title = models.CharField(max_length=70) <NEW_LINE> body = models.TextField() <NEW_LINE> created_time = models.DateTimeField() <NEW_LINE> modified_time = models.DateTimeField() <NEW_LINE> excerpt = models.CharField(max_length=200,blank=True) <NEW_LINE> category = models.ForeignKey(Category) <NEW_LINE> tags = models.ManyToManyField(Tag,blank=True) <NEW_LINE> author = models.ForeignKey(User) <NEW_LINE> views = models.PositiveIntegerField(default=0) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.title <NEW_LINE> <DEDENT> def get_absolute_url(self): <NEW_LINE> <INDENT> return reverse('myblog:detail',kwargs={'pk':self.pk}) <NEW_LINE> <DEDENT> def increase_views(self): <NEW_LINE> <INDENT> self.views +=1 <NEW_LINE> self.save(update_fields=['views']) <NEW_LINE> <DEDENT> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> if not self.excerpt: <NEW_LINE> <INDENT> md = markdown.Markdown(extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', ]) <NEW_LINE> self.excerpt = strip_tags(md.convert(self.body))[:54] <NEW_LINE> <DEDENT> super(Post, self).save(*args, **kwargs) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> ordering = ['-created_time']
文章涉及的字段多
62598fb821bff66bcd722d96
class AbstractCamera(ABC): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.zoom = 45.0 <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def lookAround(self, xoffset: float, yoffset: float, pitchBound: bool): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def zoomInOut(self, yoffset: float, zoomBound=45.0): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def getViewMatrix(self): <NEW_LINE> <INDENT> raise NotImplementedError
An abstract camera class
62598fb8d7e4931a7ef3c1c3
class BitFieldCreator: <NEW_LINE> <INDENT> def __init__(self, field): <NEW_LINE> <INDENT> self.field = field <NEW_LINE> <DEDENT> def __set__(self, obj, value): <NEW_LINE> <INDENT> obj.__dict__[self.field.name] = self.field.to_python(value) <NEW_LINE> <DEDENT> def __get__(self, obj, type=None): <NEW_LINE> <INDENT> if obj is None: <NEW_LINE> <INDENT> return BitFieldFlags(self.field.flags) <NEW_LINE> <DEDENT> retval = obj.__dict__[self.field.name] <NEW_LINE> if self.field.__class__ is BitField: <NEW_LINE> <INDENT> retval._keys = self.field.flags <NEW_LINE> <DEDENT> return retval
A placeholder class that provides a way to set the attribute on the model. Descriptor for BitFields. Checks to make sure that all flags of the instance match the class. This is to handle the case when caching an older version of the instance and a newer version of the class is available (usually during deploys).
62598fb8ec188e330fdf89be
class BillingAddressResponse(object): <NEW_LINE> <INDENT> def __init__(self, response_code=None, billing_address=None): <NEW_LINE> <INDENT> self.swagger_types = { 'response_code': 'int', 'billing_address': 'BillingAddress' } <NEW_LINE> self.attribute_map = { 'response_code': 'ResponseCode', 'billing_address': 'BillingAddress' } <NEW_LINE> self._response_code = response_code <NEW_LINE> self._billing_address = billing_address <NEW_LINE> <DEDENT> @property <NEW_LINE> def response_code(self): <NEW_LINE> <INDENT> return self._response_code <NEW_LINE> <DEDENT> @response_code.setter <NEW_LINE> def response_code(self, response_code): <NEW_LINE> <INDENT> self._response_code = response_code <NEW_LINE> <DEDENT> @property <NEW_LINE> def billing_address(self): <NEW_LINE> <INDENT> return self._billing_address <NEW_LINE> <DEDENT> @billing_address.setter <NEW_LINE> def billing_address(self, billing_address): <NEW_LINE> <INDENT> self._billing_address = billing_address <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, BillingAddressResponse): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
62598fb8e5267d203ee6ba2c
class QuantuminoSolver(SageObject): <NEW_LINE> <INDENT> def __init__(self, aside, box=(5,8,2)): <NEW_LINE> <INDENT> if not 0 <= aside < 17: <NEW_LINE> <INDENT> raise ValueError("aside (=%s) must be between 0 and 16" % aside) <NEW_LINE> <DEDENT> self._aside = aside <NEW_LINE> self._box = box <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> s = "Quantumino solver for the box %s\n" % (self._box, ) <NEW_LINE> s += "Aside pentamino number: %s" % self._aside <NEW_LINE> return s <NEW_LINE> <DEDENT> def tiling_solver(self): <NEW_LINE> <INDENT> pieces = pentaminos[:self._aside] + pentaminos[self._aside+1:] <NEW_LINE> return TilingSolver(pieces, box=self._box) <NEW_LINE> <DEDENT> def solve(self, partial=None): <NEW_LINE> <INDENT> T = self.tiling_solver() <NEW_LINE> aside = pentaminos[self._aside] <NEW_LINE> for pentos in T.solve(partial=partial): <NEW_LINE> <INDENT> yield QuantuminoState(pentos, aside) <NEW_LINE> <DEDENT> <DEDENT> def number_of_solutions(self): <NEW_LINE> <INDENT> return self.tiling_solver().number_of_solutions()
Return the Quantumino solver for the given box where one of the pentamino is put aside. INPUT: - ``aside`` - integer, from 0 to 16, the aside pentamino - ``box`` - tuple of size three (optional, default: ``(5,8,2)``), size of the box EXAMPLES:: sage: from sage.games.quantumino import QuantuminoSolver sage: QuantuminoSolver(9) Quantumino solver for the box (5, 8, 2) Aside pentamino number: 9 sage: QuantuminoSolver(12, box=(5,4,4)) Quantumino solver for the box (5, 4, 4) Aside pentamino number: 12
62598fb88a43f66fc4bf22a8
class BaseReader(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.source_file = getattr(settings, 'SVG_ICONS_SOURCE_FILE') <NEW_LINE> if not self.source_file: <NEW_LINE> <INDENT> raise SVGReaderError( "SVG_ICONS_SOURCE_FILE needs to be defined for icons to work.") <NEW_LINE> <DEDENT> self.svg_path_data = self.read_source_file() <NEW_LINE> <DEDENT> def read_source_file(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def get_svg_paths(self, icon_name): <NEW_LINE> <INDENT> path_data = self.svg_path_data.get(icon_name) <NEW_LINE> if not path_data: <NEW_LINE> <INDENT> raise SVGReaderError( "No path data found for icon {}".format(icon_name)) <NEW_LINE> <DEDENT> return path_data
Base reader class not for direct use Subclass this to have your own implementation, the class to use can be defined in the settings with SVG_ICONS_READER_CLASS
62598fb8498bea3a75a57c50
class Conta(): <NEW_LINE> <INDENT> def __init__(self, titular, numero, saldo=0): <NEW_LINE> <INDENT> self.titular = titular <NEW_LINE> self.numero = numero <NEW_LINE> self.saldo = saldo <NEW_LINE> self.taxa = 0.5 <NEW_LINE> <DEDENT> def depositar(self, valor): <NEW_LINE> <INDENT> self.saldo += valor <NEW_LINE> return self.saldo <NEW_LINE> <DEDENT> def sacar(self, valor): <NEW_LINE> <INDENT> if self.saldo >= (valor + self.taxa): <NEW_LINE> <INDENT> self.saldo -= (valor+ self.taxa) <NEW_LINE> return 'Saque realizado com sucesso!' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("Saldo insuficiente: {}".format(self.saldo)) <NEW_LINE> <DEDENT> <DEDENT> def transferir(self, valor, conta): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.sacar(valor) <NEW_LINE> conta.depositar(valor) <NEW_LINE> return "Transferência realizada com sucesso! :)" <NEW_LINE> <DEDENT> except ValueError as e: <NEW_LINE> <INDENT> print(e) <NEW_LINE> return "Não foi possível realizar a tranferência. :(" <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> return "Conta destino inválida! :(" <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "Conta: {} Titular: {}".format(self.numero, self.titular)
Tentando abstrair uma conta corrente
62598fb85fc7496912d48312
class ShowLogging(ShowLogging_iosxe): <NEW_LINE> <INDENT> pass
Parser for: * 'show logging' * 'show logging | include {include}' * 'show logging | exclude {exclude}'
62598fb866673b3332c304fd
class WebDetection(_messages.Message): <NEW_LINE> <INDENT> fullMatchingImages = _messages.MessageField('WebImage', 1, repeated=True) <NEW_LINE> pagesWithMatchingImages = _messages.MessageField('WebPage', 2, repeated=True) <NEW_LINE> partialMatchingImages = _messages.MessageField('WebImage', 3, repeated=True) <NEW_LINE> visuallySimilarImages = _messages.MessageField('WebImage', 4, repeated=True) <NEW_LINE> webEntities = _messages.MessageField('WebEntity', 5, repeated=True)
Relevant information for the image from the Internet. Fields: fullMatchingImages: Fully matching images from the Internet. Can include resized copies of the query image. pagesWithMatchingImages: Web pages containing the matching images from the Internet. partialMatchingImages: Partial matching images from the Internet. Those images are similar enough to share some key-point features. For example an original image will likely have partial matching for its crops. visuallySimilarImages: The visually similar image results. webEntities: Deduced entities from similar images on the Internet.
62598fb89f288636728188f2
class Unordered(object): <NEW_LINE> <INDENT> def __init__(self, value, extractor): <NEW_LINE> <INDENT> self.value = value <NEW_LINE> self.extractor = extractor <NEW_LINE> self.node_type = self._node_type() <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> table = self.value['table_'] <NEW_LINE> if table['buckets_']: <NEW_LINE> <INDENT> return int(table['size_']) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> table = self.value['table_'] <NEW_LINE> buckets = table['buckets_'] <NEW_LINE> if buckets: <NEW_LINE> <INDENT> first = table['cached_begin_bucket_'] <NEW_LINE> last = buckets + table['bucket_count_'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> first = last = None <NEW_LINE> <DEDENT> return self._iterator(first, last, self.node_type, self.extractor) <NEW_LINE> <DEDENT> def empty(self): <NEW_LINE> <INDENT> return not self.value['table_']['buckets_'] <NEW_LINE> <DEDENT> def _node_type(self): <NEW_LINE> <INDENT> hash_table = self.value['table_'].type.fields()[0] <NEW_LINE> assert hash_table.is_base_class <NEW_LINE> hash_buckets = hash_table.type.fields()[0] <NEW_LINE> assert hash_buckets.is_base_class <NEW_LINE> node_type = gdb.lookup_type("%s::node" % hash_buckets.type) <NEW_LINE> assert node_type != None <NEW_LINE> return node_type <NEW_LINE> <DEDENT> class _iterator(six.Iterator): <NEW_LINE> <INDENT> def __init__(self, first_bucket, last_bucket, node_type, extractor): <NEW_LINE> <INDENT> self.bucket = first_bucket <NEW_LINE> self.last_bucket = last_bucket <NEW_LINE> self.node = self.bucket <NEW_LINE> self.node_type = node_type <NEW_LINE> self.value_type = self._value_type() <NEW_LINE> self.extractor = extractor <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __next__(self): <NEW_LINE> <INDENT> if self.node: <NEW_LINE> <INDENT> self.node = self.node.dereference()['next_'] <NEW_LINE> <DEDENT> if not self.node: <NEW_LINE> <INDENT> while not self.node and self.bucket != self.last_bucket: <NEW_LINE> <INDENT> self.bucket += 1 <NEW_LINE> self.node = self.bucket.dereference()['next_'] <NEW_LINE> <DEDENT> <DEDENT> if not self.node or self.node == self.bucket: <NEW_LINE> <INDENT> raise StopIteration() <NEW_LINE> <DEDENT> mapped = self._value() <NEW_LINE> return (self.extractor.key(mapped), self.extractor.value(mapped)) <NEW_LINE> <DEDENT> def _value(self): <NEW_LINE> <INDENT> assert self.node != self.bucket <NEW_LINE> assert self.node != None <NEW_LINE> node = self.node.dereference().cast(self.node_type) <NEW_LINE> return node['data_'].cast(self.value_type) <NEW_LINE> <DEDENT> def _value_type(self): <NEW_LINE> <INDENT> value_base = self.node_type.fields()[1] <NEW_LINE> assert value_base.is_base_class <NEW_LINE> return value_base.type.template_argument(0)
Common representation of Boost.Unordered types
62598fb83d592f4c4edbafef
class GreetFriendView(FormView): <NEW_LINE> <INDENT> form_class = GreetingForm <NEW_LINE> template_name = 'response.html' <NEW_LINE> def get(self, request): <NEW_LINE> <INDENT> error_msg = 'HTTP GET is not supported' <NEW_LINE> logger.error(error_msg) <NEW_LINE> return self.render_error(error_msg, 400) <NEW_LINE> <DEDENT> def post(self, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> data = None <NEW_LINE> for item in request: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> data = json.loads(item) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> error_msg = " ".join([ "JSON decoding error", "(a valid JSON string expected in POST request)", ]) <NEW_LINE> logger.error("%s: %s (%s)", error_msg, e.message, type(e)) <NEW_LINE> return self.render_error(error_msg, 400) <NEW_LINE> <DEDENT> break <NEW_LINE> <DEDENT> if not data: <NEW_LINE> <INDENT> error_msg = "No JSON data found in request" <NEW_LINE> logger.error(error_msg) <NEW_LINE> return self.render_error(error_msg, 400) <NEW_LINE> <DEDENT> form = self.form_class(data) <NEW_LINE> if form.is_valid(): <NEW_LINE> <INDENT> data = form.cleaned_data <NEW_LINE> logger_msg = "Friend {name} will be greeted on {when}".format( name=data['name'], when=data['datetime'].ctime() ) <NEW_LINE> logger.info(logger_msg) <NEW_LINE> td_delay = data['datetime'] - datetime.utcnow() <NEW_LINE> self.send_greeting(data['name'], td_delay) <NEW_LINE> return render( request, self.template_name, {'message': logger_msg} ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logger.error(form.errors) <NEW_LINE> return self.render_error(form.errors, 400) <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> error_msg = " ".join([ "We've encountered an expected error.", "Please try again!", ]) <NEW_LINE> logger.error("Fatal error: %s (%s)", e.message, type(e)) <NEW_LINE> return self.render_error(error_msg, 500) <NEW_LINE> <DEDENT> <DEDENT> def send_greeting(self, name, td_delay): <NEW_LINE> <INDENT> tasks.greet_friend.apply_async( (name,), countdown=td_delay.total_seconds() ) <NEW_LINE> <DEDENT> def render_error(self, error_msg, status_code): <NEW_LINE> <INDENT> return render_to_response( self.template_name, {'message': error_msg}, status=status_code )
Django view that serves the endpoint (greet/)
62598fb83539df3088ecc3db
class EncoderDecoder(nn.Block): <NEW_LINE> <INDENT> def __init__(self, encoder, decoder, src_embed, trg_embed, generator): <NEW_LINE> <INDENT> super(EncoderDecoder, self).__init__() <NEW_LINE> self.encoder = encoder <NEW_LINE> self.decoder = decoder <NEW_LINE> self.src_embed = src_embed <NEW_LINE> self.trg_embed = trg_embed <NEW_LINE> self.generator = generator <NEW_LINE> <DEDENT> def forward(self, src, trg, src_mask = None, trg_mask = None): <NEW_LINE> <INDENT> memory = self.encode(src, src_mask) <NEW_LINE> return self.decode(memory, src_mask, trg, trg_mask) <NEW_LINE> <DEDENT> def encode(self, src, src_mask): <NEW_LINE> <INDENT> return self.encoder(self.src_embed(src), src_mask) <NEW_LINE> <DEDENT> def decode(self, memory, src_mask, trg, trg_mask): <NEW_LINE> <INDENT> x = self.decoder(self.trg_embed(trg), memory, src_mask, trg_mask) <NEW_LINE> _x = x.reshape(-1, x.shape[-1]) <NEW_LINE> _x = self.generator(_x) <NEW_LINE> _x = _x.reshape(x.shape[0], x.shape[1], self.generator.vocab) <NEW_LINE> return _x
A standard Encoder-Decoder architecture.
62598fb863b5f9789fe8529c
class RenderObservations(gym.Wrapper): <NEW_LINE> <INDENT> def __init__(self, env): <NEW_LINE> <INDENT> super(RenderObservations, self).__init__(env) <NEW_LINE> if "rgb_array" not in self.metadata["render.modes"]: <NEW_LINE> <INDENT> self.metadata["render.modes"].append("rgb_array") <NEW_LINE> <DEDENT> <DEDENT> def step(self, action): <NEW_LINE> <INDENT> ret = self.env.step(action) <NEW_LINE> self.last_observation = ret[0] <NEW_LINE> return ret <NEW_LINE> <DEDENT> def reset(self, **kwargs): <NEW_LINE> <INDENT> self.last_observation = self.env.reset(**kwargs) <NEW_LINE> return self.last_observation <NEW_LINE> <DEDENT> def render(self, mode="human", **kwargs): <NEW_LINE> <INDENT> assert mode == "rgb_array" <NEW_LINE> return self.last_observation
Add observations rendering in 'rgb_array' mode.
62598fb871ff763f4b5e78a6
class ServerErrorMiddleware: <NEW_LINE> <INDENT> def __init__( self, app: ASGIApp, handler: typing.Callable = None, debug: bool = False ) -> None: <NEW_LINE> <INDENT> self.app = app <NEW_LINE> self.handler = handler <NEW_LINE> self.debug = debug <NEW_LINE> <DEDENT> def __call__(self, scope: Scope) -> ASGIInstance: <NEW_LINE> <INDENT> if scope["type"] != "http": <NEW_LINE> <INDENT> return self.app(scope) <NEW_LINE> <DEDENT> return functools.partial(self.asgi, scope=scope) <NEW_LINE> <DEDENT> async def asgi(self, receive: Receive, send: Send, scope: Scope) -> None: <NEW_LINE> <INDENT> response_started = False <NEW_LINE> async def _send(message: Message) -> None: <NEW_LINE> <INDENT> nonlocal response_started, send <NEW_LINE> if message["type"] == "http.response.start": <NEW_LINE> <INDENT> response_started = True <NEW_LINE> <DEDENT> await send(message) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> asgi = self.app(scope) <NEW_LINE> await asgi(receive, _send) <NEW_LINE> <DEDENT> except Exception as exc: <NEW_LINE> <INDENT> if not response_started: <NEW_LINE> <INDENT> request = Request(scope) <NEW_LINE> if self.debug: <NEW_LINE> <INDENT> response = self.debug_response(request, exc) <NEW_LINE> <DEDENT> elif self.handler is None: <NEW_LINE> <INDENT> response = self.error_response(request, exc) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if asyncio.iscoroutinefunction(self.handler): <NEW_LINE> <INDENT> response = await self.handler(request, exc) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> response = await run_in_threadpool(self.handler, request, exc) <NEW_LINE> <DEDENT> <DEDENT> await response(receive, send) <NEW_LINE> <DEDENT> raise exc from None <NEW_LINE> <DEDENT> <DEDENT> def genenrate_frame_html(self, frame: traceback.FrameSummary) -> str: <NEW_LINE> <INDENT> values = { "frame_filename": frame.filename, "frame_lineno": frame.lineno, "frame_name": frame.name, "frame_line": frame.line, } <NEW_LINE> return FRAME_TEMPLATE.format(**values) <NEW_LINE> <DEDENT> def generate_html(self, exc: Exception) -> str: <NEW_LINE> <INDENT> traceback_obj = traceback.TracebackException.from_exception( exc, capture_locals=True ) <NEW_LINE> exc_html = "".join( self.genenrate_frame_html(frame) for frame in traceback_obj.stack ) <NEW_LINE> error = f"{traceback_obj.exc_type.__name__}: {traceback_obj}" <NEW_LINE> return TEMPLATE.format(styles=STYLES, error=error, exc_html=exc_html) <NEW_LINE> <DEDENT> def generate_plain_text(self, exc: Exception) -> str: <NEW_LINE> <INDENT> return "".join(traceback.format_tb(exc.__traceback__)) <NEW_LINE> <DEDENT> def debug_response(self, request: Request, exc: Exception) -> Response: <NEW_LINE> <INDENT> accept = request.headers.get("accept", "") <NEW_LINE> if "text/html" in accept: <NEW_LINE> <INDENT> content = self.generate_html(exc) <NEW_LINE> return HTMLResponse(content, status_code=500) <NEW_LINE> <DEDENT> content = self.generate_plain_text(exc) <NEW_LINE> return PlainTextResponse(content, status_code=500) <NEW_LINE> <DEDENT> def error_response(self, request: Request, exc: Exception) -> Response: <NEW_LINE> <INDENT> return PlainTextResponse("Internal Server Error", status_code=500)
Handles returning 500 responses when a server error occurs. If 'debug' is set, then traceback responses will be returned, otherwise the designated 'handler' will be called. This middleware class should generally be used to wrap *everything* else up, so that unhandled exceptions anywhere in the stack always result in an appropriate 500 response.
62598fb844b2445a339b6a0b
class ScheduleExecution(base.Resource): <NEW_LINE> <INDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<Execution: %s>" % self.name
ScheduleExecution is a resource used to hold information about the execution of a scheduled backup.
62598fb8bf627c535bcb15d2
class MyTasks(My, Votes): <NEW_LINE> <INDENT> label = _("My tasks") <NEW_LINE> column_names = "votable_overview workflow_buttons *" <NEW_LINE> order_by = ['-priority', '-id'] <NEW_LINE> filter_vote_states = "assigned done" <NEW_LINE> filter_ticket_states = "opened started talk"
Show my votes in states assigned and done
62598fb821bff66bcd722d98
@dataclass <NEW_LINE> class PointSource(BaseSimulation): <NEW_LINE> <INDENT> alpha: float = 1.0 <NEW_LINE> amplitude: float = 1.0 <NEW_LINE> frequency: int = 1 <NEW_LINE> p: float = 0.99 <NEW_LINE> r: float = 0.01 <NEW_LINE> seasonal_move: int = 0 <NEW_LINE> seed: Optional[int] = None <NEW_LINE> trend: float = 0.0 <NEW_LINE> def simulate( self, length: int, state_weight: float = 0, state: Optional[Sequence[int]] = None, ) -> pd.DataFrame: <NEW_LINE> <INDENT> if self.seed: <NEW_LINE> <INDENT> base.set_seed(self.seed) <NEW_LINE> <DEDENT> simulated = surveillance.sim_pointSource( p=self.p, r=self.r, length=length, A=self.amplitude, alpha=self.alpha, beta=self.trend, phi=self.seasonal_move, frequency=self.frequency, state=robjects.NULL if state is None else robjects.IntVector(state), K=state_weight, ) <NEW_LINE> simulated_as_frame = r_list_to_frame(simulated, ["observed", "state"]) <NEW_LINE> return simulated_as_frame.pipe(add_date_time_index_to_frame).rename( columns={"observed": "n_cases", "state": "is_outbreak"} )
Simulation of epidemics which were introduced by point sources. The basis of this programme is a combination of a Hidden Markov Model (to get random time points for outbreaks) and a simple model (compare :class:`epysurv.simulation.SeasonalNoise`) to simulate the baseline. Parameters ---------- amplitude Amplitude of the sine. Determines the possible range of simulated seasonal cases. alpha Parameter to move along the y-axis (negative values are not allowed) with `alpha` >= `amplitude`. frequency Factor in oscillation term. Is multiplied with the annual term :math:`\omega` and the current time point. p Probability to get a new outbreak at time :math:`t` if there was one at time :math:`t-1`. r Probability to get no new outbreak at time :math:`t` if there was none at time :math:`t-1`. seasonal_move A term added to time point :math:`t` to move the curve along the x-axis. seed Seed for the random number generation. trend Controls the influence of the current week on :math:`\mu`. References ---------- http://surveillance.r-forge.r-project.org/
62598fb85166f23b2e24350b
class JMModel: <NEW_LINE> <INDENT> def __init__(self, text): <NEW_LINE> <INDENT> token = preprocessing(text) <NEW_LINE> self.totalword = len(token) <NEW_LINE> self.wordCounter = Counter(token) <NEW_LINE> calProb = lambda value: float(value) / self.totalword <NEW_LINE> self.probdict = { name: calProb(value) for name, value in self.wordCounter.items()} <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> del self.wordCounter <NEW_LINE> del self.totalword <NEW_LINE> del self.probdict <NEW_LINE> <DEDENT> def save(self, location): <NEW_LINE> <INDENT> with open(location, 'wb') as save: <NEW_LINE> <INDENT> pickle.dump(self, save, protocol=pickle.HIGHEST_PROTOCOL) <NEW_LINE> <DEDENT> <DEDENT> def wordProb(self, word): <NEW_LINE> <INDENT> if word in self.probdict: <NEW_LINE> <INDENT> return self.probdict[word] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 0
class of language models members : token(list) : text tokenize into 1 word totalword(int) : total word count wordCounter(Counter) : Counter of every word count calProb(function) : the way to calculate(smoothing) probability probdict(dictionary) : dict of word : prob
62598fb867a9b606de546100
class LoveCalculator(Cog): <NEW_LINE> <INDENT> @in_month(Month.FEBRUARY) <NEW_LINE> @commands.command(aliases=("love_calculator", "love_calc")) <NEW_LINE> @commands.cooldown(rate=1, per=5, type=commands.BucketType.user) <NEW_LINE> async def love(self, ctx: commands.Context, who: Member, whom: Optional[Member] = None) -> None: <NEW_LINE> <INDENT> if ( Lovefest.role_id not in [role.id for role in who.roles] or (whom is not None and Lovefest.role_id not in [role.id for role in whom.roles]) ): <NEW_LINE> <INDENT> raise BadArgument( "This command can only be ran against members with the lovefest role! " "This role be can assigned by running " f"`{PYTHON_PREFIX}subscribe` in <#{Channels.bot_commands}>." ) <NEW_LINE> <DEDENT> if whom is None: <NEW_LINE> <INDENT> whom = ctx.author <NEW_LINE> <DEDENT> def normalize(arg: Member) -> Coroutine: <NEW_LINE> <INDENT> return clean_content(escape_markdown=True).convert(ctx, str(arg)) <NEW_LINE> <DEDENT> who, whom = sorted([await normalize(arg) for arg in (who, whom)]) <NEW_LINE> m = hashlib.sha256(who.encode() + whom.encode()) <NEW_LINE> love_percent = sum(m.digest()) % 101 <NEW_LINE> love_threshold = [threshold for threshold, _ in LOVE_DATA] <NEW_LINE> index = bisect.bisect(love_threshold, love_percent) - 1 <NEW_LINE> _, data = LOVE_DATA[index] <NEW_LINE> status = random.choice(data["titles"]) <NEW_LINE> embed = discord.Embed( title=status, description=f"{who} \N{HEAVY BLACK HEART} {whom} scored {love_percent}%!\n\u200b", color=discord.Color.dark_magenta() ) <NEW_LINE> embed.add_field( name="A letter from Dr. Love:", value=data["text"] ) <NEW_LINE> embed.set_footer(text=f"You can unsubscribe from lovefest by using {PYTHON_PREFIX}subscribe.") <NEW_LINE> await ctx.send(embed=embed)
A cog for calculating the love between two people.
62598fb81b99ca400228f5c8
@pulumi.output_type <NEW_LINE> class GetPeeringAttachmentResult: <NEW_LINE> <INDENT> def __init__(__self__, filters=None, id=None, peer_account_id=None, peer_region=None, peer_transit_gateway_id=None, tags=None, transit_gateway_id=None): <NEW_LINE> <INDENT> if filters and not isinstance(filters, list): <NEW_LINE> <INDENT> raise TypeError("Expected argument 'filters' to be a list") <NEW_LINE> <DEDENT> pulumi.set(__self__, "filters", filters) <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 peer_account_id and not isinstance(peer_account_id, str): <NEW_LINE> <INDENT> raise TypeError("Expected argument 'peer_account_id' to be a str") <NEW_LINE> <DEDENT> pulumi.set(__self__, "peer_account_id", peer_account_id) <NEW_LINE> if peer_region and not isinstance(peer_region, str): <NEW_LINE> <INDENT> raise TypeError("Expected argument 'peer_region' to be a str") <NEW_LINE> <DEDENT> pulumi.set(__self__, "peer_region", peer_region) <NEW_LINE> if peer_transit_gateway_id and not isinstance(peer_transit_gateway_id, str): <NEW_LINE> <INDENT> raise TypeError("Expected argument 'peer_transit_gateway_id' to be a str") <NEW_LINE> <DEDENT> pulumi.set(__self__, "peer_transit_gateway_id", peer_transit_gateway_id) <NEW_LINE> if tags and not isinstance(tags, dict): <NEW_LINE> <INDENT> raise TypeError("Expected argument 'tags' to be a dict") <NEW_LINE> <DEDENT> pulumi.set(__self__, "tags", tags) <NEW_LINE> if transit_gateway_id and not isinstance(transit_gateway_id, str): <NEW_LINE> <INDENT> raise TypeError("Expected argument 'transit_gateway_id' to be a str") <NEW_LINE> <DEDENT> pulumi.set(__self__, "transit_gateway_id", transit_gateway_id) <NEW_LINE> <DEDENT> @property <NEW_LINE> @pulumi.getter <NEW_LINE> def filters(self) -> Optional[Sequence['outputs.GetPeeringAttachmentFilterResult']]: <NEW_LINE> <INDENT> return pulumi.get(self, "filters") <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(name="peerAccountId") <NEW_LINE> def peer_account_id(self) -> str: <NEW_LINE> <INDENT> return pulumi.get(self, "peer_account_id") <NEW_LINE> <DEDENT> @property <NEW_LINE> @pulumi.getter(name="peerRegion") <NEW_LINE> def peer_region(self) -> str: <NEW_LINE> <INDENT> return pulumi.get(self, "peer_region") <NEW_LINE> <DEDENT> @property <NEW_LINE> @pulumi.getter(name="peerTransitGatewayId") <NEW_LINE> def peer_transit_gateway_id(self) -> str: <NEW_LINE> <INDENT> return pulumi.get(self, "peer_transit_gateway_id") <NEW_LINE> <DEDENT> @property <NEW_LINE> @pulumi.getter <NEW_LINE> def tags(self) -> Mapping[str, str]: <NEW_LINE> <INDENT> return pulumi.get(self, "tags") <NEW_LINE> <DEDENT> @property <NEW_LINE> @pulumi.getter(name="transitGatewayId") <NEW_LINE> def transit_gateway_id(self) -> str: <NEW_LINE> <INDENT> return pulumi.get(self, "transit_gateway_id")
A collection of values returned by getPeeringAttachment.
62598fb87b180e01f3e490e9
@dataclass <NEW_LINE> class DensePoseChartResultQuantized: <NEW_LINE> <INDENT> labels_uv_uint8: torch.Tensor <NEW_LINE> def to(self, device: torch.device): <NEW_LINE> <INDENT> labels_uv_uint8 = self.labels_uv_uint8.to(device) <NEW_LINE> return DensePoseChartResultQuantized(labels_uv_uint8=labels_uv_uint8)
DensePose results for chart-based methods represented by labels and quantized inner coordinates (U, V) of individual charts. Each chart is a 2D manifold that has an associated label and is parameterized by two coordinates U and V. Both U and V take values in [0, 1]. Quantized coordinates Uq and Vq have uint8 values which are obtained as: Uq = U * 255 (hence 0 <= Uq <= 255) Vq = V * 255 (hence 0 <= Vq <= 255) Thus the results are represented by one tensor: - labels_uv_uint8 (tensor [3, H, W] of uint8): contains estimated label and quantized coordinates Uq and Vq for each pixel of the detection bounding box of size (H, W)
62598fb8cc0a2c111447b13c
class SinglePotatoResource(Resource): <NEW_LINE> <INDENT> def get(self, id): <NEW_LINE> <INDENT> pot = Potatoes.query.filter_by(id=id).first() <NEW_LINE> current = { 'title': pot.type, 'image': pot.photo_path, 'price': float(pot.price_per_kilo), 'amount': float(pot.amount), 'description': pot.description, 'location': 'No location', 'owner': pot.owner, 'id': pot.id } <NEW_LINE> return [current] <NEW_LINE> <DEDENT> def patch(self, id): <NEW_LINE> <INDENT> pot = Potatoes.query.filter_by(id=id).first() <NEW_LINE> if request.form.get('amount'): <NEW_LINE> <INDENT> pot.amount = request.form.get('amount') <NEW_LINE> <DEDENT> db.session.commit()
Resource for geting and patching an individual potato
62598fb88a43f66fc4bf22aa
@api.route('/centers') <NEW_LINE> class CenterResource(Resource): <NEW_LINE> <INDENT> @token_required <NEW_LINE> @validate_json_request <NEW_LINE> def post(self): <NEW_LINE> <INDENT> request_data = request.get_json() <NEW_LINE> center_schema = CenterSchema( only=['name', 'image', 'created_at', 'updated_at']) <NEW_LINE> center_data = center_schema.load_object_into_schema(request_data) <NEW_LINE> validate_duplicate(Center, name=request_data['name'].title()) <NEW_LINE> center = Center(**center_data) <NEW_LINE> center.save() <NEW_LINE> return { 'status': 'success', 'message': SUCCESS_MESSAGES['created'].format('Center'), 'data': center_schema.dump(center).data }, 201
Resource class for creating and getting centers
62598fb897e22403b383b036
class MotionBlockSerializer(ModelSerializer): <NEW_LINE> <INDENT> agenda_type = IntegerField( write_only=True, required=False, min_value=1, max_value=3 ) <NEW_LINE> agenda_parent_id = IntegerField(write_only=True, required=False, min_value=1) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = MotionBlock <NEW_LINE> fields = ("id", "title", "agenda_item_id", "agenda_type", "agenda_parent_id") <NEW_LINE> <DEDENT> def create(self, validated_data): <NEW_LINE> <INDENT> agenda_type = validated_data.pop("agenda_type", None) <NEW_LINE> agenda_parent_id = validated_data.pop("agenda_parent_id", None) <NEW_LINE> motion_block = MotionBlock(**validated_data) <NEW_LINE> motion_block.agenda_item_update_information["type"] = agenda_type <NEW_LINE> motion_block.agenda_item_update_information["parent_id"] = agenda_parent_id <NEW_LINE> motion_block.save() <NEW_LINE> return motion_block
Serializer for motion.models.Category objects.
62598fb81f5feb6acb162d4f
class Properties: <NEW_LINE> <INDENT> def __init__(self, prob, query_len, match_lst, e_val): <NEW_LINE> <INDENT> self.prob = prob <NEW_LINE> self.query_len = query_len <NEW_LINE> self.match_lst = match_lst <NEW_LINE> self.e_val = e_val <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "{0} {1} {2} {3}".format(self.prob, self.query_len, self.match_lst, self.e_val) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return (isinstance(other, Properties)) and self.prob == other.prob and self.query_len == other.query_len and self.match_lst == other.match_lst and self.e_val == other.e_val
Fields prob: Str query_len: Str match_lst: listof Nat e_val: Str
62598fb8796e427e5384e8c5
class ScaledFloatFrame(gym.ObservationWrapper): <NEW_LINE> <INDENT> def observation(self, observation): <NEW_LINE> <INDENT> return np.array(observation).astype(np.float32)/255.0
The final wrapper we have in the library converts observation data from bytes to floats and scales every pixel's value to the range [0.0...1.0].
62598fb8851cf427c66b83e6
class QuanComparison(tables.IsDescription): <NEW_LINE> <INDENT> spec_id = tables.Int32Col(pos=0) <NEW_LINE> isolabel_id = tables.Int32Col(pos=1) <NEW_LINE> primary_inten = tables.Float64Col(pos=2) <NEW_LINE> primary_fit_c12 = tables.Float64Col(pos=2) <NEW_LINE> primary_ls = tables.Float64Col(pos=3) <NEW_LINE> primary_sum_ls = tables.Float64Col(pos=4) <NEW_LINE> secondary_inten = tables.Float64Col(pos=5) <NEW_LINE> secondary_fit_c12 = tables.Float64Col(pos=5) <NEW_LINE> secondary_ls = tables.Float64Col(pos=6) <NEW_LINE> secondary_sum_ls = tables.Float64Col(pos=7) <NEW_LINE> pcm = tables.StringCol(255, pos=8) <NEW_LINE> score = tables.Float64Col(pos=9)
@brief HDF5 table definition for quantification data table
62598fb87d847024c075c4ec
class AutoscaleErrorResponse(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'system_data': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'error': {'key': 'error', 'type': 'AutoscaleErrorResponseError'}, 'system_data': {'key': 'systemData', 'type': 'SystemData'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(AutoscaleErrorResponse, self).__init__(**kwargs) <NEW_LINE> self.error = kwargs.get('error', None) <NEW_LINE> self.system_data = None
Describes the format of Error response. Variables are only populated by the server, and will be ignored when sending a request. :param error: The error object. :type error: ~$(python-base-namespace).v2021_05_01_preview.models.AutoscaleErrorResponseError :ivar system_data: The system metadata related to the response. :vartype system_data: ~$(python-base-namespace).v2021_05_01_preview.models.SystemData
62598fb8379a373c97d99146
class CastroRedux(object): <NEW_LINE> <INDENT> def __init__(self, outfile_file, host, port = 5900, pwdfile = os.path.join(os.path.expanduser("~"), ".vnc", "passwd"), framerate = 12, keyframe = 120, clipping = None, logger_name = "CastroRedux", logger_log_dir = False, logger_level = "INFO"): <NEW_LINE> <INDENT> self.outfile_file = outfile_file <NEW_LINE> self.host = host <NEW_LINE> self.port = port <NEW_LINE> self.framerate = framerate <NEW_LINE> self.keyframe = keyframe <NEW_LINE> self.clipping = clipping <NEW_LINE> self.pwdfile = pwdfile <NEW_LINE> self.logger_level = logger_level <NEW_LINE> self.logger_name = logger_name <NEW_LINE> self.logger_log_dir = logger_log_dir <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> self.recorder = FlvRec( self.outfile_file, host = self.host, port = self.port, framerate = self.framerate, keyframe = self.keyframe, pwdfile = self.pwdfile, clipping = self.clipping, logger_name = self.logger_name, logger_log_dir = self.logger_log_dir, logger_level = self.logger_level ) <NEW_LINE> self.recorder.start() <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> self.recorder.stop()
CastroRedux vnc to flv recorder Attributes: outfile_file (str) host (str) port (int) pwdfile (str) framerate (int) keyframe (int) clipping (int) debug (bool)
62598fb832920d7e50bc617f
class ToolBack(ViewsPositionsBase): <NEW_LINE> <INDENT> description = 'Back to previous view' <NEW_LINE> image = 'back' <NEW_LINE> default_keymap = rcParams['keymap.back'] <NEW_LINE> _on_trigger = 'back'
Move back up the view lim stack
62598fb863b5f9789fe8529e
class WinkFanDevice(WinkDevice, FanEntity): <NEW_LINE> <INDENT> @asyncio.coroutine <NEW_LINE> def async_added_to_hass(self): <NEW_LINE> <INDENT> self.hass.data[DOMAIN]['entities']['fan'].append(self) <NEW_LINE> <DEDENT> def set_direction(self: ToggleEntity, direction: str) -> None: <NEW_LINE> <INDENT> self.wink.set_fan_direction(direction) <NEW_LINE> <DEDENT> def set_speed(self: ToggleEntity, speed: str) -> None: <NEW_LINE> <INDENT> self.wink.set_state(True, speed) <NEW_LINE> <DEDENT> def turn_on(self: ToggleEntity, speed: str = None, **kwargs) -> None: <NEW_LINE> <INDENT> self.wink.set_state(True, speed) <NEW_LINE> <DEDENT> def turn_off(self: ToggleEntity, **kwargs) -> None: <NEW_LINE> <INDENT> self.wink.set_state(False) <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_on(self): <NEW_LINE> <INDENT> return self.wink.state() <NEW_LINE> <DEDENT> @property <NEW_LINE> def speed(self) -> str: <NEW_LINE> <INDENT> current_wink_speed = self.wink.current_fan_speed() <NEW_LINE> if SPEED_AUTO == current_wink_speed: <NEW_LINE> <INDENT> return SPEED_AUTO <NEW_LINE> <DEDENT> if SPEED_LOWEST == current_wink_speed: <NEW_LINE> <INDENT> return SPEED_LOWEST <NEW_LINE> <DEDENT> if SPEED_LOW == current_wink_speed: <NEW_LINE> <INDENT> return SPEED_LOW <NEW_LINE> <DEDENT> if SPEED_MEDIUM == current_wink_speed: <NEW_LINE> <INDENT> return SPEED_MEDIUM <NEW_LINE> <DEDENT> if SPEED_HIGH == current_wink_speed: <NEW_LINE> <INDENT> return SPEED_HIGH <NEW_LINE> <DEDENT> return STATE_UNKNOWN <NEW_LINE> <DEDENT> @property <NEW_LINE> def current_direction(self): <NEW_LINE> <INDENT> return self.wink.current_fan_direction() <NEW_LINE> <DEDENT> @property <NEW_LINE> def speed_list(self: ToggleEntity) -> list: <NEW_LINE> <INDENT> wink_supported_speeds = self.wink.fan_speeds() <NEW_LINE> supported_speeds = [] <NEW_LINE> if SPEED_AUTO in wink_supported_speeds: <NEW_LINE> <INDENT> supported_speeds.append(SPEED_AUTO) <NEW_LINE> <DEDENT> if SPEED_LOWEST in wink_supported_speeds: <NEW_LINE> <INDENT> supported_speeds.append(SPEED_LOWEST) <NEW_LINE> <DEDENT> if SPEED_LOW in wink_supported_speeds: <NEW_LINE> <INDENT> supported_speeds.append(SPEED_LOW) <NEW_LINE> <DEDENT> if SPEED_MEDIUM in wink_supported_speeds: <NEW_LINE> <INDENT> supported_speeds.append(SPEED_MEDIUM) <NEW_LINE> <DEDENT> if SPEED_HIGH in wink_supported_speeds: <NEW_LINE> <INDENT> supported_speeds.append(SPEED_HIGH) <NEW_LINE> <DEDENT> return supported_speeds <NEW_LINE> <DEDENT> @property <NEW_LINE> def supported_features(self: ToggleEntity) -> int: <NEW_LINE> <INDENT> return SUPPORTED_FEATURES
Representation of a Wink fan.
62598fb80fa83653e46f5012
class RichTextarea(Textarea): <NEW_LINE> <INDENT> class Media: <NEW_LINE> <INDENT> js = [join(PAGES_MEDIA_URL, path) for path in ( 'javascript/jquery.js', )] <NEW_LINE> css = { 'all': [join(PAGES_MEDIA_URL, path) for path in ( 'css/rte.css', )] } <NEW_LINE> <DEDENT> def __init__(self, language=None, attrs=None, **kwargs): <NEW_LINE> <INDENT> attrs = {'class': 'rte'} <NEW_LINE> self.language = language <NEW_LINE> super(RichTextarea, self).__init__(attrs) <NEW_LINE> <DEDENT> def render(self, name, value, attrs=None, **kwargs): <NEW_LINE> <INDENT> rendered = super(RichTextarea, self).render(name, value, attrs) <NEW_LINE> context = { 'name': name, 'PAGES_MEDIA_URL': PAGES_MEDIA_URL, } <NEW_LINE> return rendered + mark_safe(render_to_string( 'pages/widgets/richtextarea.html', context))
A RichTextarea widget.
62598fb84428ac0f6e658652
class StaleTaskStatusException(ValueError): <NEW_LINE> <INDENT> pass
Raised when attempting to update the status of a task which was changed concurrently by another transaction.
62598fb844b2445a339b6a0c
class StatusReporter(object): <NEW_LINE> <INDENT> def __init__(self, duplicate_reporter=None): <NEW_LINE> <INDENT> self.__has_reported = False <NEW_LINE> if duplicate_reporter is None: <NEW_LINE> <INDENT> self.__fp = tempfile.TemporaryFile() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> source_fp = duplicate_reporter.__fp <NEW_LINE> assert not hasattr(source_fp, "file") <NEW_LINE> self.__fp = os.fdopen(os.dup(source_fp.fileno()), "w+b") <NEW_LINE> assert self.__fp.fileno() != source_fp.fileno() <NEW_LINE> <DEDENT> <DEDENT> def close(self): <NEW_LINE> <INDENT> self.__fp.close() <NEW_LINE> <DEDENT> def report_status(self, message): <NEW_LINE> <INDENT> encoded_message = message.encode("utf-8") <NEW_LINE> self.__fp.write(b"%d\n" % len(encoded_message)) <NEW_LINE> self.__fp.write(b"%s" % encoded_message) <NEW_LINE> self.__fp.flush() <NEW_LINE> <DEDENT> def read_status(self, timeout=None, timeout_status=None): <NEW_LINE> <INDENT> if timeout is not None: <NEW_LINE> <INDENT> deadline = time.time() + timeout <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> deadline = None <NEW_LINE> <DEDENT> while True: <NEW_LINE> <INDENT> if deadline is not None and time.time() > deadline: <NEW_LINE> <INDENT> return timeout_status <NEW_LINE> <DEDENT> self.__fp.seek(0) <NEW_LINE> num_bytes = self.__fp.readline() <NEW_LINE> if num_bytes != b"": <NEW_LINE> <INDENT> message = self.__fp.read() <NEW_LINE> if len(message) == int(num_bytes): <NEW_LINE> <INDENT> return message.decode("utf-8", "replace") <NEW_LINE> <DEDENT> <DEDENT> time.sleep(0.20) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def has_reported(self): <NEW_LINE> <INDENT> return self.__has_reported
Used to send back a status message to process A from process B where process A has forked process B. The status message is just a single string of text. This is implemented by writing and reading bytes out of a shared temporary file.
62598fb88a349b6b4368636d
class CourseDetialSerializer(ModelSerializer): <NEW_LINE> <INDENT> teacher = TeacherSerializer() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = Course <NEW_LINE> fields = ["id", "name", "course_img", "students", "lessons", "pub_lessons", "price", "teacher", "lesson_list","level_name","course_video","brief_image", "discount_name","real_price","active_time"]
课程列表
62598fb85166f23b2e24350d
class DyStockDataFocusAnalysisMainWindow(DyBasicMainWindow): <NEW_LINE> <INDENT> name = 'DyStockDataFocusAnalysisMainWindow' <NEW_LINE> def __init__(self, dataWindow, focusStrengthDf, focusInfoPoolDict): <NEW_LINE> <INDENT> super().__init__(None, None) <NEW_LINE> self._dataWindow = dataWindow <NEW_LINE> self._focusStrengthDf = focusStrengthDf <NEW_LINE> self._focusInfoPoolDict = focusInfoPoolDict <NEW_LINE> self._initUi() <NEW_LINE> <DEDENT> def _initUi(self): <NEW_LINE> <INDENT> self.setWindowTitle('热点分析') <NEW_LINE> self._initCentral() <NEW_LINE> self._initToolBar() <NEW_LINE> self._loadWindowSettings() <NEW_LINE> <DEDENT> def _initCentral(self): <NEW_LINE> <INDENT> widgetStats, dockStats = self._createDock(DyStockDataFocusAnalysisWidget, '热点强度', Qt.BottomDockWidgetArea, self._dataWindow, self._focusStrengthDf.copy(), self._focusInfoPoolDict) <NEW_LINE> <DEDENT> def _initToolBar(self): <NEW_LINE> <INDENT> toolBar = self.addToolBar('工具栏') <NEW_LINE> toolBar.setObjectName('工具栏') <NEW_LINE> action = QAction('画图', self) <NEW_LINE> action.triggered.connect(self._plotAct) <NEW_LINE> toolBar.addAction(action) <NEW_LINE> <DEDENT> def closeEvent(self, event): <NEW_LINE> <INDENT> return super().closeEvent(event) <NEW_LINE> <DEDENT> def _plotAct(self): <NEW_LINE> <INDENT> self._dataWindow.plotFocusStrength(DyStockCommon.shIndex, self._focusStrengthDf)
热点分析主窗口
62598fb8460517430c4320f6
class YamlSettings(JsonSettings): <NEW_LINE> <INDENT> def load_file(self, settings_file, extra_settings): <NEW_LINE> <INDENT> settings = yaml.safe_load(settings_file) <NEW_LINE> template_path = settings['path'] <NEW_LINE> parameters = settings['parameters'] <NEW_LINE> parameters.update(extra_settings) <NEW_LINE> self.load_template(open(template_path).read(), parameters)
A YamlSettings object is initiated with a yaml file, which has a 'path', indicating a json template file, and 'parameters', where we find a dictionary that we can pass to the template. This dictionary might contains parameters that override default parameters in the base class.
62598fb8d7e4931a7ef3c1c7
class CIFAR_100(object): <NEW_LINE> <INDENT> def unpickle(self, filename): <NEW_LINE> <INDENT> fo= open(filename, 'rb') <NEW_LINE> dictData=cPickle.load(fo) <NEW_LINE> fo.close() <NEW_LINE> return dictData <NEW_LINE> <DEDENT> def onehot_fine_labels(self, labels): <NEW_LINE> <INDENT> return np.eye(100)[labels] <NEW_LINE> <DEDENT> def onehot_coarse_labels(self, labels): <NEW_LINE> <INDENT> return np.eye(20)[labels] <NEW_LINE> <DEDENT> def structureImages(self, rawImage): <NEW_LINE> <INDENT> raw_float= np.array(rawImage, dtype=float) <NEW_LINE> images= raw_float.reshape([-1,3,32,32]) <NEW_LINE> images=images.transpose([0,2,3,1]) <NEW_LINE> return images <NEW_LINE> <DEDENT> def __init__(self): <NEW_LINE> <INDENT> testUrl="http://kashaaf.com/cifar-100-python/test" <NEW_LINE> trainUrl= "http://kashaaf.com/cifar-100-python/train" <NEW_LINE> opener= urllib.URLopener() <NEW_LINE> if not os.path.isfile('train'): <NEW_LINE> <INDENT> opener.retrieve(trainUrl, 'train') <NEW_LINE> <DEDENT> if not os.path.isfile('test'): <NEW_LINE> <INDENT> opener.retrieve(testUrl, 'test') <NEW_LINE> <DEDENT> self.x_train=self.unpickle('train')['data'] <NEW_LINE> self.x_test=self.unpickle('test')['data'] <NEW_LINE> self.y_fine_train=self.onehot_fine_labels(self.unpickle('train')['fine_labels']) <NEW_LINE> self.y_coarse_train=self.onehot_coarse_labels(self.unpickle('train')['coarse_labels']) <NEW_LINE> self.y_fine_test= self.onehot_fine_labels(self.unpickle('test')['fine_labels']) <NEW_LINE> self.y_coarse_test=self.onehot_coarse_labels(self.unpickle('test')['coarse_labels']) <NEW_LINE> self.fine_label_names= self.unpickle('meta')['fine_label_names'] <NEW_LINE> self.coarse_label_names= self.unpickle('meta')['coarse_label_names']
class for cifar 100
62598fb867a9b606de546103
class CreateDomainBatchResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.LogId = None <NEW_LINE> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.LogId = params.get("LogId") <NEW_LINE> self.RequestId = params.get("RequestId")
CreateDomainBatch返回参数结构体
62598fb856ac1b37e630231d
class UnknownAuthMethodError(Error): <NEW_LINE> <INDENT> pass
Raised when there's no method to call for a specific auth type
62598fb810dbd63aa1c70cea
class Preprocessing(): <NEW_LINE> <INDENT> def __init__(self, data, ): <NEW_LINE> <INDENT> self.xs = getattr(data, 'xs') <NEW_LINE> self.ys = getattr(data, 'ys') <NEW_LINE> self._initial() <NEW_LINE> <DEDENT> def _initial(self): <NEW_LINE> <INDENT> self.xs = self.xs.dropna() <NEW_LINE> self.ys = self.ys.dropna() <NEW_LINE> print('Dimensions of X: [%d, %d]' % ( len(self.xs), len(self.xs.ix[0])) ) <NEW_LINE> print('Features\n%s' % self.xs.columns) <NEW_LINE> print('Target\n%s' % self.ys.name) <NEW_LINE> <DEDENT> def get_standardized_training_test_split(self, test_size=0.4): <NEW_LINE> <INDENT> X_train, X_test, Y_train, Y_test = train_test_split(self.xs, self.ys, test_size=test_size) <NEW_LINE> scaler = StandardScaler() <NEW_LINE> scaler.fit(X_train) <NEW_LINE> X_train, X_test = scaler.transform(X_train), scaler.transform(X_test) <NEW_LINE> return X_train, X_test, Y_train, Y_test <NEW_LINE> <DEDENT> def get_training_test_split(self, test_size=0.4): <NEW_LINE> <INDENT> self.xs = add_constant(self.xs) <NEW_LINE> X_train, X_test, Y_train, Y_test = train_test_split(self.xs, self.ys, test_size=test_size) <NEW_LINE> return X_train, X_test, Y_train, Y_test
handles missing values and stores basic information about features
62598fb8e5267d203ee6ba30
class HeapPriorityQueue(PriorityQueueBase): <NEW_LINE> <INDENT> def _parent(self, j): <NEW_LINE> <INDENT> return (j-1) // 2 <NEW_LINE> <DEDENT> def _left(self, j): <NEW_LINE> <INDENT> return 2*j + 1 <NEW_LINE> <DEDENT> def _right(self, j): <NEW_LINE> <INDENT> return 2*j + 2 <NEW_LINE> <DEDENT> def _has_left(self, j): <NEW_LINE> <INDENT> return self._left(j) < len(self._data) <NEW_LINE> <DEDENT> def _has_right(self, j): <NEW_LINE> <INDENT> return self._right(j) < len(self._data) <NEW_LINE> <DEDENT> def _swep(self, i, j): <NEW_LINE> <INDENT> self._data[i], self._data[j] = self._data[j], self._data[i] <NEW_LINE> <DEDENT> def _upheap(self, j): <NEW_LINE> <INDENT> parent = self._parent(j) <NEW_LINE> if j > 0 and self._data[j] < self._data[parent]: <NEW_LINE> <INDENT> self._swep(j, parent) <NEW_LINE> self._upheap(parent) <NEW_LINE> <DEDENT> <DEDENT> def _downheap(self, j): <NEW_LINE> <INDENT> if self._has_left(j): <NEW_LINE> <INDENT> left = self._left(j) <NEW_LINE> small_child = left <NEW_LINE> if self._has_right(j): <NEW_LINE> <INDENT> right = self._right(j) <NEW_LINE> if self._data[right] < self._data[left]: <NEW_LINE> <INDENT> small_child = right <NEW_LINE> <DEDENT> <DEDENT> if self._data[small_child] < self._data[j]: <NEW_LINE> <INDENT> self._swep(j, small_child) <NEW_LINE> self._downheap(small_child) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __init__(self): <NEW_LINE> <INDENT> self._data = [] <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self._data) <NEW_LINE> <DEDENT> def add(self, key, value): <NEW_LINE> <INDENT> self._data.append(self._ltem(key, value)) <NEW_LINE> self._upheap(len(self._data) - 1) <NEW_LINE> <DEDENT> def min(self): <NEW_LINE> <INDENT> if self.is_empty(): <NEW_LINE> <INDENT> raise Empty('Priority queue is empty.') <NEW_LINE> <DEDENT> item = self._data[0] <NEW_LINE> return (item._key, item._value) <NEW_LINE> <DEDENT> def remove_min(self): <NEW_LINE> <INDENT> if self.is_empty(): <NEW_LINE> <INDENT> raise Empty('Priority queue is empty.') <NEW_LINE> <DEDENT> self._swep(0, len(self._data) - 1) <NEW_LINE> item = self._data.pop() <NEW_LINE> self._downheap(0) <NEW_LINE> return (item._key, item._value)
A min-oriented priority queue implemented with a binary heap.
62598fb897e22403b383b037
class BaseTemplate(templates.Template): <NEW_LINE> <INDENT> pass
Base template for all templates
62598fb8a8370b77170f0510
class ControllerTest(unittest.TestCase): <NEW_LINE> <INDENT> def testAssertNotNone(self): <NEW_LINE> <INDENT> controller = puremvc.core.Controller.getInstance() <NEW_LINE> self.assertNotEqual(None, controller) <NEW_LINE> <DEDENT> def testAssertIController(self): <NEW_LINE> <INDENT> controller = puremvc.core.Controller.getInstance() <NEW_LINE> self.assertEqual(True, isinstance(controller, puremvc.interfaces.IController)) <NEW_LINE> <DEDENT> def testRegisterAndExecuteCommand(self): <NEW_LINE> <INDENT> controller = puremvc.core.Controller.getInstance() <NEW_LINE> controller.registerCommand('ControllerTest', utils.controller.ControllerTestCommand) <NEW_LINE> vo = utils.controller.ControllerTestVO(12) <NEW_LINE> note = puremvc.patterns.observer.Notification('ControllerTest', vo) <NEW_LINE> controller.executeCommand(note) <NEW_LINE> self.assertEqual(True, vo.result == 24 ) <NEW_LINE> <DEDENT> def testRegisterAndRemoveCommand(self): <NEW_LINE> <INDENT> controller = puremvc.core.Controller.getInstance() <NEW_LINE> controller.registerCommand('ControllerRemoveTest', utils.controller.ControllerTestCommand) <NEW_LINE> vo = utils.controller.ControllerTestVO(12) <NEW_LINE> note = puremvc.patterns.observer.Notification('ControllerRemoveTest', vo) <NEW_LINE> controller.executeCommand(note) <NEW_LINE> self.assertEqual(True, vo.result == 24 ) <NEW_LINE> vo.result = 0 <NEW_LINE> controller.removeCommand('ControllerRemoveTest') <NEW_LINE> controller.executeCommand(note) <NEW_LINE> self.assertEqual(True, vo.result == 0) <NEW_LINE> <DEDENT> def testHasCommand(self): <NEW_LINE> <INDENT> controller = puremvc.core.Controller.getInstance() <NEW_LINE> controller.registerCommand('hasCommandTest', utils.controller.ControllerTestCommand) <NEW_LINE> self.assertEqual(True, controller.hasCommand('hasCommandTest')) <NEW_LINE> controller.removeCommand('hasCommandTest') <NEW_LINE> self.assertEqual(False, controller.hasCommand('hasCommandTest'))
ControllerTest: Test Controller Singleton
62598fb8e1aae11d1e7ce8bd
class FwNoStatusEntryError(FwErrorClass): <NEW_LINE> <INDENT> def __init__(self, missentry): <NEW_LINE> <INDENT> self.missing_entry = missentry
FwMissingStatusEntryError Raised when a module's status information in the controller status dict is requested but no valid entry is found.
62598fb801c39578d7f12eac
class GetShipmentTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.demo = utils.create_demo() <NEW_LINE> demo_json = loads(self.demo) <NEW_LINE> demo_guid = demo_json.get('guid') <NEW_LINE> demo_user_id = demo_json.get('users')[0].get('id') <NEW_LINE> auth_data = user_service.login(demo_guid, demo_user_id) <NEW_LINE> self.loopback_token = auth_data.get('loopback_token') <NEW_LINE> <DEDENT> def test_get_shipment_success(self): <NEW_LINE> <INDENT> shipments = shipment_service.get_shipments(self.loopback_token) <NEW_LINE> shipment_id = loads(shipments)[0].get('id') <NEW_LINE> shipment = shipment_service.get_shipment(self.loopback_token, shipment_id) <NEW_LINE> shipment_json = loads(shipment) <NEW_LINE> self.assertTrue(shipment_json.get('id')) <NEW_LINE> self.assertTrue(shipment_json.get('status')) <NEW_LINE> self.assertTrue(shipment_json.get('createdAt')) <NEW_LINE> self.assertTrue(shipment_json.get('estimatedTimeOfArrival')) <NEW_LINE> self.assertTrue(shipment_json.get('fromId')) <NEW_LINE> self.assertTrue(shipment_json.get('toId')) <NEW_LINE> if shipment_json.get('currentLocation'): <NEW_LINE> <INDENT> self.assertTrue(shipment_json.get('currentLocation').get('city')) <NEW_LINE> self.assertTrue(shipment_json.get('currentLocation').get('state')) <NEW_LINE> self.assertTrue(shipment_json.get('currentLocation').get('country')) <NEW_LINE> self.assertTrue(shipment_json.get('currentLocation').get('latitude')) <NEW_LINE> self.assertTrue(shipment_json.get('currentLocation').get('longitude')) <NEW_LINE> <DEDENT> for item_json in shipment_json.get('items'): <NEW_LINE> <INDENT> self.assertTrue(item_json.get('id')) <NEW_LINE> self.assertTrue(item_json.get('shipmentId')) <NEW_LINE> self.assertTrue(item_json.get('productId')) <NEW_LINE> self.assertTrue(item_json.get('quantity')) <NEW_LINE> <DEDENT> <DEDENT> def test_get_shipment_no_items_filter_success(self): <NEW_LINE> <INDENT> shipments = shipment_service.get_shipments(self.loopback_token) <NEW_LINE> shipment_id = loads(shipments)[0].get('id') <NEW_LINE> shipment = shipment_service.get_shipment(self.loopback_token, shipment_id, include_items="0") <NEW_LINE> self.assertFalse(loads(shipment).get('items')) <NEW_LINE> <DEDENT> def test_get_shipment_invalid_input(self): <NEW_LINE> <INDENT> self.assertRaises(ResourceDoesNotExistException, shipment_service.get_shipment, self.loopback_token, '123321') <NEW_LINE> <DEDENT> def test_get_shipment_invalid_token(self): <NEW_LINE> <INDENT> shipments = shipment_service.get_shipments(self.loopback_token) <NEW_LINE> shipment_id = loads(shipments)[0].get('id') <NEW_LINE> self.assertRaises(AuthenticationException, shipment_service.get_shipment, utils.get_bad_token(), shipment_id) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> utils.delete_demo(loads(self.demo).get('guid'))
Tests for `services/shipments.py - get_shipment()`.
62598fb89f288636728188f6
class OG_254: <NEW_LINE> <INDENT> play = ( Buff(SELF, "OG_254e") * Count(ENEMY_SECRETS), Destroy(ENEMY_SECRETS) )
Eater of Secrets
62598fb8851cf427c66b83e8
class InputNeuron(Neuron): <NEW_LINE> <INDENT> def __init__(self, value): <NEW_LINE> <INDENT> super(InputNeuron, self).__init__([]) <NEW_LINE> self.value = value <NEW_LINE> <DEDENT> def set_value(self, value): <NEW_LINE> <INDENT> self.value = value
Input neuron
62598fb892d797404e388bfc
class Giflib(AutotoolsPackage): <NEW_LINE> <INDENT> homepage = "http://giflib.sourceforge.net/" <NEW_LINE> url = "https://downloads.sourceforge.net/project/giflib/giflib-5.1.4.tar.bz2" <NEW_LINE> version('5.1.4', '2c171ced93c0e83bb09e6ccad8e3ba2b')
The GIFLIB project maintains the giflib service library, which has been pulling images out of GIFs since 1989.
62598fb832920d7e50bc6181