code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class SettingsItem(models.Model): <NEW_LINE> <INDENT> name = models.CharField('设置名', max_length=30) <NEW_LINE> value = models.CharField('值', max_length=200, blank=True) <NEW_LINE> note = models.TextField('备注', blank=True) <NEW_LINE> s_type = models.ForeignKey(SettingsType, on_delete=models.CASCADE, verbose_name='设置类型', related_name='item_set') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> unique_together = (('name', 's_type'),) <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def delete_cache(self): <NEW_LINE> <INDENT> self.s_type.delete_cache() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def post_save_callback(sender, **kwargs): <NEW_LINE> <INDENT> self = kwargs['instance'] <NEW_LINE> self.delete_cache() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def post_delete_callback(sender, **kwargs): <NEW_LINE> <INDENT> self = kwargs['instance'] <NEW_LINE> self.delete_cache()
设置项
62598fad7047854f4633f3ae
class State(Base): <NEW_LINE> <INDENT> __tablename__ = "states" <NEW_LINE> id = Column(Integer, unique=True, primary_key=True, autoincrement=True, nullable=False) <NEW_LINE> name = Column(String(128), nullable=False)
Define class State
62598fad6aa9bd52df0d4e9c
class Rose(Visualization): <NEW_LINE> <INDENT> def __init__(self, app): <NEW_LINE> <INDENT> super(Rose, self).__init__(app) <NEW_LINE> self.app.add_javascripts( '/js/rgraph/RGraph.common.core.js', '/js/rgraph/RGraph.common.tooltips.js', '/js/rgraph/RGraph.common.effects.js', '/js/rgraph/RGraph.rose.js' )
Uses RGraph to render the facet as a rose diagram.
62598fad01c39578d7f12d53
class ExplicitYamlDumper(yaml.SafeDumper): <NEW_LINE> <INDENT> def ignore_aliases(self, data): <NEW_LINE> <INDENT> return True
A yaml dumper that will never emit aliases.
62598fad5fc7496912d4826c
class RemoteTimeout(Timeout): <NEW_LINE> <INDENT> pass
DEPRECATED, DO NOT USE. Prefer Timeout exception
62598fad21bff66bcd722c3b
class JointPositionAction(JointAction): <NEW_LINE> <INDENT> def __init__(self, robot, joint_ids=None, bounds=(None, None), kp=None, kd=None, max_force=None, discrete_values=None): <NEW_LINE> <INDENT> super(JointPositionAction, self).__init__(robot, joint_ids, discrete_values=discrete_values) <NEW_LINE> self.kp, self.kd, self.max_force = kp, kd, max_force <NEW_LINE> if self.max_force is None: <NEW_LINE> <INDENT> self.max_force = self.robot.get_joint_max_forces(self.joints) <NEW_LINE> if np.allclose(self.max_force, 0): <NEW_LINE> <INDENT> self.max_force = None <NEW_LINE> <DEDENT> <DEDENT> if self.discrete_values is None: <NEW_LINE> <INDENT> self.data = self.robot.get_joint_positions(self.joints) <NEW_LINE> bounds = self._check_continuous_bounds(bounds) <NEW_LINE> if bounds == (None, None): <NEW_LINE> <INDENT> bounds = self.robot.get_joint_limits(self.joints) <NEW_LINE> <DEDENT> self._space = gym.spaces.Box(low=bounds[:, 0], high=bounds[:, 1]) <NEW_LINE> <DEDENT> <DEDENT> def bounds(self): <NEW_LINE> <INDENT> return self.robot.get_joint_limits(self.joints) <NEW_LINE> <DEDENT> def _write_continuous(self, data): <NEW_LINE> <INDENT> self.robot.set_joint_positions(data, self.joints, kp=self.kp, kd=self.kd, forces=self.max_force) <NEW_LINE> <DEDENT> def __copy__(self): <NEW_LINE> <INDENT> return self.__class__(robot=self.robot, joint_ids=self.joints, kp=self.kp, kd=self.kd, max_force=self.max_force) <NEW_LINE> <DEDENT> def __deepcopy__(self, memo={}): <NEW_LINE> <INDENT> if self in memo: <NEW_LINE> <INDENT> return memo[self] <NEW_LINE> <DEDENT> robot = memo.get(self.robot, self.robot) <NEW_LINE> joints = copy.deepcopy(self.joints) <NEW_LINE> bounds = copy.deepcopy(self.bounds) <NEW_LINE> kp = copy.deepcopy(self.kp) <NEW_LINE> kd = copy.deepcopy(self.kd) <NEW_LINE> max_force = copy.deepcopy(self.max_force) <NEW_LINE> discrete_values = copy.deepcopy(self.discrete_values) <NEW_LINE> action = self.__class__(robot=robot, joint_ids=joints, bounds=bounds, kp=kp, kd=kd, max_force=max_force, discrete_values=discrete_values) <NEW_LINE> memo[self] = action <NEW_LINE> return action
Joint Position Action Set the joint positions using position control.
62598fadd58c6744b42dc2c1
class AdversarialLoss(nn.Module): <NEW_LINE> <INDENT> def __init__(self, type='lsgan', target_real_label=1.0, target_fake_label=0.0): <NEW_LINE> <INDENT> super(AdversarialLoss, self).__init__() <NEW_LINE> self.type = type <NEW_LINE> self.register_buffer('real_label', torch.tensor(target_real_label).to(device)) <NEW_LINE> self.register_buffer('fake_label', torch.tensor(target_fake_label).to(device)) <NEW_LINE> if type == 'nsgan': <NEW_LINE> <INDENT> self.criterion = nn.BCELoss() <NEW_LINE> <DEDENT> elif type == 'lsgan': <NEW_LINE> <INDENT> self.criterion = nn.MSELoss() <NEW_LINE> <DEDENT> elif type == 'hinge': <NEW_LINE> <INDENT> self.criterion = nn.ReLU() <NEW_LINE> <DEDENT> elif type == 'l1': <NEW_LINE> <INDENT> self.criterion = nn.L1Loss() <NEW_LINE> <DEDENT> <DEDENT> def __call__(self, outputs, is_real, is_disc=None): <NEW_LINE> <INDENT> if self.type == 'hinge': <NEW_LINE> <INDENT> if is_disc: <NEW_LINE> <INDENT> if is_real: <NEW_LINE> <INDENT> outputs = -outputs <NEW_LINE> <DEDENT> return self.criterion(1 + outputs).mean() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return (-outputs).mean() <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> labels = (self.real_label if is_real else self.fake_label).expand_as(outputs) <NEW_LINE> loss = self.criterion(outputs, labels) <NEW_LINE> return loss
Adversarial loss https://arxiv.org/abs/1711.10337
62598fadadb09d7d5dc0a55f
class ITarget(ISimple): <NEW_LINE> <INDENT> pass
Target.
62598fad97e22403b383aee2
class EmailConfig: <NEW_LINE> <INDENT> def __init__(self, **conf): <NEW_LINE> <INDENT> self.s_host = conf["s_host"] <NEW_LINE> self.s_login = conf["s_login"] <NEW_LINE> self.s_pass = conf["s_pass"] <NEW_LINE> self.c_type = conf["c_type"] <NEW_LINE> self.s_port = conf["s_port"]
Экземпляр данного класса будет содержать настройки провадера
62598fada79ad1619776a03b
class subProcess: <NEW_LINE> <INDENT> def __init__(self, cmd, bufsize=8192): <NEW_LINE> <INDENT> self.cleaned=False <NEW_LINE> self.BUFSIZ=bufsize <NEW_LINE> self.outr, self.outw = os.pipe() <NEW_LINE> self.errr, self.errw = os.pipe() <NEW_LINE> self.pid = os.fork() <NEW_LINE> if self.pid == 0: <NEW_LINE> <INDENT> self._child(cmd) <NEW_LINE> <DEDENT> os.close(self.outw) <NEW_LINE> os.close(self.errw) <NEW_LINE> self.outdata = self.errdata = '' <NEW_LINE> self.outchunk = self.errchunk = '' <NEW_LINE> self._outeof = self._erreof = 0 <NEW_LINE> <DEDENT> def _child(self, cmd): <NEW_LINE> <INDENT> os.setpgrp() <NEW_LINE> os.dup2(self.outw,1) <NEW_LINE> os.dup2(self.errw,2) <NEW_LINE> map(os.close,(self.outr,self.outw,self.errr,self.errw)) <NEW_LINE> try: <NEW_LINE> <INDENT> cmd = ['/bin/sh', '-c', cmd] <NEW_LINE> os.execvp(cmd[0], cmd) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> os._exit(1) <NEW_LINE> <DEDENT> <DEDENT> def read(self, timeout=None): <NEW_LINE> <INDENT> currtime=time.time() <NEW_LINE> while 1: <NEW_LINE> <INDENT> tocheck=[] <NEW_LINE> if not self._outeof: <NEW_LINE> <INDENT> tocheck.append(self.outr) <NEW_LINE> <DEDENT> if not self._erreof: <NEW_LINE> <INDENT> tocheck.append(self.errr) <NEW_LINE> <DEDENT> ready = select.select(tocheck,[],[],timeout) <NEW_LINE> if len(ready[0]) == 0: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self.outr in ready[0]: <NEW_LINE> <INDENT> outchunk = os.read(self.outr,self.BUFSIZ) <NEW_LINE> if outchunk == '': <NEW_LINE> <INDENT> self._outeof = 1 <NEW_LINE> <DEDENT> self.outdata += outchunk <NEW_LINE> self.outchunk = outchunk <NEW_LINE> <DEDENT> if self.errr in ready[0]: <NEW_LINE> <INDENT> errchunk = os.read(self.errr,self.BUFSIZ) <NEW_LINE> if errchunk == '': <NEW_LINE> <INDENT> self._erreof = 1 <NEW_LINE> <DEDENT> self.errdata += errchunk <NEW_LINE> self.errchunk = errchunk <NEW_LINE> <DEDENT> if self._outeof and self._erreof: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> elif timeout: <NEW_LINE> <INDENT> if (time.time()-currtime) > timeout: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def kill(self): <NEW_LINE> <INDENT> os.kill(-self.pid, signal.SIGTERM) <NEW_LINE> <DEDENT> def pause(self): <NEW_LINE> <INDENT> os.kill(-self.pid, signal.SIGSTOP) <NEW_LINE> <DEDENT> def resume(self): <NEW_LINE> <INDENT> os.kill(-self.pid, signal.SIGCONT) <NEW_LINE> <DEDENT> def cleanup(self): <NEW_LINE> <INDENT> self.cleaned=True <NEW_LINE> os.close(self.outr) <NEW_LINE> os.close(self.errr) <NEW_LINE> pid, sts = os.waitpid(self.pid, 0) <NEW_LINE> if pid == self.pid: <NEW_LINE> <INDENT> self.sts = sts <NEW_LINE> <DEDENT> return self.sts <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> if not self.cleaned: <NEW_LINE> <INDENT> self.cleanup()
Class representing a child process. It's like popen2.Popen3 but there are three main differences. 1. This makes the new child process group leader (using setpgrp()) so that all children can be killed. 2. The output function (read) is optionally non blocking returning in specified timeout if nothing is read, or as close to specified timeout as possible if data is read. 3. The output from both stdout & stderr is read (into outdata and errdata). Reading from multiple outputs while not deadlocking is not trivial and is often done in a non robust manner.
62598fad2ae34c7f260ab0b7
class BSTree(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.__root = None <NEW_LINE> self.__size = 0 <NEW_LINE> <DEDENT> def insert(self, data) -> (BSTIterator, bool): <NEW_LINE> <INDENT> if self.__root is None: <NEW_LINE> <INDENT> self.__root = BSTNode(data) <NEW_LINE> self.__size += 1 <NEW_LINE> return (BSTIterator(self.__root), True) <NEW_LINE> <DEDENT> curr = self.__root <NEW_LINE> parent = self.__root <NEW_LINE> while curr is not None: <NEW_LINE> <INDENT> if data < curr.data: <NEW_LINE> <INDENT> parent = curr <NEW_LINE> curr = curr.left <NEW_LINE> <DEDENT> elif data > curr.data: <NEW_LINE> <INDENT> parent = curr <NEW_LINE> curr = curr.right <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return (BSTIterator(curr), False) <NEW_LINE> <DEDENT> <DEDENT> newNode = BSTNode(data) <NEW_LINE> newNode.parent = parent <NEW_LINE> if data < parent.data: <NEW_LINE> <INDENT> parent.left = newNode <NEW_LINE> <DEDENT> elif data > parent.data: <NEW_LINE> <INDENT> parent.right = newNode <NEW_LINE> <DEDENT> self.__size += 1 <NEW_LINE> return (BSTIterator(newNode), True) <NEW_LINE> <DEDENT> def find(self, data): <NEW_LINE> <INDENT> curr = self.__root <NEW_LINE> while curr is not None: <NEW_LINE> <INDENT> if curr.data > data: <NEW_LINE> <INDENT> curr = curr.left <NEW_LINE> <DEDENT> elif curr.data < data: <NEW_LINE> <INDENT> curr = curr.right <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return BSTIterator(curr) <NEW_LINE> <DEDENT> <DEDENT> return BSTIterator(None) <NEW_LINE> <DEDENT> def size(self): <NEW_LINE> <INDENT> return self.__size <NEW_LINE> <DEDENT> def height(self): <NEW_LINE> <INDENT> return self.__heightHelper(self.__root) - 1 <NEW_LINE> <DEDENT> def empty(self): <NEW_LINE> <INDENT> return self.__size == 0 <NEW_LINE> <DEDENT> def begin(self) -> (BSTIterator): <NEW_LINE> <INDENT> if self.__root is None: <NEW_LINE> <INDENT> return BSTIterator(None) <NEW_LINE> <DEDENT> curr = self.__root <NEW_LINE> while curr.left is not None: <NEW_LINE> <INDENT> curr = curr.left <NEW_LINE> <DEDENT> return BSTIterator(curr) <NEW_LINE> <DEDENT> def end(self) -> (BSTIterator): <NEW_LINE> <INDENT> return BSTIterator(None) <NEW_LINE> <DEDENT> def __heightHelper(self, node) -> (int): <NEW_LINE> <INDENT> if node is None: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> left = self.__heightHelper(node.left) <NEW_LINE> right = self.__heightHelper(node.right) <NEW_LINE> return 1 + max(left, right)
Binary Search Tree Attributes: __root: the root of the tree __size: the size of the tree
62598fad66673b3332c303a1
class GPMultiValue(BaseGPObject): <NEW_LINE> <INDENT> _type = None <NEW_LINE> def __init__(self, gptype): <NEW_LINE> <INDENT> self._type = gptype <NEW_LINE> self._dataType = "GPMultiValue:%s" % gptype <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return json.dumps(self.asDictionary) <NEW_LINE> <DEDENT> def asDictionary(self): <NEW_LINE> <INDENT> return { "dataType" : self._dataType, "value" : self._value, "paramName" : self._paramName } <NEW_LINE> <DEDENT> @property <NEW_LINE> def value(self): <NEW_LINE> <INDENT> return self._value <NEW_LINE> <DEDENT> @value.setter <NEW_LINE> def value(self, value): <NEW_LINE> <INDENT> self._value = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def dataType(self): <NEW_LINE> <INDENT> return self._dataType <NEW_LINE> <DEDENT> @property <NEW_LINE> def paramName(self): <NEW_LINE> <INDENT> return self._paramName <NEW_LINE> <DEDENT> @paramName.setter <NEW_LINE> def paramName(self, value): <NEW_LINE> <INDENT> if isinstance(value, str): <NEW_LINE> <INDENT> self._paramName = value <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def fromJSON(value): <NEW_LINE> <INDENT> j = json.loads(value) <NEW_LINE> v = GPMultiValue(gptype=j['dataType']) <NEW_LINE> if "defaultValue" in j: <NEW_LINE> <INDENT> v.value = j['defaultValue'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> v.value = j['value'] <NEW_LINE> <DEDENT> if 'paramName' in j: <NEW_LINE> <INDENT> v.paramName = j['paramName'] <NEW_LINE> <DEDENT> elif 'name' in j: <NEW_LINE> <INDENT> v.paramName = j['name'] <NEW_LINE> <DEDENT> return v
The fully qualified data type for a GPMultiValue parameter is GPMultiValue:<memberDataType>, where memberDataType is one of the data types defined above (for example, GPMultiValue:GPString, GPMultiValue:GPLong, and so on). The parameter value for GPMultiValue data types is a JSON array. Each element in this array is of the data type as defined by the memberDataType suffix of the fully qualified GPMultiValue data type name.
62598fad99cbb53fe6830ead
class FullPoolError(PoolError): <NEW_LINE> <INDENT> pass
Raised when we try to add a connection to a full pool in blocking mode.
62598fad30bbd72246469963
class TestClientRegistration(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testClientRegistration(self): <NEW_LINE> <INDENT> pass
ClientRegistration unit test stubs
62598fad5166f23b2e2433ae
class Output(): <NEW_LINE> <INDENT> def write(self, line): echo(line) <NEW_LINE> def flush(self): pass
Standard output like class using echo.
62598fad3317a56b869be535
class GetList(Choreography): <NEW_LINE> <INDENT> def __init__(self, temboo_session): <NEW_LINE> <INDENT> Choreography.__init__(self, temboo_session, '/Library/SunlightLabs/Congress/Legislator/GetList') <NEW_LINE> <DEDENT> def new_input_set(self): <NEW_LINE> <INDENT> return GetListInputSet() <NEW_LINE> <DEDENT> def _make_result_set(self, result, path): <NEW_LINE> <INDENT> return GetListResultSet(result, path) <NEW_LINE> <DEDENT> def _make_execution(self, session, exec_id, path): <NEW_LINE> <INDENT> return GetListChoreographyExecution(session, exec_id, path)
Create a new instance of the GetList Choreography. A TembooSession object, containing a valid set of Temboo credentials, must be supplied.
62598fad4428ac0f6e6584fa
class _PublisherAPI(object): <NEW_LINE> <INDENT> def __init__(self, gax_api): <NEW_LINE> <INDENT> self._gax_api = gax_api <NEW_LINE> <DEDENT> def list_topics(self, project): <NEW_LINE> <INDENT> options = CallOptions(is_page_streaming=False) <NEW_LINE> path = 'projects/%s' % (project,) <NEW_LINE> response = self._gax_api.list_topics(path, options) <NEW_LINE> topics = [{'name': topic_pb.name} for topic_pb in response.topics] <NEW_LINE> return topics, response.next_page_token <NEW_LINE> <DEDENT> def topic_create(self, topic_path): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> topic_pb = self._gax_api.create_topic(topic_path) <NEW_LINE> <DEDENT> except GaxError as exc: <NEW_LINE> <INDENT> if exc_to_code(exc.cause) == StatusCode.FAILED_PRECONDITION: <NEW_LINE> <INDENT> raise Conflict(topic_path) <NEW_LINE> <DEDENT> raise <NEW_LINE> <DEDENT> return {'name': topic_pb.name} <NEW_LINE> <DEDENT> def topic_get(self, topic_path): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> topic_pb = self._gax_api.get_topic(topic_path) <NEW_LINE> <DEDENT> except GaxError as exc: <NEW_LINE> <INDENT> if exc_to_code(exc.cause) == StatusCode.NOT_FOUND: <NEW_LINE> <INDENT> raise NotFound(topic_path) <NEW_LINE> <DEDENT> raise <NEW_LINE> <DEDENT> return {'name': topic_pb.name} <NEW_LINE> <DEDENT> def topic_delete(self, topic_path): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._gax_api.delete_topic(topic_path) <NEW_LINE> <DEDENT> except GaxError as exc: <NEW_LINE> <INDENT> if exc_to_code(exc.cause) == StatusCode.NOT_FOUND: <NEW_LINE> <INDENT> raise NotFound(topic_path) <NEW_LINE> <DEDENT> raise <NEW_LINE> <DEDENT> <DEDENT> def topic_publish(self, topic_path, messages): <NEW_LINE> <INDENT> message_pbs = [_message_pb_from_dict(message) for message in messages] <NEW_LINE> try: <NEW_LINE> <INDENT> response = self._gax_api.publish(topic_path, message_pbs) <NEW_LINE> <DEDENT> except GaxError as exc: <NEW_LINE> <INDENT> if exc_to_code(exc.cause) == StatusCode.NOT_FOUND: <NEW_LINE> <INDENT> raise NotFound(topic_path) <NEW_LINE> <DEDENT> raise <NEW_LINE> <DEDENT> return response.message_ids <NEW_LINE> <DEDENT> def topic_list_subscriptions(self, topic_path): <NEW_LINE> <INDENT> options = CallOptions(is_page_streaming=False) <NEW_LINE> try: <NEW_LINE> <INDENT> response = self._gax_api.list_topic_subscriptions( topic_path, options) <NEW_LINE> <DEDENT> except GaxError as exc: <NEW_LINE> <INDENT> if exc_to_code(exc.cause) == StatusCode.NOT_FOUND: <NEW_LINE> <INDENT> raise NotFound(topic_path) <NEW_LINE> <DEDENT> raise <NEW_LINE> <DEDENT> subs = [{'topic': topic_path, 'name': subscription} for subscription in response.subscriptions] <NEW_LINE> return subs, response.next_page_token
Helper mapping publisher-related APIs. :type gax_api: :class:`google.pubsub.v1.publisher_api.PublisherApi` :param gax_api: API object used to make GAX requests.
62598fad091ae35668704bf4
@base.ReleaseTracks(base.ReleaseTrack.BETA) <NEW_LINE> class List(base.ListCommand): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def Args(parser): <NEW_LINE> <INDENT> parser.display_info.AddFormat('table(updateTime)') <NEW_LINE> base.URI_FLAG.RemoveFromParser(parser) <NEW_LINE> base.PAGE_SIZE_FLAG.RemoveFromParser(parser) <NEW_LINE> resource_args.AddDeviceResourceArg(parser, 'for which to list configs', positional=False) <NEW_LINE> <DEDENT> def Run(self, args): <NEW_LINE> <INDENT> client = devices.DeviceStatesClient() <NEW_LINE> device_ref = args.CONCEPTS.device.Parse() <NEW_LINE> return client.List(device_ref, args.limit)
List states for a device. This command lists all available states in the history of the device. Up to 10 are kept; you may restrict the output to fewer via the `--limit` flag.
62598fadbe8e80087fbbf03a
@addTupleType <NEW_LINE> class LdapSetting(Tuple, DeclarativeBase): <NEW_LINE> <INDENT> __tupleType__ = userPluginTuplePrefix + 'LdapSettingTuple' <NEW_LINE> __tablename__ = 'LdapSetting' <NEW_LINE> id = Column(Integer, primary_key=True, autoincrement=True) <NEW_LINE> ldapTitle = Column(String, nullable=False, unique=True) <NEW_LINE> ldapDomain = Column(String, nullable=False) <NEW_LINE> ldapUri = Column(String, nullable=False) <NEW_LINE> ldapCNFolders = Column(String, nullable=True) <NEW_LINE> ldapOUFolders = Column(String, nullable=True) <NEW_LINE> ldapGroups = Column(String, nullable=True) <NEW_LINE> adminEnabled = Column(Boolean, nullable=False, server_default='0') <NEW_LINE> desktopEnabled = Column(Boolean, nullable=False, server_default='0') <NEW_LINE> mobileEnabled = Column(Boolean, nullable=False, server_default='0')
LdapSetting This table stores connetions and settings to LDAP servers
62598fad435de62698e9bdc6
class StreamingQualityCheckRunnerDelegate(QualityCheckRunnerDelegate): <NEW_LINE> <INDENT> __slots__ = () <NEW_LINE> output = sys.stdout <NEW_LINE> error = sys.stderr <NEW_LINE> def _check_failed(self, check): <NEW_LINE> <INDENT> assert isinstance(check, QualityCheck) <NEW_LINE> return check.result() != check.success <NEW_LINE> <DEDENT> def handle_error(self, quality_check): <NEW_LINE> <INDENT> self.error.write(traceback.format_exc() + "\n") <NEW_LINE> self.error.write("Unhandled exception caught for quality check '%s'\n" % quality_check.name()) <NEW_LINE> <DEDENT> def pre_run(self, quality_check): <NEW_LINE> <INDENT> self.output.write("%s ... " % quality_check.name()) <NEW_LINE> <DEDENT> def post_run(self, quality_check): <NEW_LINE> <INDENT> suffix = "OK" <NEW_LINE> if self._check_failed(quality_check): <NEW_LINE> <INDENT> suffix = "FAILED" <NEW_LINE> <DEDENT> self.output.write("%s\n" % suffix) <NEW_LINE> if self._check_failed(quality_check): <NEW_LINE> <INDENT> for line in quality_check.description().split('\n'): <NEW_LINE> <INDENT> self.output.write("\t%s\n" % line) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def post_fix(self, quality_check): <NEW_LINE> <INDENT> super(StreamingQualityCheckRunnerDelegate, self).post_fix(quality_check) <NEW_LINE> if not self._check_failed(quality_check): <NEW_LINE> <INDENT> self.output.write("(FIXED) ")
A delegate that writes information about the runner's progress to streams @note we do not explicitly flush streams after writing
62598fadcc0a2c111447afe7
class DebugLandmarks(PostProcessAction): <NEW_LINE> <INDENT> def process(self, extract_media): <NEW_LINE> <INDENT> frame = os.path.splitext(os.path.basename(extract_media.filename))[0] <NEW_LINE> for idx, face in enumerate(extract_media.detected_faces): <NEW_LINE> <INDENT> logger.trace("Drawing Landmarks. Frame: '%s'. Face: %s", frame, idx) <NEW_LINE> for (pos_x, pos_y) in face.aligned.landmarks: <NEW_LINE> <INDENT> cv2.circle(face.aligned.face, (pos_x, pos_y), 1, (0, 255, 255), -1) <NEW_LINE> <DEDENT> center = tuple(np.int32((face.aligned.size / 2, face.aligned.size / 2))) <NEW_LINE> points = (face.aligned.pose.xyz_2d * face.aligned.size).astype("int32") <NEW_LINE> cv2.line(face.aligned.face, center, tuple(points[1]), (0, 255, 0), 1) <NEW_LINE> cv2.line(face.aligned.face, center, tuple(points[0]), (255, 0, 0), 1) <NEW_LINE> cv2.line(face.aligned.face, center, tuple(points[2]), (0, 0, 255), 1) <NEW_LINE> roi = face.aligned.get_cropped_roi("face") <NEW_LINE> cv2.rectangle(face.aligned.face, tuple(roi[:2]), tuple(roi[2:]), (0, 255, 0), 1)
Draw debug landmarks on face output. Extract Only
62598fad498bea3a75a57af4
class Versioned(object): <NEW_LINE> <INDENT> def __init__(self, content, low, high): <NEW_LINE> <INDENT> self.content = content <NEW_LINE> self.low = low <NEW_LINE> self.high = high <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Versioned({0!r}, {1!r}, {2!r})".format(self.content, self.low, self.high)
This class encapsulates an object and adds information about its (continuous) lifetime. .. data:: content The object .. data:: low The first version where the object starts to appear. .. data:: high The last version where the object still appears.
62598fada05bb46b3848a842
class Command: <NEW_LINE> <INDENT> def __init__(self, transport: RevvyTransport): <NEW_LINE> <INDENT> self._transport = transport <NEW_LINE> self._command_byte = self.command_id <NEW_LINE> self._log = get_logger(f'{type(self).__name__} [id={self._command_byte}]') <NEW_LINE> <DEDENT> @property <NEW_LINE> def command_id(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def _process(self, response: Response): <NEW_LINE> <INDENT> if response.status == ResponseStatus.Ok: <NEW_LINE> <INDENT> return self.parse_response(response.payload) <NEW_LINE> <DEDENT> elif response.status == ResponseStatus.Error_UnknownCommand: <NEW_LINE> <INDENT> raise UnknownCommandError(f"Command not implemented: {self._command_byte}") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError(f'Command status: "{response.status}" with payload: {repr(response.payload)}') <NEW_LINE> <DEDENT> <DEDENT> def _send(self, payload=b''): <NEW_LINE> <INDENT> response = self._transport.send_command(self._command_byte, payload) <NEW_LINE> try: <NEW_LINE> <INDENT> return self._process(response) <NEW_LINE> <DEDENT> except (UnknownCommandError, ValueError) as e: <NEW_LINE> <INDENT> self._log(f'Payload for error: {payload} (length {len(payload)})') <NEW_LINE> self._log(traceback.format_exc()) <NEW_LINE> raise e <NEW_LINE> <DEDENT> <DEDENT> def __call__(self, *args): <NEW_LINE> <INDENT> if args: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> return self._send() <NEW_LINE> <DEDENT> def parse_response(self, payload): <NEW_LINE> <INDENT> if payload: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> return None
A generic command towards the MCU
62598fad7b180e01f3e4903b
class AttentionWeightedAverage(Layer): <NEW_LINE> <INDENT> def __init__(self, embed_dim, **kwargs): <NEW_LINE> <INDENT> self.kernel_initializer = initializers.get('uniform') <NEW_LINE> self.supports_masking = True <NEW_LINE> self.embed_dim = embed_dim <NEW_LINE> super().__init__(**kwargs) <NEW_LINE> <DEDENT> def build(self, input_shape): <NEW_LINE> <INDENT> if not isinstance(input_shape, list): <NEW_LINE> <INDENT> raise ValueError('An AttentionWeightedAverage layer should have 2 inputs.') <NEW_LINE> <DEDENT> if len(input_shape) < 2: <NEW_LINE> <INDENT> raise ValueError('An AttentionWeightedAverage layer should have exactly 2 inputs.') <NEW_LINE> <DEDENT> assert len(input_shape[0]) == 2 <NEW_LINE> seqdim = input_shape[0][0] <NEW_LINE> assert len(input_shape[1]) == 2 <NEW_LINE> self.vfeat_dim = input_shape[1][0] <NEW_LINE> self.vfeat_len = input_shape[1][1] <NEW_LINE> self.wh = self.add_weight(shape=(self.vfeat_len, self.embed_dim), initializer=self.kernel_initializer, name='{}_wh'.format(self.name)) <NEW_LINE> self.wv = self.add_weight(shape=(self.embed_dim, self.vfeat_dim), initializer=self.kernel_initializer, name='{}_wv'.format(self.name)) <NEW_LINE> self.wg = self.add_weight(shape=(self.embed_dim, seqdim), initializer=self.kernel_initializer, name='{}_wg'.format(self.name)) <NEW_LINE> super().build(input_shape) <NEW_LINE> <DEDENT> def call(self, x, mask=None): <NEW_LINE> <INDENT> assert isinstance(x, list) <NEW_LINE> h, v = x <NEW_LINE> s = K.dot(self.wv, v) + K.dot(K.dot(self.wg, h), K.ones((1, self.vfeat_len))) <NEW_LINE> z = K.dot(self.wh, K.tanh(s)) <NEW_LINE> alpha = K.softmax(z) <NEW_LINE> if mask is not None: <NEW_LINE> <INDENT> mask = K.cast(mask, K.floatx()) <NEW_LINE> alpha = alpha * mask <NEW_LINE> <DEDENT> weighted_avg = v * K.expand_dims(alpha) <NEW_LINE> return weighted_avg <NEW_LINE> <DEDENT> def compute_output_shape(self, input_shape): <NEW_LINE> <INDENT> assert isinstance(input_shape, list) <NEW_LINE> shape_h, shape_v = input_shape <NEW_LINE> return shape_v <NEW_LINE> <DEDENT> def get_config(self): <NEW_LINE> <INDENT> config = { 'embed_dim': self.embed_dim } <NEW_LINE> base_config = super().get_config() <NEW_LINE> return dict(list(base_config.items()) + list(config.items()))
Weighted average for image captioning. Inputs: - hidden state of shape (seqdim, seqlen) - visual features of shape (vfeat_dim, vfeatlen) The equation followed is (6) in https://arxiv.org/pdf/1612.01887.pdf z_t = w_h tanh(W_v V + (W_g h_t) 1_{vfeatlen}^T) lpha_t = softmax(z_t) The dimension of the embedding, embed_dim means that: - w_h is of shape (vfeatlen, embed_dim) - W_v is of shape (embed_dim, vfeat_dim) - W_g is of shape (embed_dim, seqdim)
62598fadfff4ab517ebcd7bb
class UsergroupsModelField(models.IntegerField): <NEW_LINE> <INDENT> ANONYMOUS_USERS = 0 <NEW_LINE> STAFF_USERS = -1 <NEW_LINE> SUPERUSERS = -2 <NEW_LINE> NORMAL_USERS = -3 <NEW_LINE> USER_TYPES_CHOICES = [ (ANONYMOUS_USERS, _("anonymous users")), (NORMAL_USERS, _("normal users")), (STAFF_USERS, _("staff users")), (SUPERUSERS, _("superusers")), ] <NEW_LINE> USER_TYPES_DICT = dict(USER_TYPES_CHOICES) <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> kwargs["choices"] = self.USER_TYPES_CHOICES <NEW_LINE> super(UsergroupsModelField, self).__init__(*args, **kwargs) <NEW_LINE> <DEDENT> def get_choices(self, *args, **kwargs): <NEW_LINE> <INDENT> groups = get_user_groups() <NEW_LINE> choices = self.USER_TYPES_CHOICES + list(groups) <NEW_LINE> return choices
TODO: Use html select optgroup [1] to group anonymous, staff and superusers from user groups [1] http://www.w3.org/wiki/HTML/Elements/optgroup
62598fad99cbb53fe6830eae
class ServiceError(Exception): <NEW_LINE> <INDENT> def __init__(self, msg, error=None, target: ErrorTarget = None): <NEW_LINE> <INDENT> self.message = msg <NEW_LINE> self.error = error <NEW_LINE> self.target = target
Base class for exceptions in MRM.
62598fad4e4d5625663723fc
class Component(OrderedDict): <NEW_LINE> <INDENT> def __init__(self, name=None,data=None): <NEW_LINE> <INDENT> if name in [None, '']: <NEW_LINE> <INDENT> raise Exception('Component must have a name') <NEW_LINE> <DEDENT> self.name = name <NEW_LINE> if data is None: <NEW_LINE> <INDENT> self.data = OrderedDict() <NEW_LINE> <DEDENT> elif isinstance(data, OrderedDict): <NEW_LINE> <INDENT> self.data = data <NEW_LINE> <DEDENT> elif isinstance(data, dict): <NEW_LINE> <INDENT> self.data = OrderedDict() <NEW_LINE> for key, val in data.items(): <NEW_LINE> <INDENT> self.data[key] = val <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception('Component data in __init__ should be a dict or ordereddict') <NEW_LINE> <DEDENT> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> return self.data[key] <NEW_LINE> <DEDENT> def __setitem__(self,key,value): <NEW_LINE> <INDENT> if not isinstance(key, str): <NEW_LINE> <INDENT> raise Exception('Component key must be a string') <NEW_LINE> <DEDENT> self.data[key] = value <NEW_LINE> <DEDENT> def toXML(self): <NEW_LINE> <INDENT> root = ET.Element('component') <NEW_LINE> root.attrib['name'] = self.name <NEW_LINE> for key, val in self.data.items(): <NEW_LINE> <INDENT> if isinstance(val, Catalog): <NEW_LINE> <INDENT> compSubEl = ET.SubElement(root, 'component') <NEW_LINE> compSubEl.attrib['name'] = key <NEW_LINE> ET.SubElement(compSubEl, 'catalog').text = str(val.xmlname) <NEW_LINE> <DEDENT> elif isinstance(val, Component): <NEW_LINE> <INDENT> if key != val.name: <NEW_LINE> <INDENT> print('WARNING: dictionary name and Component name dont match') <NEW_LINE> print('Proceeding with Component name') <NEW_LINE> <DEDENT> root.append(val.toXML()) <NEW_LINE> <DEDENT> elif (isinstance(val,dict) or isinstance(val, OrderedDict)): <NEW_LINE> <INDENT> obj = Component(name=key, data=val) <NEW_LINE> root.append(obj.toXML()) <NEW_LINE> <DEDENT> elif (not isinstance(val, dict)) and (not isinstance(val, OrderedDict)): <NEW_LINE> <INDENT> propSubEl = ET.SubElement(root,'property') <NEW_LINE> propSubEl.attrib['name'] = key <NEW_LINE> ET.SubElement(propSubEl, 'value').text = str(val) <NEW_LINE> <DEDENT> <DEDENT> return root <NEW_LINE> <DEDENT> def writeXML(self, filename, root='dummy', noroot=False): <NEW_LINE> <INDENT> if root in [None, '']: <NEW_LINE> <INDENT> raise Exception('Root name cannot be blank') <NEW_LINE> <DEDENT> if noroot: <NEW_LINE> <INDENT> fileRoot = self.toXML() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> fileRoot = ET.Element(root) <NEW_LINE> root = self.toXML() <NEW_LINE> fileRoot.append(root) <NEW_LINE> <DEDENT> print(fileRoot) <NEW_LINE> indentXML(fileRoot) <NEW_LINE> etObj = ET.ElementTree(fileRoot) <NEW_LINE> etObj.write(filename, encoding='unicode')
Class for storing component information.
62598fad91f36d47f2230e91
class ReportViewTestCase(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> user = User.objects.create_user( email='test@test.com', password='test', first_name='Test', last_name='User', phone='9997609994', address='Gurgaon', id_number='PBX024', is_admin=True, ) <NEW_LINE> resp = self.client.post( reverse_lazy('login'), { 'email': 'test@test.com', 'password': 'test' }, follow=True ) <NEW_LINE> <DEDENT> def test_report_view_get(self): <NEW_LINE> <INDENT> resp = self.client.get(reverse_lazy('report'), follow=False) <NEW_LINE> self.assertEqual(resp.status_code, 200) <NEW_LINE> self.assertTrue('form' in resp.context)
TestCase for report page
62598fada17c0f6771d5c20c
class _MelModel(MelGroup): <NEW_LINE> <INDENT> typeSets = ((b'MODL', b'MODB', b'MODT'), (b'MOD2', b'MO2B', b'MO2T'), (b'MOD3', b'MO3B', b'MO3T'), (b'MOD4', b'MO4B', b'MO4T')) <NEW_LINE> def __init__(self, attr=u'model', index=0): <NEW_LINE> <INDENT> types = self.__class__.typeSets[index - 1 if index > 1 else 0] <NEW_LINE> super(_MelModel, self).__init__(attr, MelString(types[0], u'modPath'), MelFloat(types[1], u'modb'), MelBase(types[2], u'modt_p') )
Represents a model record.
62598fad009cb60464d014f7
class BasicMultiAgent(MultiAgentEnv): <NEW_LINE> <INDENT> def __init__(self, num): <NEW_LINE> <INDENT> self.agents = [MockEnv(25) for _ in range(num)] <NEW_LINE> self.dones = set() <NEW_LINE> self.observation_space = gym.spaces.Discrete(2) <NEW_LINE> self.action_space = gym.spaces.Discrete(2) <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self.dones = set() <NEW_LINE> return {i: a.reset() for i, a in enumerate(self.agents)} <NEW_LINE> <DEDENT> def step(self, action_dict): <NEW_LINE> <INDENT> obs, rew, done, info = {}, {}, {}, {} <NEW_LINE> for i, action in action_dict.items(): <NEW_LINE> <INDENT> obs[i], rew[i], done[i], info[i] = self.agents[i].step(action) <NEW_LINE> if done[i]: <NEW_LINE> <INDENT> self.dones.add(i) <NEW_LINE> <DEDENT> <DEDENT> done["__all__"] = len(self.dones) == len(self.agents) <NEW_LINE> return obs, rew, done, info
Env of N independent agents, each of which exits after 25 steps.
62598fad2c8b7c6e89bd379c
class Catalog(abc.ABC): <NEW_LINE> <INDENT> @abc.abstractmethod <NEW_LINE> def get_all(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def get(self, id): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def add(self, object, add_to_db): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def modify(self, modifiedObject): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def remove(self, id): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def search(self, search_string): <NEW_LINE> <INDENT> pass
Abstract class Catalog
62598fad4527f215b58e9eb7
class SurfaceLaplaceLayerTerm(Term): <NEW_LINE> <INDENT> name = 'dw_surface_laplace' <NEW_LINE> arg_types = [('material', 'virtual', 'state'), ('material', 'parameter_2', 'parameter_1')] <NEW_LINE> modes = ('weak', 'eval') <NEW_LINE> integration = 'surface' <NEW_LINE> def get_fargs(self, mat, virtual, state, mode=None, term_mode=None, diff_var=None, **kwargs): <NEW_LINE> <INDENT> ap, sg = self.get_approximation(virtual) <NEW_LINE> aps, sgs = self.get_approximation(state) <NEW_LINE> sd = aps.surface_data[self.region.name] <NEW_LINE> bfg = ap.get_base(sd.face_type, 1, self.integral) <NEW_LINE> elvol = nm.sum(sgs.det, axis=1) <NEW_LINE> vol = nm.tile(elvol[:,nm.newaxis], (1, sgs.det.shape[1], 1, 1)) <NEW_LINE> if mode == 'weak': <NEW_LINE> <INDENT> if diff_var is None: <NEW_LINE> <INDENT> vec = self.get(state, 'val', bfun=bfg) / vol <NEW_LINE> fmode = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> vec = nm.array([0], ndmin=4, dtype=nm.float64) <NEW_LINE> fmode = 1 <NEW_LINE> <DEDENT> return vec, mat, bfg, sgs, fmode <NEW_LINE> <DEDENT> elif mode == 'eval': <NEW_LINE> <INDENT> vec1 = self.get(state, 'val', bfun=bfg) / vol <NEW_LINE> vec2 = self.get(virtual, 'val', bfun=bfg) / vol <NEW_LINE> return vec1, vec2, mat, sgs <NEW_LINE> <DEDENT> <DEDENT> def get_eval_shape(self, mat, virtual, state, mode=None, term_mode=None, diff_var=None, **kwargs): <NEW_LINE> <INDENT> n_el, n_qp, dim, n_en, n_c = self.get_data_shape(state) <NEW_LINE> return (n_el, 1, 1, 1), state.dtype <NEW_LINE> <DEDENT> def set_arg_types(self): <NEW_LINE> <INDENT> if self.mode == 'weak': <NEW_LINE> <INDENT> self.function = terms.dw_surf_laplace <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.function = terms.d_surf_laplace
:Description: Acoustic 'layer' term - derivatives in surface directions. :Definition: .. math:: \int_{\Gamma} c \partial_\alpha \ul{q}\,\partial_\alpha \ul{p}, \alpha = 1,\dots,N-1 :Arguments 1: material: :math:`c`, virtual: :math:`q`, state: :math:`p` :Arguments 2: material: :math:`c`, parameter_1 : :math:`q`, parameter_2 : :math:`p`
62598fad01c39578d7f12d55
class Menu(Region): <NEW_LINE> <INDENT> _menu_options_locator = ( By.CSS_SELECTOR, "label") <NEW_LINE> _menu_toggle_locator = ( By.CSS_SELECTOR, "[class*=Toggle]") <NEW_LINE> _select_all_button_locator = ( By.CSS_SELECTOR, "[class*=AllOrNone] button:first-child") <NEW_LINE> _select_none_button_locator = ( By.CSS_SELECTOR, "[class*=AllOrNone] button:last-child") <NEW_LINE> @property <NEW_LINE> def all_button(self) -> WebElement: <NEW_LINE> <INDENT> return self.find_element(*self._select_all_button_locator) <NEW_LINE> <DEDENT> @property <NEW_LINE> def menu_toggle_button(self) -> WebElement: <NEW_LINE> <INDENT> return self.find_element(*self._menu_toggle_locator) <NEW_LINE> <DEDENT> @property <NEW_LINE> def none_button(self) -> WebElement: <NEW_LINE> <INDENT> return self.find_element(*self._select_none_button_locator) <NEW_LINE> <DEDENT> @property <NEW_LINE> def options(self) -> List[StudyGuide.Toolbar.Menu.Filter]: <NEW_LINE> <INDENT> return [self.Filter(self, option) for option in self.find_elements(*self._menu_options_locator)] <NEW_LINE> <DEDENT> def all(self) -> StudyGuide.Toolbar.Menu: <NEW_LINE> <INDENT> Utilities.click_option( self.driver, element=self.all_button ) <NEW_LINE> return self <NEW_LINE> <DEDENT> def click(self) -> StudyGuide.Toolbar.Menu: <NEW_LINE> <INDENT> Utilities.click_option( self.driver, element=self.menu_toggle_button ) <NEW_LINE> return self <NEW_LINE> <DEDENT> def none(self) -> StudyGuide.Toolbar.Menu: <NEW_LINE> <INDENT> Utilities.click_option( self.driver, element=self.none_button ) <NEW_LINE> return self <NEW_LINE> <DEDENT> class Filter(Region): <NEW_LINE> <INDENT> _checkbox_locator = ( By.CSS_SELECTOR, "input") <NEW_LINE> _filter_name_locator = ( By.CSS_SELECTOR, ".os-text, [class*=ColorLabel]") <NEW_LINE> _filter_number_locator = ( By.CSS_SELECTOR, ".os-number") <NEW_LINE> _is_checked_locator = ( By.CSS_SELECTOR, "input[checked]") <NEW_LINE> _is_disabled_locator = ( By.CSS_SELECTOR, "input[disabled]") <NEW_LINE> @property <NEW_LINE> def checkbox(self) -> WebElement: <NEW_LINE> <INDENT> return self.find_element(*self._checkbox_locator) <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_checked(self) -> bool: <NEW_LINE> <INDENT> return bool(self.find_elements(*self._is_checked_locator)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_disabled(self) -> bool: <NEW_LINE> <INDENT> return bool(self.find_elements(*self._is_disabled_locator)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self) -> str: <NEW_LINE> <INDENT> return self.find_element(*self._filter_name_locator).text <NEW_LINE> <DEDENT> @property <NEW_LINE> def number(self) -> str: <NEW_LINE> <INDENT> chapter = self.find_elements(*self._filter_number_locator) <NEW_LINE> if chapter: <NEW_LINE> <INDENT> return chapter.text <NEW_LINE> <DEDENT> return ""
A study guide filter menu.
62598fad8e7ae83300ee9079
class levenshtein: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def compare(self,true_seq,input_seq): <NEW_LINE> <INDENT> hpt_lst = init_hpt(true_seq[0], input_seq[0]) <NEW_LINE> len_true = len(true_seq) <NEW_LINE> len_in = len(input_seq) <NEW_LINE> no_more_to_expand = False <NEW_LINE> seq_hpt_lst = [] <NEW_LINE> while not no_more_to_expand: <NEW_LINE> <INDENT> no_more_to_expand, hpt_lst = expand(hpt_lst, true_seq, input_seq) <NEW_LINE> hpt_lst = recombination(hpt_lst) <NEW_LINE> if not no_more_to_expand: <NEW_LINE> <INDENT> seq_hpt_lst.append(hpt_lst) <NEW_LINE> <DEDENT> <DEDENT> return seq_hpt_lst[-1][0].num_sub, seq_hpt_lst[-1][0].num_del, seq_hpt_lst[-1][0].num_ins
Class for computing Levenshtein distance between two strings
62598fad01c39578d7f12d56
class IsAdminOrReadOnly(permissions.BasePermission): <NEW_LINE> <INDENT> def has_permission(self, request, view): <NEW_LINE> <INDENT> return ( request.method in permissions.SAFE_METHODS or request.user and is_authenticated(request.user) and request.user.is_staff )
The request is authenticated as a user, or is a read-only request.
62598fad76e4537e8c3ef584
class DoxygenWarning(object): <NEW_LINE> <INDENT> def __init__(self, firstline, filename, warning): <NEW_LINE> <INDENT> self.firstline = firstline <NEW_LINE> self.filename = filename <NEW_LINE> self.warning = warning <NEW_LINE> self.otherlines = [] <NEW_LINE> <DEDENT> def equals_ignoring_path_and_line_number(self, other): <NEW_LINE> <INDENT> if self.filename != other.filename: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if self.warning != other.warning: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.otherlines == other.otherlines <NEW_LINE> <DEDENT> def print_with_prefix(self, prefix): <NEW_LINE> <INDENT> print(prefix + self.firstline) <NEW_LINE> for line in self.otherlines: <NEW_LINE> <INDENT> print(prefix + ' ' + line)
Doxygen warning class.
62598fad8a43f66fc4bf2153
class CornersProblem(search.SearchProblem): <NEW_LINE> <INDENT> def __init__(self, startingGameState): <NEW_LINE> <INDENT> self.walls = startingGameState.getWalls() <NEW_LINE> self.startingPosition = startingGameState.getPacmanPosition() <NEW_LINE> top, right = self.walls.height-2, self.walls.width-2 <NEW_LINE> self.corners = ((1,1), (1,top), (right, 1), (right, top)) <NEW_LINE> for corner in self.corners: <NEW_LINE> <INDENT> if not startingGameState.hasFood(*corner): <NEW_LINE> <INDENT> print('Warning: no food in corner ' + str(corner)) <NEW_LINE> <DEDENT> <DEDENT> self._expanded = 0 <NEW_LINE> <DEDENT> def getStartState(self): <NEW_LINE> <INDENT> corners_visited = [] <NEW_LINE> return (self.startingPosition, corners_visited) <NEW_LINE> <DEDENT> def isGoalState(self, state): <NEW_LINE> <INDENT> return all(corner in state[1] for corner in self.corners) <NEW_LINE> <DEDENT> def getSuccessors(self, state): <NEW_LINE> <INDENT> successors = [] <NEW_LINE> for action in [Directions.NORTH, Directions.SOUTH, Directions.EAST, Directions.WEST]: <NEW_LINE> <INDENT> x,y = state[0] <NEW_LINE> dx, dy = Actions.directionToVector(action) <NEW_LINE> nextx, nexty = int(x + dx), int(y + dy) <NEW_LINE> if not self.walls[nextx][nexty]: <NEW_LINE> <INDENT> visited_corners = list(state[1]) <NEW_LINE> if (nextx, nexty) in self.corners and (nextx, nexty) not in visited_corners: <NEW_LINE> <INDENT> visited_corners.append((nextx, nexty)) <NEW_LINE> <DEDENT> nextState = ((nextx, nexty), visited_corners) <NEW_LINE> cost = 1 <NEW_LINE> successors.append( ( nextState, action, cost) ) <NEW_LINE> <DEDENT> <DEDENT> self._expanded += 1 <NEW_LINE> print(state) <NEW_LINE> return successors <NEW_LINE> <DEDENT> def getCostOfActions(self, actions): <NEW_LINE> <INDENT> if actions == None: return 999999 <NEW_LINE> x,y= self.startingPosition <NEW_LINE> for action in actions: <NEW_LINE> <INDENT> dx, dy = Actions.directionToVector(action) <NEW_LINE> x, y = int(x + dx), int(y + dy) <NEW_LINE> if self.walls[x][y]: return 999999 <NEW_LINE> <DEDENT> return len(actions)
This search problem finds paths through all four corners of a layout. You must select a suitable state space and successor function
62598fad56ac1b37e63021c2
class UserInfo(models.Model): <NEW_LINE> <INDENT> username = models.CharField(verbose_name="用户名",max_length=32) <NEW_LINE> password = models.CharField(verbose_name='密码',max_length=64) <NEW_LINE> roles = models.ManyToManyField(verbose_name='具有所有角色',to="Role",blank=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name_plural = "用户表" <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.username
用户表
62598fad60cbc95b06364325
class VerticalBot(Bot): <NEW_LINE> <INDENT> def __init__(self, character=8982): <NEW_LINE> <INDENT> super().__init__(character=8982) <NEW_LINE> self.moves = [[1, 0], [-1, 0]] <NEW_LINE> self.position = random.choice([[0, 0], [0, 1], [0, 2], [0, 3], [0, 4]]) <NEW_LINE> <DEDENT> def updown_move(self): <NEW_LINE> <INDENT> has_new_position = False <NEW_LINE> while not has_new_position: <NEW_LINE> <INDENT> move = random.choice(self.moves) <NEW_LINE> new_vertical_position = add_lists(move, self.position) <NEW_LINE> has_new_position = check_bounds(new_vertical_position, self.grid_size) <NEW_LINE> <DEDENT> return new_vertical_position <NEW_LINE> <DEDENT> def move(self): <NEW_LINE> <INDENT> if self.updown_move() == Obstacle.stationary(self): <NEW_LINE> <INDENT> self.position = add_lists(self.updown_move(), [0, 1]) <NEW_LINE> return self.position <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.position = self.updown_move() <NEW_LINE> return self.position
Initializes a bot that can only move directly up or down Parameters ---------- character = string Attributes ---------- moves = list ordered pairs that represent possible movements of the bot position = list ordered pairs that represent possible starting positions of the bot
62598fad55399d3f056264fb
class Meta: <NEW_LINE> <INDENT> model = User
Meta class.
62598fad66673b3332c303a3
class MicrositeSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> values = serializers.JSONField() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = Microsite <NEW_LINE> fields = '__all__'
Serializer class for Microsite model.
62598fad236d856c2adc9429
class PaddleLeft(Paddle): <NEW_LINE> <INDENT> def __init__(self, game): <NEW_LINE> <INDENT> super().__init__(game) <NEW_LINE> self.reset_paddle() <NEW_LINE> <DEDENT> def reset_paddle(self): <NEW_LINE> <INDENT> self.rect.midleft = self.screen_rect.midleft <NEW_LINE> self.rect.x += 50 <NEW_LINE> self.y = float(self.rect.y)
Class for left paddle
62598fade76e3b2f99fd8a0e
class TestVersionedCityObject: <NEW_LINE> <INDENT> def test_initialisation(self): <NEW_LINE> <INDENT> obj = cjm.CityObject({"type" : "Building"}, "building1") <NEW_LINE> ver_obj = cjv.VersionedCityObject(obj) <NEW_LINE> assert ver_obj.original_cityobject.name == "building1" <NEW_LINE> assert ver_obj.name == ver_obj.hash() <NEW_LINE> assert ver_obj.name == "d1a15b40c76164b118a73201255fbee8ad48d8ea"
Tests the VersionedCityObject class.
62598fadf7d966606f747fbd
class HTMLPreview(object): <NEW_LINE> <INDENT> def __init__(self, content, excerpt='', splitters=PREVIEW_SPLITTERS, max_words=PREVIEW_MAX_WORDS, more_string=PREVIEW_MORE_STRING): <NEW_LINE> <INDENT> self._preview = None <NEW_LINE> self.excerpt = excerpt <NEW_LINE> self.content = content <NEW_LINE> self.splitters = splitters <NEW_LINE> self.max_words = max_words <NEW_LINE> self.more_string = more_string <NEW_LINE> <DEDENT> @property <NEW_LINE> def preview(self): <NEW_LINE> <INDENT> if self._preview is None: <NEW_LINE> <INDENT> self._preview = self.build_preview() <NEW_LINE> <DEDENT> return self._preview <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return six.text_type(self.preview) <NEW_LINE> <DEDENT> def build_preview(self): <NEW_LINE> <INDENT> for splitter in self.splitters: <NEW_LINE> <INDENT> if splitter in self.content: <NEW_LINE> <INDENT> return self.split(splitter) <NEW_LINE> <DEDENT> <DEDENT> return self.truncate() <NEW_LINE> <DEDENT> def truncate(self): <NEW_LINE> <INDENT> return Truncator(self.content).words( self.max_words, self.more_string, html=True) <NEW_LINE> <DEDENT> def split(self, splitter): <NEW_LINE> <INDENT> soup = BeautifulSoup(self.content.split(splitter)[0], 'html.parser') <NEW_LINE> last_string = soup.find_all(text=True)[-1] <NEW_LINE> last_string.replace_with(last_string.string + self.more_string) <NEW_LINE> return soup
Build an HTML preview of an HTML content.
62598fad460517430c432049
class DeleteOwnComment(permissions.BasePermission): <NEW_LINE> <INDENT> def has_object_permission(self, request, view, obj): <NEW_LINE> <INDENT> if request.method in permissions.SAFE_METHODS: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return request.user.is_superuser or obj.author == request.user
Allow admin and user to delete their own thread or comment
62598fadd268445f26639b6f
class UserInput: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.X_train, self.y_train = None, None <NEW_LINE> self.class_type = None <NEW_LINE> self.filename = None <NEW_LINE> self.result_path = './result' <NEW_LINE> self.kernel_type = None <NEW_LINE> self.rect_kernel = 1 <NEW_LINE> self.test_method_tuple = None <NEW_LINE> self.lower_b_c, self.upper_b_c = None, None <NEW_LINE> self.lower_b_u, self.upper_b_u = None, None
This class stores user inputs
62598fad3539df3088ecc28b
class ClouduseraccountsGlobalAccountsOperationsListRequest(_messages.Message): <NEW_LINE> <INDENT> filter = _messages.StringField(1) <NEW_LINE> maxResults = _messages.IntegerField(2, variant=_messages.Variant.UINT32, default=500) <NEW_LINE> orderBy = _messages.StringField(3) <NEW_LINE> pageToken = _messages.StringField(4) <NEW_LINE> project = _messages.StringField(5, required=True)
A ClouduseraccountsGlobalAccountsOperationsListRequest object. Fields: filter: Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: field_name comparison_string literal_string. The field_name is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The comparison_string must be either eq (equals) or ne (not equals). The literal_string is the string value to filter to. The literal value must be valid for the type of field you are filtering by (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. For example, to filter for instances that do not have a name of example-instance, you would use filter=name ne example-instance. You can filter on nested fields. For example, you could filter on instances that have set the scheduling.automaticRestart field to true. Use filtering on nested fields to take advantage of labels to organize and search for results based on label values. To filter on multiple expressions, provide each separate expression within parentheses. For example, (scheduling.automaticRestart eq true) (zone eq us-central1-f). Multiple expressions are treated as AND expressions, meaning that resources must match all expressions to pass the filters. maxResults: The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. orderBy: Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name. You can also sort results in descending order based on the creation timestamp using orderBy="creationTimestamp desc". This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first. Currently, only sorting by name or creationTimestamp desc is supported. pageToken: Specifies a page token to use. Set pageToken to the nextPageToken returned by a previous list request to get the next page of results. project: Project ID for this request.
62598fad627d3e7fe0e06e86
class UseJSONTests(APITestCase): <NEW_LINE> <INDENT> def test_accept_and_return_json(self): <NEW_LINE> <INDENT> response = self.api_client.get(self.catalogus_list_url) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> self.assertEqual(response['content-type'], 'application/json') <NEW_LINE> <DEDENT> @skip('Optional and currently not supported.') <NEW_LINE> def test_json_schema_support(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @skip('Optional and currently not supported.') <NEW_LINE> def test_content_negotiation_xml(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_content_negotiation_unsupported_format(self): <NEW_LINE> <INDENT> response = self.api_client.get(self.catalogus_list_url, HTTP_ACCEPT='text/html') <NEW_LINE> self.assertEqual(response.status_code, 406) <NEW_LINE> <DEDENT> @skip('This API is currently read-only.') <NEW_LINE> def test_content_type_header_is_required(self): <NEW_LINE> <INDENT> response = self.api_client.put(self.catalogus_detail_url, '{}', content_type='text/html') <NEW_LINE> self.assertEqual(response.status_code, 415) <NEW_LINE> <DEDENT> def test_camelcase_field_names(self): <NEW_LINE> <INDENT> response = self.api_client.get(self.catalogus_detail_url) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> data = response.json() <NEW_LINE> self.assertTrue('contactpersoonBeheerNaam' in data) <NEW_LINE> <DEDENT> def test_no_pretty_print(self): <NEW_LINE> <INDENT> response = self.api_client.get(self.catalogus_detail_url) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> raw_data = response.content.decode('utf-8') <NEW_LINE> self.assertFalse(' ' in raw_data, raw_data) <NEW_LINE> self.assertFalse('\n' in raw_data) <NEW_LINE> <DEDENT> def test_no_envelope(self): <NEW_LINE> <INDENT> response = self.api_client.get(self.catalogus_detail_url) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> data = response.json() <NEW_LINE> self.assertTrue('contactpersoonBeheerNaam' in data) <NEW_LINE> <DEDENT> @skip('This API is currently read-only.') <NEW_LINE> def test_content_type_json_is_supported(self): <NEW_LINE> <INDENT> response = self.api_client.patch(self.catalogus_detail_url, '{}') <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> response = self.api_client.put(self.catalogus_detail_url, '{}') <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> response = self.api_client.post(self.catalogus_list_url, '{}') <NEW_LINE> self.assertEqual(response.status_code, 201) <NEW_LINE> <DEDENT> @skip('This API is currently read-only.') <NEW_LINE> def test_content_type_x_is_not_supported(self): <NEW_LINE> <INDENT> response = self.api_client.patch(self.catalogus_detail_url, '{}', content_type='application/x-www-form-urlencoded') <NEW_LINE> self.assertEqual(response.status_code, 415) <NEW_LINE> response = self.api_client.put(self.catalogus_detail_url, '{}', content_type='application/x-www-form-urlencoded') <NEW_LINE> self.assertEqual(response.status_code, 415) <NEW_LINE> response = self.api_client.post(self.catalogus_list_url, '{}', content_type='application/x-www-form-urlencoded') <NEW_LINE> self.assertEqual(response.status_code, 415)
Section 2.6.5 of the DSO: API strategy
62598fadd58c6744b42dc2c3
class symbolic_dttmm_system_common_params(symbolic_dttmm_system): <NEW_LINE> <INDENT> def gen_list_of_all_params(self, params={}): <NEW_LINE> <INDENT> symbolic_dttmm_system.gen_list_of_all_params(self) <NEW_LINE> self.all_params.extend(params.keys()) <NEW_LINE> return self.all_params
Symbolic DT-TMM stuff doesn't work very well if there are more than a few elements. Before I completely scrap the idea, I want to see what happens if all of the TSD and rigid mass elements have the same properties, as would be the case for a uniform beam broken into pieces.
62598fad442bda511e95c430
class _SaverDict(_SaverMutable, MutableMapping): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> self._data = dict() <NEW_LINE> <DEDENT> def has_key(self, key): <NEW_LINE> <INDENT> return key in self._data <NEW_LINE> <DEDENT> @_save <NEW_LINE> def update(self, *args, **kwargs): <NEW_LINE> <INDENT> self._data.update(*args, **kwargs)
A dict that stores changes to an Attribute when updated
62598fad63d6d428bbee2784
class dl_select(OC_Dialogo): <NEW_LINE> <INDENT> def __init__(self,padre,fichero,campos,preguntas): <NEW_LINE> <INDENT> OC_Dialogo.__init__(self, padre,'Selección de Registros',tam=(580,520),btn=False) <NEW_LINE> preg=[] <NEW_LINE> lsfmt=[] <NEW_LINE> i=0 <NEW_LINE> for ln in preguntas: <NEW_LINE> <INDENT> titu,op,valor,campo,fmt,lmax = ln <NEW_LINE> preg.append([titu,op,valor,campo]) <NEW_LINE> lsfmt.append([fmt,i,lmax]) <NEW_LINE> i+=1 <NEW_LINE> <DEDENT> self._fichero = fichero <NEW_LINE> self._preguntas = preg <NEW_LINE> self._campos = campos <NEW_LINE> self._res = None <NEW_LINE> self._prg = [] <NEW_LINE> p1 = ['PANEL','P1',0,0,-1,-1,'','','',[]] <NEW_LINE> cols = [] <NEW_LINE> cols.append(['Pregunta',17,'l',0,'n','','','','','','','','','']) <NEW_LINE> cols.append(['Op',3,'l',0,'n','','','','','','','','','']) <NEW_LINE> cols.append(['Valor',13,'l',0,'','','','','','','','','','']) <NEW_LINE> cols.append(['Campo',5,'l',0,'i','','','','','','','','','']) <NEW_LINE> p1[-1].append(['GRID','G1','Búsqueda Selectiva',10,10,370,22,7,cols,1,[],'']) <NEW_LINE> btn=[] <NEW_LINE> btn.append(['B2',90,290,100,'good.png','Aceptar','a_aceptar','']) <NEW_LINE> btn.append(['B3',250,290,100,'error.png','Salir','a_salir','']) <NEW_LINE> p1[-1].append(['BUTTONS','BID',45,'','',btn]) <NEW_LINE> ls_campos = [] <NEW_LINE> ls_campos.append(p1) <NEW_LINE> self.init_ctrls(ls_campos) <NEW_LINE> grid = self._ct['G1'] <NEW_LINE> for ln in lsfmt: <NEW_LINE> <INDENT> fmt,fila,lmax = ln <NEW_LINE> grid.SetFmt(fmt,2,fila) <NEW_LINE> <DEDENT> grid.SetValue(preguntas) <NEW_LINE> grid.SetCursor(0,2) <NEW_LINE> self.ShowModal() <NEW_LINE> <DEDENT> def Ejecuta_Accion(self,accion,obj=None): <NEW_LINE> <INDENT> if accion=='a_aceptar': <NEW_LINE> <INDENT> fichero = self._fichero <NEW_LINE> campos = self._campos <NEW_LINE> preguntas = self._ct['G1'].GetValue() <NEW_LINE> preg=[] <NEW_LINE> for lnp in preguntas: <NEW_LINE> <INDENT> deno,op,valor,campo= lnp <NEW_LINE> if valor in ['',None,0]: continue <NEW_LINE> preg.append([campo,op,valor]) <NEW_LINE> <DEDENT> tabla = OC.db.Table(fichero) <NEW_LINE> resul = tabla.select(campos, preg) <NEW_LINE> resul.sort() <NEW_LINE> self._res = [] <NEW_LINE> for ln in resul: <NEW_LINE> <INDENT> self._res.append(list(ln)) <NEW_LINE> <DEDENT> self._prg = preg <NEW_LINE> self.Close() <NEW_LINE> <DEDENT> elif accion=='a_salir': <NEW_LINE> <INDENT> self._res = None <NEW_LINE> self._prg = [] <NEW_LINE> self.Close() <NEW_LINE> <DEDENT> return 1 <NEW_LINE> <DEDENT> def res(self): <NEW_LINE> <INDENT> res = self._res <NEW_LINE> prg = self._prg <NEW_LINE> self.Destroy() <NEW_LINE> return (res,prg)
Dialogo de selección de registros, pone en lista destino
62598fad63b5f9789fe85140
class DiagonalOperator(SymmetricOperator): <NEW_LINE> <INDENT> def __init__(self, diag, **kwargs): <NEW_LINE> <INDENT> shape = 2 * (diag.size,) <NEW_LINE> self.diag = diag <NEW_LINE> matvec = lambda x: x * diag <NEW_LINE> SymmetricOperator.__init__(self, shape, matvec, **kwargs) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> s = LinearOperator.__repr__(self) <NEW_LINE> return s[:-1] + ",\n diagonal=" + self.diag.__repr__() + ">"
An operator which mimics a diagonal matrix. Attributes ---------- diag: ndarray of 1 dim The diagonal of the matrix.
62598fad2ae34c7f260ab0bb
class ASGIApp(engineio.ASGIApp): <NEW_LINE> <INDENT> def __init__(self, socketio_server, other_asgi_app=None, static_files=None, socketio_path='socket.io'): <NEW_LINE> <INDENT> super().__init__(socketio_server, other_asgi_app, static_files=static_files, engineio_path=socketio_path)
ASGI application middleware for Socket.IO. This middleware dispatches traffic to an Socket.IO application. It can also serve a list of static files to the client, or forward unrelated HTTP traffic to another ASGI application. :param socketio_server: The Socket.IO server. Must be an instance of the ``socketio.AsyncServer`` class. :param static_files: A dictionary with static file mapping rules. See the documentation for details on this argument. :param other_asgi_app: A separate ASGI app that receives all other traffic. :param socketio_path: The endpoint where the Socket.IO application should be installed. The default value is appropriate for most cases. Example usage:: import socketio import uvicorn sio = socketio.AsyncServer() app = engineio.ASGIApp(sio, static_files={ '/': 'index.html', '/static': './public', }) uvicorn.run(app, host='127.0.0.1', port=5000)
62598fad99cbb53fe6830eb1
class RunnerThread(QThread): <NEW_LINE> <INDENT> def __init__(self, ip="127.0.0.1", port=8000, app=None): <NEW_LINE> <INDENT> QThread.__init__(self) <NEW_LINE> self.ip = ip <NEW_LINE> self.port = port <NEW_LINE> self.app = app <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> self.stopper = thevent() <NEW_LINE> monkey.patch_socket() <NEW_LINE> self.app.config['LOCALADDR'] = str(self.ip) <NEW_LINE> self.server = pywsgi.WSGIServer((str(self.ip), int(self.port)), self.app, log=None) <NEW_LINE> self.server.start() <NEW_LINE> self.stopper.wait() <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> self.stopper.set() <NEW_LINE> self.server.stop()
PyQT thread to monitor the web server
62598fad236d856c2adc942a
class IDocumentFusion(IGeneration): <NEW_LINE> <INDENT> pass
When this behavior is selected, we generate a fusion of the main file of the document with the fields of the dexterity content.
62598fadbd1bec0571e150b0
class Point(Vector): <NEW_LINE> <INDENT> def __new__(cls, *args): <NEW_LINE> <INDENT> from .plane import Point2 <NEW_LINE> from .space import Point3 <NEW_LINE> if len(args) == 2: <NEW_LINE> <INDENT> return Point2(*args) <NEW_LINE> <DEDENT> elif len(args) == 3: <NEW_LINE> <INDENT> return Point3(*args) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return NotImplemented
A generic constructor that chooses the correct variant of :py:class:`~petrify.plane.Point2` or :py:class:`~petrify.space.Point3` based on argument count: >>> Point(1, 2) Point(1, 2) >>> Point(1, 2, 3) Point(1, 2, 3)
62598fad091ae35668704bf8
@as_function <NEW_LINE> class gauss_stats(IterOnInfs, Stats): <NEW_LINE> <INDENT> exec_name = "gausfitting" <NEW_LINE> names = "MNaseSeq", <NEW_LINE> def fun(self, f, genome_dir, out_dir): <NEW_LINE> <INDENT> _, base = PathHelpers.base_name(f["file_path"]) <NEW_LINE> input = PathHelpers.build_path(base, out_dir, "gff", "STF") <NEW_LINE> out_genes = PathHelpers.build_path(base, out_dir, "csv", "STF", "genes_stats") <NEW_LINE> out_gw = PathHelpers.build_path(base, out_dir, "csv", "STF", "stats1") <NEW_LINE> out_gw2 = PathHelpers.build_path(base, out_dir, "png", "STF", "stats2") <NEW_LINE> assembly = f["meta_data"]["assembly"] <NEW_LINE> genome = PathHelpers.get_genes_f(assembly, genome_dir) <NEW_LINE> args = {"input": input, "genome": genome, "out_genes": out_genes, "out_gw": out_gw, "out_gw2": out_gw2} <NEW_LINE> meta = [out_genes, out_gw, out_gw2] <NEW_LINE> return args, meta
Gaussian fitting and stiffness constant estimation statistics
62598fadf7d966606f747fbf
class accuracy(loss_metric): <NEW_LINE> <INDENT> def __call__(self, labels, result): <NEW_LINE> <INDENT> batch_size = result.shape[0] <NEW_LINE> choices = np.argmax(result, axis=-1) <NEW_LINE> pct = np.count_nonzero(choices == np.where(labels == 1)[1]) * 100. / batch_size <NEW_LINE> return f'{pct:.2f}%'
Computes percentage of one-hot outputs from a softmax n-class classifier that match the given labels
62598fad8e7ae83300ee907c
class SampleView(grok.View): <NEW_LINE> <INDENT> grok.context(IProfile) <NEW_LINE> grok.require('zope2.View') <NEW_LINE> grok.name('view') <NEW_LINE> def get_current(self): <NEW_LINE> <INDENT> return api.user.get_current() <NEW_LINE> <DEDENT> def has_permission(self, permission, user, obj): <NEW_LINE> <INDENT> if api.user.is_anonymous(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if user.getId() == 'admin': <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return api.user.has_permission(permission, user=user, obj=obj) <NEW_LINE> <DEDENT> def checkPermission(self, permissionString): <NEW_LINE> <INDENT> return checkPermission(permissionString, self.context) <NEW_LINE> <DEDENT> def getBrain(self): <NEW_LINE> <INDENT> context = self.context <NEW_LINE> request = context.REQUEST <NEW_LINE> catalog = context.portal_catalog <NEW_LINE> ownerId = context.owner_info()['id'] <NEW_LINE> t = request.get('t') <NEW_LINE> if t == 'info': <NEW_LINE> <INDENT> queryList = ['Info'] <NEW_LINE> <DEDENT> elif t == 'article': <NEW_LINE> <INDENT> queryList = ['Article'] <NEW_LINE> <DEDENT> elif t == 'review': <NEW_LINE> <INDENT> queryList = ['Review', 'Quarterly'] <NEW_LINE> <DEDENT> elif t == 'artandlife': <NEW_LINE> <INDENT> queryList = ['ArtAndLife'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> queryList = ['Info', 'Review', 'Article', 'ArtAndLife', 'Quarterly'] <NEW_LINE> <DEDENT> brain = catalog({'Creator':ownerId, 'Type':queryList}, sort_on='created', sort_order='reverse') <NEW_LINE> return brain <NEW_LINE> <DEDENT> def toLocalizedTime(self, time, long_format=None, time_only=None): <NEW_LINE> <INDENT> util = api.portal.get_tool(name='translation_service') <NEW_LINE> return util.ulocalized_time(time, long_format, time_only, self.context, domain='plonelocales')
sample view class
62598fad460517430c43204a
class AbstractGlobalGeometer( object): <NEW_LINE> <INDENT> def __init__(self, target): <NEW_LINE> <INDENT> self.target = target <NEW_LINE> return <NEW_LINE> <DEDENT> def displacement( self, element1, element2): <NEW_LINE> <INDENT> self._abstract( "displacement" ) <NEW_LINE> <DEDENT> def distance(self, element1, element2 ): <NEW_LINE> <INDENT> self._abstract( "distance" ) <NEW_LINE> <DEDENT> def orientation( self, element): <NEW_LINE> <INDENT> self._abstract( "orientation" ) <NEW_LINE> <DEDENT> def position( self, element): <NEW_LINE> <INDENT> self._abstract( "position" ) <NEW_LINE> <DEDENT> def getCoordinateSystemDescription( self): <NEW_LINE> <INDENT> self._abstract( "getCoordinateSystemDescription" ) <NEW_LINE> <DEDENT> def _abstract(self, method): <NEW_LINE> <INDENT> raise NotImplementedError( "class '%s' should override method '%s'" % (self.__class__.__name__, method)) <NEW_LINE> <DEDENT> pass
Maintain positions and orientations of elements in a hierarchial structure. each layer in the hierarchy will have a local geometer. measures displacements between elements.
62598fad851cf427c66b8296
class Light(object): <NEW_LINE> <INDENT> @property <NEW_LINE> def illumination(self): <NEW_LINE> <INDENT> return self._get_illumination() <NEW_LINE> <DEDENT> def enable(self): <NEW_LINE> <INDENT> self._enable() <NEW_LINE> <DEDENT> def disable(self): <NEW_LINE> <INDENT> self._disable() <NEW_LINE> <DEDENT> def _get_illumination(self, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def _enable(self, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def _disable(self, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError()
Light facade. Light sensor measures the ambient light level(illumination) in lx. Common uses include controlling screen brightness. With method `enable` you can turn on the sensor and `disable` method stops the sensor. Use property `illumination` to get current illumination in lx. .. versionadded:: 1.2.5
62598fada219f33f346c67f0
class FullFieldBinaryPattern(Sequence): <NEW_LINE> <INDENT> def __init__(self, binary_pattern, rate): <NEW_LINE> <INDENT> binary_pattern = self.format_binary_pattern(binary_pattern) <NEW_LINE> bit_planes = 1 <NEW_LINE> pic_num = len(binary_pattern) <NEW_LINE> picture_time = int(1.0e+6 / rate) <NEW_LINE> Sequence.__init__(self, bit_planes, pic_num, picture_time=picture_time) <NEW_LINE> self.binary_pattern = binary_pattern <NEW_LINE> self.rate = rate <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def format_binary_pattern(binary_pattern): <NEW_LINE> <INDENT> if isinstance(binary_pattern, str): <NEW_LINE> <INDENT> dataframe = pandas.read_csv(binary_pattern, sep=';') <NEW_LINE> binary_pattern = dataframe['bit'].values <NEW_LINE> <DEDENT> binary_pattern = [255 if bit else 0 for bit in binary_pattern] <NEW_LINE> binary_pattern = numpy.array(binary_pattern, dtype=numpy.uint8) <NEW_LINE> binary_pattern = binary_pattern[:, numpy.newaxis, numpy.newaxis] <NEW_LINE> return binary_pattern <NEW_LINE> <DEDENT> def get_user_array(self): <NEW_LINE> <INDENT> width, height = self.device.get_resolution() <NEW_LINE> nb_repetitions = (1, height, width) <NEW_LINE> frames = numpy.tile(self.binary_pattern, nb_repetitions) <NEW_LINE> return frames
Full-field binary pattern sequence Parameters ---------- binary_pattern: list or string rate: float Frame rate [Hz].
62598fade5267d203ee6b8e3
class protectedBlock(protected): <NEW_LINE> <INDENT> withCursor = False
Same as L{protected} but without a cursor.
62598fad32920d7e50bc602e
class CosineDecayPruneScheduler(PruneSchedulerBase): <NEW_LINE> <INDENT> def __init__(self, prune_fraction, total_steps, warmup_steps=0): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.prune_fraction = prune_fraction <NEW_LINE> self.total_steps = total_steps - warmup_steps <NEW_LINE> self.warmup_steps = warmup_steps <NEW_LINE> <DEDENT> def get_prune_fraction(self): <NEW_LINE> <INDENT> step_count = self._step_count - self.warmup_steps <NEW_LINE> if step_count < 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> return 0.5 * self.prune_fraction * ( 1 + np.cos((step_count * np.pi) / (self.total_steps - 1)) ) <NEW_LINE> <DEDENT> def get_num_add(self, num_removed): <NEW_LINE> <INDENT> return num_removed
This class enables a tapering of an initial pruning-rate while `get_num_add` always returns how much has been removed. :param prune_fraction: starting pruning rate between 0 and 1 :param total_steps: total number of steps of training; this can be training iterations or epochs depending on how often the user calls self.step() :param warmup_steps: how many steps to wait before pruning starts
62598fadbe383301e02537d3
@unittest.skipIf(storage_type == 'db', 'skip if environ is db') <NEW_LINE> class TestFileStorageDocs(unittest.TestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setUpClass(cls): <NEW_LINE> <INDENT> print('\n\n.................................') <NEW_LINE> print('..... Testing Documentation .....') <NEW_LINE> print('..... For FileStorage Class .....') <NEW_LINE> print('.................................\n\n') <NEW_LINE> <DEDENT> def test_doc_file(self): <NEW_LINE> <INDENT> expected = ("\nHandles I/O, writing and reading, of JSON for storage " "of all class instances\n") <NEW_LINE> actual = models.file_storage.__doc__ <NEW_LINE> self.assertEqual(expected, actual) <NEW_LINE> <DEDENT> def test_doc_class(self): <NEW_LINE> <INDENT> expected = 'handles long term storage of all class instances' <NEW_LINE> actual = FileStorage.__doc__ <NEW_LINE> self.assertEqual(expected, actual) <NEW_LINE> <DEDENT> def test_doc_all(self): <NEW_LINE> <INDENT> expected = 'returns private attribute: __objects' <NEW_LINE> actual = FileStorage.all.__doc__ <NEW_LINE> self.assertEqual(expected, actual) <NEW_LINE> <DEDENT> def test_doc_new(self): <NEW_LINE> <INDENT> expected = ("sets / updates in __objects the obj with key <obj class " "name>.id") <NEW_LINE> actual = FileStorage.new.__doc__ <NEW_LINE> self.assertEqual(expected, actual) <NEW_LINE> <DEDENT> def test_doc_save(self): <NEW_LINE> <INDENT> expected = 'serializes __objects to the JSON file (path: __file_path)' <NEW_LINE> actual = FileStorage.save.__doc__ <NEW_LINE> self.assertEqual(expected, actual) <NEW_LINE> <DEDENT> def test_doc_reload(self): <NEW_LINE> <INDENT> expected = ("if file exists, deserializes JSON file to __objects, " "else nothing") <NEW_LINE> actual = FileStorage.reload.__doc__ <NEW_LINE> self.assertEqual(expected, actual) <NEW_LINE> <DEDENT> def test_doc_get(self): <NEW_LINE> <INDENT> expected = ' retrieves one object ' <NEW_LINE> actual = FileStorage.get.__doc__ <NEW_LINE> self.assertEqual(expected, actual) <NEW_LINE> <DEDENT> def test_doc_count(self): <NEW_LINE> <INDENT> expected = ' counts number of objects of a class in storage ' <NEW_LINE> actual = FileStorage.count.__doc__ <NEW_LINE> self.assertEqual(expected, actual)
Class for testing BaseModel docs
62598fad7b180e01f3e4903d
class BucketScanLog(object): <NEW_LINE> <INDENT> def __init__(self, log_dir, name): <NEW_LINE> <INDENT> self.log_dir = log_dir <NEW_LINE> self.name = name <NEW_LINE> self.fh = None <NEW_LINE> self.count = 0 <NEW_LINE> <DEDENT> @property <NEW_LINE> def path(self): <NEW_LINE> <INDENT> return os.path.join(self.log_dir, "%s.json" % self.name) <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> if self.log_dir is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.fh = open(self.path, 'w') <NEW_LINE> self.fh.write("[\n") <NEW_LINE> return self <NEW_LINE> <DEDENT> def __exit__(self, exc_type=None, exc_value=None, exc_frame=None): <NEW_LINE> <INDENT> if self.fh is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.fh.write("[]") <NEW_LINE> self.fh.write("\n]") <NEW_LINE> self.fh.close() <NEW_LINE> if not self.count: <NEW_LINE> <INDENT> os.remove(self.fh.name) <NEW_LINE> <DEDENT> self.fh = None <NEW_LINE> return False <NEW_LINE> <DEDENT> def add(self, keys): <NEW_LINE> <INDENT> self.count += len(keys) <NEW_LINE> if self.fh is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.fh.write(dumps(keys)) <NEW_LINE> self.fh.write(",\n")
Offload remediated key ids to a disk file in batches A bucket keyspace is effectively infinite, we need to store partial results out of memory, this class provides for a json log on disk with partial write support. json output format: - [list_of_serialized_keys], - [] # Empty list of keys at end when we close the buffer
62598fada05bb46b3848a846
class BbcodeAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> pass
Custom BBCodes
62598fadd486a94d0ba2bfa9
class AtomicFile(object): <NEW_LINE> <INDENT> def __init__(self, name, mode="w+b", createmode=None, encoding=None): <NEW_LINE> <INDENT> self.__name = name <NEW_LINE> self._tempname = _maketemp(name, createmode=createmode) <NEW_LINE> if encoding: <NEW_LINE> <INDENT> self._fp = codecs.open(self._tempname, mode, encoding) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._fp = open(self._tempname, mode) <NEW_LINE> <DEDENT> self.write = self._fp.write <NEW_LINE> self.fileno = self._fp.fileno <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __exit__(self, exc_type, exc_value, exc_tb): <NEW_LINE> <INDENT> if exc_type: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.close() <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> if not self._fp.closed: <NEW_LINE> <INDENT> self._fp.close() <NEW_LINE> if os.name == 'nt' and os.path.exists(self.__name): <NEW_LINE> <INDENT> os.remove(self.__name) <NEW_LINE> <DEDENT> os.rename(self._tempname, self.__name) <NEW_LINE> <DEDENT> <DEDENT> def discard(self): <NEW_LINE> <INDENT> if not self._fp.closed: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> os.unlink(self._tempname) <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self._fp.close() <NEW_LINE> <DEDENT> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> if getattr(self, "_fp", None): <NEW_LINE> <INDENT> self.discard()
This is a straight port of Alexander Saltanov's atomicfile package. Writeable file object that atomically writes a file. All writes will go to a temporary file. Call ``close()`` when you are done writing, and AtomicFile will rename the temporary copy to the original name, making the changes visible. If the object is destroyed without being closed, all your writes are discarded. If an ``encoding`` argument is specified, codecs.open will be called to open the file in the wanted encoding.
62598fad7c178a314d78d477
class Config(dict): <NEW_LINE> <INDENT> def configure(self, **params): <NEW_LINE> <INDENT> self.update(params) <NEW_LINE> <DEDENT> def dns_configure(self, **params): <NEW_LINE> <INDENT> self['dns_params'].update(params)
Base config
62598fad4527f215b58e9ebb
class BaseGeometry: <NEW_LINE> <INDENT> def area(self): <NEW_LINE> <INDENT> raise Exception("area() is not implemented")
BaseGeometry empty class
62598fad01c39578d7f12d59
class Bookmark(object): <NEW_LINE> <INDENT> def __init__(self, beginRow, endRow, data): <NEW_LINE> <INDENT> self.__begin = int(beginRow) <NEW_LINE> self.__end = int(endRow) <NEW_LINE> self.data = data <NEW_LINE> <DEDENT> @property <NEW_LINE> def range(self): <NEW_LINE> <INDENT> return (self.begin, self.end) <NEW_LINE> <DEDENT> @range.setter <NEW_LINE> def range(self, value): <NEW_LINE> <INDENT> self.__begin, self.__end = sorted(int(x) for x in value) <NEW_LINE> <DEDENT> @property <NEW_LINE> def begin(self): <NEW_LINE> <INDENT> return self.__begin <NEW_LINE> <DEDENT> @begin.setter <NEW_LINE> def begin(self, value): <NEW_LINE> <INDENT> self.__begin, self.__end = sorted(int(x) for x in (value, self.__end)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def end(self): <NEW_LINE> <INDENT> return self.__end <NEW_LINE> <DEDENT> @end.setter <NEW_LINE> def end(self, value): <NEW_LINE> <INDENT> self.__begin, self.__end = sorted(int(x) for x in (self.__begin, value)) <NEW_LINE> <DEDENT> def overlaps(self, bookmark): <NEW_LINE> <INDENT> begin1, end1 = self.range <NEW_LINE> begin2, end2 = bookmark.range <NEW_LINE> return begin1 <= end2 and end1 >= begin2 <NEW_LINE> <DEDENT> def __contains__(self, row): <NEW_LINE> <INDENT> return self.begin <= row <= self.end <NEW_LINE> <DEDENT> def __lt__(self, other): <NEW_LINE> <INDENT> assert isinstance(other, Bookmark) <NEW_LINE> return self.range < other.range <NEW_LINE> <DEDENT> def __gt__(self, other): <NEW_LINE> <INDENT> assert isinstance(other, Bookmark) <NEW_LINE> return self.range > other.range <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> assert isinstance(other, Bookmark) <NEW_LINE> return self.range == other.range <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> assert isinstance(other, Bookmark) <NEW_LINE> return self.range != other.range <NEW_LINE> <DEDENT> def __le__(self, other): <NEW_LINE> <INDENT> assert isinstance(other, Bookmark) <NEW_LINE> return self.range <= other.range <NEW_LINE> <DEDENT> def __ge__(self, other): <NEW_LINE> <INDENT> assert isinstance(other, Bookmark) <NEW_LINE> return self.range >= other.range <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash(self.range) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return repr(self.range)
This bookmark object is used as a marker for different places in a text document. Note that because text buffer lines index at 0, all references to rows also assume that 0 is the first line.
62598fadd58c6744b42dc2c4
class VoVInitBlock(nn.Module): <NEW_LINE> <INDENT> def __init__(self, in_channels, out_channels): <NEW_LINE> <INDENT> super(VoVInitBlock, self).__init__() <NEW_LINE> mid_channels = out_channels // 2 <NEW_LINE> self.conv1 = conv3x3_block( in_channels=in_channels, out_channels=mid_channels, stride=2) <NEW_LINE> self.conv2 = conv3x3_block( in_channels=mid_channels, out_channels=mid_channels) <NEW_LINE> self.conv3 = conv3x3_block( in_channels=mid_channels, out_channels=out_channels, stride=2) <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> x = self.conv1(x) <NEW_LINE> x = self.conv2(x) <NEW_LINE> x = self.conv3(x) <NEW_LINE> return x
VoVNet specific initial block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels.
62598fad76e4537e8c3ef588
class InlineResponse20023(object): <NEW_LINE> <INDENT> openapi_types = { 'items': 'list[XenonntNvetoPmtError]' } <NEW_LINE> attribute_map = { 'items': '_items' } <NEW_LINE> def __init__(self, items=None, local_vars_configuration=None): <NEW_LINE> <INDENT> if local_vars_configuration is None: <NEW_LINE> <INDENT> local_vars_configuration = Configuration() <NEW_LINE> <DEDENT> self.local_vars_configuration = local_vars_configuration <NEW_LINE> self._items = None <NEW_LINE> self.discriminator = None <NEW_LINE> if items is not None: <NEW_LINE> <INDENT> self.items = items <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def items(self): <NEW_LINE> <INDENT> return self._items <NEW_LINE> <DEDENT> @items.setter <NEW_LINE> def items(self, items): <NEW_LINE> <INDENT> self._items = items <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.openapi_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 pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, InlineResponse20023): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.to_dict() == other.to_dict() <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, InlineResponse20023): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.to_dict() != other.to_dict()
NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually.
62598fadf548e778e596b57f
class UserSession(models.Model): <NEW_LINE> <INDENT> user = models.ForeignKey(settings.AUTH_USER_MODEL) <NEW_LINE> session = models.ForeignKey(Session)
User<->Session model Model for linking user to session. Solution from http://gavinballard.com/associating-django-users-sessions/
62598fad63b5f9789fe85142
class SyncDaemonConfigParser(TypedConfigParser): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(SyncDaemonConfigParser, self).__init__(*args, **kwargs) <NEW_LINE> self.upgrade_hooks = {} <NEW_LINE> for name, parser in get_parsers(): <NEW_LINE> <INDENT> self.add_parser(name, parser) <NEW_LINE> <DEDENT> self.add_upgrade_hook(MAIN, 'log_level', upgrade_log_level) <NEW_LINE> <DEDENT> def add_upgrade_hook(self, section, option, func): <NEW_LINE> <INDENT> if (section, option) in self.upgrade_hooks: <NEW_LINE> <INDENT> raise ValueError('An upgrade hook for %s, %s already exists' % (section, option)) <NEW_LINE> <DEDENT> self.upgrade_hooks[(section, option)] = func <NEW_LINE> <DEDENT> def parse_all(self): <NEW_LINE> <INDENT> super(SyncDaemonConfigParser, self).parse_all() <NEW_LINE> self.upgrade_all() <NEW_LINE> <DEDENT> def upgrade_all(self): <NEW_LINE> <INDENT> for section, option in self.upgrade_hooks: <NEW_LINE> <INDENT> if self.has_option(section, option): <NEW_LINE> <INDENT> self.upgrade_hooks[(section, option)](self)
Custom TypedConfigParser with upgrade support and syncdaemon parsers.
62598fad99cbb53fe6830eb3
class Platform(object): <NEW_LINE> <INDENT> def __init__(self, name="None", vendor="None", version=None, extensions=None, idx=0): <NEW_LINE> <INDENT> self.name = name.strip() <NEW_LINE> self.vendor = vendor.strip() <NEW_LINE> self.version = version <NEW_LINE> self.extensions = extensions.split() <NEW_LINE> self.devices = [] <NEW_LINE> self.id = idx <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "%s" % self.name <NEW_LINE> <DEDENT> def add_device(self, device): <NEW_LINE> <INDENT> self.devices.append(device) <NEW_LINE> <DEDENT> def get_device(self, key): <NEW_LINE> <INDENT> out = None <NEW_LINE> try: <NEW_LINE> <INDENT> devid = int(key) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> for a_dev in self.devices: <NEW_LINE> <INDENT> if a_dev.name == key: <NEW_LINE> <INDENT> out = a_dev <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if len(self.devices) > devid > 0: <NEW_LINE> <INDENT> out = self.devices[devid] <NEW_LINE> <DEDENT> <DEDENT> return out
Simple class that contains the structure of an OpenCL platform
62598fad0c0af96317c5635e
class RangeFeature(featuresModule.FeatureExtractor): <NEW_LINE> <INDENT> id = 'P10' <NEW_LINE> def __init__(self, dataOrStream=None, *arguments, **keywords): <NEW_LINE> <INDENT> super().__init__(dataOrStream=dataOrStream, *arguments, **keywords) <NEW_LINE> self.name = 'Range' <NEW_LINE> self.description = 'Difference between highest and lowest pitches.' <NEW_LINE> self.isSequential = True <NEW_LINE> self.dimensions = 1 <NEW_LINE> <DEDENT> def process(self): <NEW_LINE> <INDENT> histo = self.data['pitches.midiPitchHistogram'] <NEW_LINE> if not histo: <NEW_LINE> <INDENT> raise JSymbolicFeatureException('input lacks notes') <NEW_LINE> <DEDENT> minIndex = min(histo.keys()) <NEW_LINE> maxIndex = max(histo.keys()) <NEW_LINE> self.feature.vector[0] = maxIndex - minIndex
Difference between highest and lowest pitches. In semitones >>> s = corpus.parse('bwv66.6') >>> fe = features.jSymbolic.RangeFeature(s) >>> fe.extract().vector [34]
62598fadf7d966606f747fc1
class ActorSerializer(ModelSerializer): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = Actor <NEW_LINE> fields = ('id', 'first_name', 'last_name')
Simple serializer
62598fad5fcc89381b26613a
class Dimensions(namedtuple('Dimensions', ['x', 'y'])): <NEW_LINE> <INDENT> pass
Dimensions.
62598fada219f33f346c67f2
class RelocateCommand(CCCommand): <NEW_LINE> <INDENT> KEYWORDS = { 'en': ['reloc'], 'fr': ['reloc'], } <NEW_LINE> LOCATION_MOVED = 'X' <NEW_LINE> @authenticated <NEW_LINE> def process(self): <NEW_LINE> <INDENT> if 'encounter_date' not in self.message.__dict__: <NEW_LINE> <INDENT> self.message.respond(_(u'Cannot run reloc command from ' 'cell phone. Use the computer interface ' 'instead.'), 'error') <NEW_LINE> return True <NEW_LINE> <DEDENT> if self.params.__len__() != 3: <NEW_LINE> <INDENT> self.message.respond(_(u"Relocate command format: " "reloc LOC HEALTH_ID."), 'error') <NEW_LINE> return True <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> new_chw = CHW.objects.get(pk = self.message.chw) <NEW_LINE> <DEDENT> except CHW.DoesNotExist: <NEW_LINE> <INDENT> self.message.respond(_(u"CHW with ID %(id)d does not exist") % {'id': self.message.chw}) <NEW_LINE> return True <NEW_LINE> <DEDENT> loc_code = self.params[1] <NEW_LINE> health_id = self.params[2] <NEW_LINE> location = None <NEW_LINE> active = (loc_code.upper() != self.LOCATION_MOVED) <NEW_LINE> if active: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> location = Location.objects.get(code=loc_code) <NEW_LINE> <DEDENT> except Patient.DoesNotExist: <NEW_LINE> <INDENT> self.message.respond(_(u"There is no location with code " "%(code)s.") % {'code': loc_code}, 'error') <NEW_LINE> <DEDENT> <DEDENT> person = None <NEW_LINE> try: <NEW_LINE> <INDENT> person = Patient.objects.get(health_id=health_id) <NEW_LINE> <DEDENT> except Patient.DoesNotExist: <NEW_LINE> <INDENT> self.message.respond(_(u"There is no person with " "ID %(hid)s.") % {'hid': health_id}, 'error') <NEW_LINE> <DEDENT> members = Patient .objects .filter(household__health_id=person.household.health_id) <NEW_LINE> msg = u'' <NEW_LINE> if active: <NEW_LINE> <INDENT> count = members.update(location=location, chw=new_chw, status=Patient.STATUS_ACTIVE) <NEW_LINE> msg = _(u"Made status ACTIVE and moved %(count)d people to %(loc)s with CHW %(chw)s: ") % {'loc': location.code.upper(), 'chw': new_chw.full_name(), 'count': count} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> count = members.update(status=Patient.STATUS_INACTIVE) <NEW_LINE> msg = _("Marked %(count)d patients as INACTIVE: ") % {'count': count} <NEW_LINE> <DEDENT> msg += ' '.join([p.health_id.upper() for p in members]) <NEW_LINE> self.message.respond(msg, 'success') <NEW_LINE> return True
Relocate a household Format: reloc LOC_CODE HEALTH_ID Relocates the household containing the patient HEALTH_ID to location LOC_CODE with the current CHW.
62598fadac7a0e7691f724e5
class LimbDarkening: <NEW_LINE> <INDENT> def __init__(self, teff, logg, passband): <NEW_LINE> <INDENT> self.fn = ld_dir+'data/Claret2013_PHOENIX_Nonlinear.tsv' <NEW_LINE> self.teff = teff <NEW_LINE> self.logg = logg <NEW_LINE> self.pb = passband <NEW_LINE> self.round_values() <NEW_LINE> <DEDENT> def round_values(self): <NEW_LINE> <INDENT> self.rteff = np.round(self.teff/250) * 250 <NEW_LINE> self.rlogg = np.round(self.logg/0.5) * 0.5 <NEW_LINE> <DEDENT> def get_data(self): <NEW_LINE> <INDENT> return pd.read_csv(self.fn, sep='\s*\s*', engine='python', header=47)[2:] <NEW_LINE> <DEDENT> def get_ldcs(self): <NEW_LINE> <INDENT> ldcs = np.zeros(4) <NEW_LINE> coeffNames = ['a1', 'a2', 'a3', 'a4'] <NEW_LINE> idx = 0 <NEW_LINE> lddf = self.get_data() <NEW_LINE> for cNm in coeffNames: <NEW_LINE> <INDENT> ldcs[idx] = lddf[((lddf['Teff'] == '{:n}'.format(self.rteff)) & (lddf['logg'] == '{:.2f}'.format(self.rlogg)) & (lddf['Filt'] == self.pb))][cNm].values[0] <NEW_LINE> idx += 1 <NEW_LINE> <DEDENT> return ldcs <NEW_LINE> <DEDENT> def claret_model(self, ldcs): <NEW_LINE> <INDENT> def limb_darkening_function(theta): <NEW_LINE> <INDENT> mu = np.cos(theta) <NEW_LINE> limbdark = 1. - ldcs[0] * (1. - mu**0.5) - ldcs[1] * (1. - mu**1.0) - ldcs[2] * (1. - mu**1.5) - ldcs[3] * (1. - mu**2.0) <NEW_LINE> return limbdark <NEW_LINE> <DEDENT> return limb_darkening_function <NEW_LINE> <DEDENT> def get_eps_eri_ldcs(self): <NEW_LINE> <INDENT> ldcs = np.array([ 0.78552, -0.88512, 1.60631, -0.60365]) <NEW_LINE> return ldcs
The main class that creates a limb darkening object. :param teff: The effective temperature in Kelvin :param logg: The log of the surface gravity :param passband: The passband of interest. Acceptable values are ['Kp', 'C', 'S1', 'S2', 'S3', 'S4', 'u', 'v', 'b', 'y', 'U', 'B', 'V', 'R', 'I', 'J', 'H', 'K', "u'", "g'", "r'", "i'", "z'", 'J2', 'H2', 'Ks']
62598fad16aa5153ce4004de
class PipeOutputImpl(object): <NEW_LINE> <INDENT> def __init__(self) : <NEW_LINE> <INDENT> self.stream = None <NEW_LINE> self.command = [] <NEW_LINE> self.process = [] <NEW_LINE> <DEDENT> def Open(self, command, binary, ignore_stderr = True): <NEW_LINE> <INDENT> if self.stream: <NEW_LINE> <INDENT> LogError('Called on already open file.') <NEW_LINE> <DEDENT> if not command or command[0] != '|': <NEW_LINE> <INDENT> LogError('Invalid command \"%s\"' % command) <NEW_LINE> <DEDENT> self.command = command[1:].split('|') <NEW_LINE> stdin = sys.stdin <NEW_LINE> stderr = DEVNULL if ignore_stderr else sys.stderr <NEW_LINE> for i in xrange(len(self.command)): <NEW_LINE> <INDENT> self.process.append(subprocess.Popen(self.command[i].split(), stdin=stdin, stdout=subprocess.PIPE, stderr=stderr)) <NEW_LINE> stdin = self.process[-1].stdout <NEW_LINE> <DEDENT> self.stream = KaldiOutputStream(self.process[0]) <NEW_LINE> return True <NEW_LINE> <DEDENT> def Stream(self): <NEW_LINE> <INDENT> if not self.stream: <NEW_LINE> <INDENT> LogError('Object not initialized.') <NEW_LINE> <DEDENT> return self.stream <NEW_LINE> <DEDENT> def Close(self): <NEW_LINE> <INDENT> if not self.stream: <NEW_LINE> <INDENT> LogError('Object not initialized.') <NEW_LINE> <DEDENT> self.stream.Flush() <NEW_LINE> return self.stream.Close() <NEW_LINE> <DEDENT> def MyType(self): <NEW_LINE> <INDENT> return OutputType.kPipeOutput
Implementation for pipe outputs, such as '| gzip -c > feats.gz'.
62598fadf9cc0f698b1c52b7
class TradingEngine(object): <NEW_LINE> <INDENT> def __init__(self, redis, strategy, start=None, end=None): <NEW_LINE> <INDENT> self.redis = redis <NEW_LINE> self.pubsub = redis.pubsub() <NEW_LINE> self.strategy = strategy <NEW_LINE> self.start = start <NEW_LINE> self.end = end <NEW_LINE> self.securities = [] <NEW_LINE> <DEDENT> def listen(self, security): <NEW_LINE> <INDENT> self.securities.append(security) <NEW_LINE> self.pubsub.subscribe(security.symbol) <NEW_LINE> <DEDENT> def execute(self, security, tick): <NEW_LINE> <INDENT> action = self.strategy.update(security, tick) <NEW_LINE> if action: <NEW_LINE> <INDENT> self.redis.publish('action', {'action': action, 'tick': tick}) <NEW_LINE> <DEDENT> <DEDENT> def consume(self): <NEW_LINE> <INDENT> for security in self.securities: <NEW_LINE> <INDENT> for tick in self.pubsub.listen(): <NEW_LINE> <INDENT> log.info('New tick {0}'.format(tick)) <NEW_LINE> if tick['type'] in 'subscribe': <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> tick['data'] = json.loads(tick['data'].decode('utf-8').replace("'", '"').replace('u"', '"')) <NEW_LINE> self.execute(security, tick)
has the responsability to execut strategies Sends actions to trading center does not store anything, used for realtime
62598fad7047854f4633f3b6
class WebhookMgr: <NEW_LINE> <INDENT> def __init__(self, authdata): <NEW_LINE> <INDENT> self.authdata = authdata <NEW_LINE> <DEDENT> def getAll(self): <NEW_LINE> <INDENT> response = requests.get(self.authdata.getUrl() + WEBHOOK_WS_URL, auth=(self.authdata.getUsername(), self.authdata.getPassword())) <NEW_LINE> if response.status_code == 200: <NEW_LINE> <INDENT> return response.json()['results'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return response.text <NEW_LINE> <DEDENT> <DEDENT> def get(self, id): <NEW_LINE> <INDENT> response = requests.get(self.authdata.getUrl() + WEBHOOK_WS_URL + '/' + str(id) + "/", auth=(self.authdata.getUsername(), self.authdata.getPassword())) <NEW_LINE> if response.status_code == 200: <NEW_LINE> <INDENT> return response.json() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return response.text <NEW_LINE> <DEDENT> <DEDENT> def create(self, url): <NEW_LINE> <INDENT> headers = {'content-type': 'application/json'} <NEW_LINE> data = {'url': url} <NEW_LINE> response = requests.post(self.authdata.getUrl() + WEBHOOK_WS_URL + "/", data=json.dumps(data), headers=headers, auth=(self.authdata.getUsername(), self.authdata.getPassword())) <NEW_LINE> if response.status_code == 201: <NEW_LINE> <INDENT> return response.json() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return response.text <NEW_LINE> <DEDENT> <DEDENT> def update(self, id, new_url): <NEW_LINE> <INDENT> headers = {'content-type': 'application/json'} <NEW_LINE> data = {'url': new_url} <NEW_LINE> response = requests.put(self.authdata.getUrl() + WEBHOOK_WS_URL + '/' + str(id) + "/", data=json.dumps(data), headers=headers, auth=(self.authdata.getUsername(), self.authdata.getPassword())) <NEW_LINE> if response.status_code == 201: <NEW_LINE> <INDENT> return response.json() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return response.text <NEW_LINE> <DEDENT> <DEDENT> def delete(self, id): <NEW_LINE> <INDENT> headers = {'content-type': 'application/json'} <NEW_LINE> response = requests.delete(self.authdata.getUrl() + WEBHOOK_WS_URL + '/' + str(id) + "/", headers=headers, auth=(self.authdata.getUsername(), self.authdata.getPassword())) <NEW_LINE> if response.status_code == 204: <NEW_LINE> <INDENT> return "true" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return response.text
Webhook - creates webhook
62598fad5fdd1c0f98e5df69
class SimpleFactory(AbstractFactory): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.__missile_strategy = SimpleMove() <NEW_LINE> <DEDENT> def create_missile(self, position: Position, speed: float, movement_angle: float) -> Missile: <NEW_LINE> <INDENT> missile = Missile(position, speed, movement_angle, self.__missile_strategy) <NEW_LINE> return missile <NEW_LINE> <DEDENT> def create_smart_enemy(self, position: Position): <NEW_LINE> <INDENT> enemy = DummyEnemy(position) <NEW_LINE> return enemy <NEW_LINE> <DEDENT> def create_dummy_enemy(self, position: Position): <NEW_LINE> <INDENT> enemy = DummyEnemy(position) <NEW_LINE> return enemy
Simple factory for creating enemies and missiles Missiles: - simple lowering angle Smart enemy: - dump enemy sitting at one place Dummy enemy: - dump enemy sitting at one place
62598fad2c8b7c6e89bd37a2
class Satsuma2(CMakePackage): <NEW_LINE> <INDENT> homepage = "https://github.com/bioinfologics/satsuma2" <NEW_LINE> git = "https://github.com/bioinfologics/satsuma2.git" <NEW_LINE> version('2016-11-22', commit='da694aeecf352e344b790bea4a7aaa529f5b69e6') <NEW_LINE> def install(self, spec, prefix): <NEW_LINE> <INDENT> install_tree(join_path(self.build_directory, 'bin'), prefix.bin)
Satsuma2 is an optimsed version of Satsuma, a tool to reliably align large and complex DNA sequences providing maximum sensitivity (to find all there is to find), specificity (to only find real homology) and speed (to accomodate the billions of base pairs in vertebrate genomes).
62598fad4527f215b58e9ebd
class AngleTransform(tr.Transform): <NEW_LINE> <INDENT> name = "angle" <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.regularized = kwargs.pop("regularized", 10.0) <NEW_LINE> super(AngleTransform, self).__init__(*args, **kwargs) <NEW_LINE> <DEDENT> def backward(self, y): <NEW_LINE> <INDENT> return tt.arctan2(y[0], y[1]) <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> return tt.concatenate( (tt.shape_padleft(tt.sin(x)), tt.shape_padleft(tt.cos(x))), axis=0 ) <NEW_LINE> <DEDENT> def forward_val(self, x, point=None): <NEW_LINE> <INDENT> return np.array([np.sin(x), np.cos(x)]) <NEW_LINE> <DEDENT> def jacobian_det(self, y): <NEW_LINE> <INDENT> sm = tt.sum(tt.square(y), axis=0) <NEW_LINE> if self.regularized is not None: <NEW_LINE> <INDENT> return self.regularized * tt.log(sm) - 0.5 * sm <NEW_LINE> <DEDENT> return -0.5 * sm
Reference: exoplanet.dfm.io
62598fad6aa9bd52df0d4ea4
class ResPartner(models.Model): <NEW_LINE> <INDENT> _inherit = 'res.partner' <NEW_LINE> is_commercial_partner = fields.Boolean( "Is Commercial Partner", compute='_compute_is_commercial_partner', store=True) <NEW_LINE> @api.depends('commercial_partner_id') <NEW_LINE> def _compute_is_commercial_partner(self): <NEW_LINE> <INDENT> for rec in self: <NEW_LINE> <INDENT> rec.is_commercial_partner = rec == rec.commercial_partner_id
Extend to add is_commercial_partner field.
62598fad2ae34c7f260ab0be
class BaseCache: <NEW_LINE> <INDENT> def trim(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def autotrim(self, delay=CACHE_LIFESPAN): <NEW_LINE> <INDENT> self.trim() <NEW_LINE> t = threading.Timer(delay, self.autotrim) <NEW_LINE> t.daemon = True <NEW_LINE> t.start() <NEW_LINE> <DEDENT> def __contains__(self, url): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self[url] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True
Subclasses must behave like a dict
62598fadcc40096d6161a1c9
class Function(mixins.TaskDescriptionMixin, mixins.NextNodeMixin, mixins.DetailViewMixin, mixins.UndoViewMixin, mixins.CancelViewMixin, mixins.PerformViewMixin, Event): <NEW_LINE> <INDENT> task_type = 'FUNC' <NEW_LINE> activation_class = FuncActivation <NEW_LINE> def __init__(self, func, task_loader=None, **kwargs): <NEW_LINE> <INDENT> self.func = func <NEW_LINE> self.task_loader = task_loader <NEW_LINE> super(Function, self).__init__(**kwargs) <NEW_LINE> <DEDENT> def ready(self): <NEW_LINE> <INDENT> if isinstance(self.func, ThisObject): <NEW_LINE> <INDENT> self.func = getattr(self.flow_class.instance, self.func.name) <NEW_LINE> <DEDENT> if isinstance(self.task_loader, ThisObject): <NEW_LINE> <INDENT> self.task_loader = getattr(self.flow_class.instance, self.task_loader.name) <NEW_LINE> <DEDENT> <DEDENT> def run(self, *args, **kwargs): <NEW_LINE> <INDENT> if self.task_loader is None: <NEW_LINE> <INDENT> if 'task' not in kwargs: <NEW_LINE> <INDENT> if len(args) == 0 or not isinstance(args[0], self.flow_class.task_class): <NEW_LINE> <INDENT> raise FlowRuntimeError('Function {} should be called with task instance', self.name) <NEW_LINE> <DEDENT> <DEDENT> return self.func(*args, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> task = self.task_loader(self, *args, **kwargs) <NEW_LINE> return self.func(task, *args, **kwargs)
Function task to be executed outside of the flow. Example:: class MyFlow(Flow): ... shipment_received_handler = ( flow.Function( this.on_shipment_receive, task_loader=this.get_shipment_handler_task) .Next(this.end) ) .... @flow.flow_func def on_shipment_receive(self, activation, shipment): activation.prepare() activation.done() def get_shipment_handler_task(self, flow_task, shipment): return Task.objects.get(process=shipment.process) Somewhere in you code:: ... MyFlow.shipment_received_handler.run(shipment)
62598fadadb09d7d5dc0a567
class RegisterConfirmSerializer(SocialAuthSerializer): <NEW_LINE> <INDENT> partial_token = serializers.CharField(source="get_partial_token") <NEW_LINE> verification_code = serializers.CharField(write_only=True) <NEW_LINE> def create(self, validated_data): <NEW_LINE> <INDENT> return super()._authenticate(SocialAuthState.FLOW_REGISTER)
Serializer for email confirmation
62598fad10dbd63aa1c70b91
class MyModuleList(torch.nn.ModuleList): <NEW_LINE> <INDENT> def __init__(self, lst): <NEW_LINE> <INDENT> self.layers = [] <NEW_LINE> self.activations = [] <NEW_LINE> for layer_activations in lst: <NEW_LINE> <INDENT> self.layers.append(layer_activations[0]) <NEW_LINE> self.activations.append(layer_activations[1:]) <NEW_LINE> <DEDENT> super().__init__(self.layers) <NEW_LINE> <DEDENT> def compose_modules(self): <NEW_LINE> <INDENT> def f(x): <NEW_LINE> <INDENT> for layer, activations in zip(self.layers, self.activations): <NEW_LINE> <INDENT> x = layer(x) <NEW_LINE> for activation in activations: <NEW_LINE> <INDENT> x = activation(x) <NEW_LINE> <DEDENT> <DEDENT> return x <NEW_LINE> <DEDENT> return f
Wrapper for easily composing modules and activation functions.
62598fad167d2b6e312b6f4f
class SubscriptionPlanAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> fields = ( 'plan_name', 'slug', 'plan_description', 'group', 'tags', 'grace_period', ) <NEW_LINE> inlines = [PlanCostInline] <NEW_LINE> list_display = ( 'plan_name', 'group', 'display_tags', ) <NEW_LINE> prepopulated_fields = {'slug': ('plan_name',)}
Admin class for the SubscriptionPlan model.
62598fad7d847024c075c3a0
class RequiredFormSetMixin(object): <NEW_LINE> <INDENT> def clean(self): <NEW_LINE> <INDENT> super(RequiredFormSetMixin, self).clean() <NEW_LINE> count = 0 <NEW_LINE> for form in self.forms: <NEW_LINE> <INDENT> if (hasattr(form, 'cleaned_data') and not form.cleaned_data.get('DELETE', True)): <NEW_LINE> <INDENT> count += 1 <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if count < 1: <NEW_LINE> <INDENT> raise forms.ValidationError("At least one Transaction is required " "to create an Entry.")
This class ensures at least one form in the formset is filled.
62598fad5166f23b2e2433b6
class ResidualBlock(nn.Module): <NEW_LINE> <INDENT> def __init__(self, ch_in=64, ch_out=128, in_place=True): <NEW_LINE> <INDENT> super(ResidualBlock, self).__init__() <NEW_LINE> conv1 = nn.Conv2d(in_channels=ch_in, out_channels=ch_out, kernel_size=1, stride=1, padding=0, bias=False) <NEW_LINE> conv2 = nn.Conv2d(in_channels=ch_out, out_channels=ch_out, kernel_size=3, stride=1, padding=1, bias=False) <NEW_LINE> conv3 = nn.Conv2d(in_channels=ch_out, out_channels=ch_out, kernel_size=1, stride=1, padding=0, bias=False) <NEW_LINE> relu1 = nn.LeakyReLU(0.2, inplace=in_place) <NEW_LINE> relu2 = nn.LeakyReLU(0.2, inplace=in_place) <NEW_LINE> self.res = nn.Sequential(conv1, relu1, conv2, relu2, conv3) <NEW_LINE> if ch_in != ch_out: <NEW_LINE> <INDENT> self.identity = nn.Conv2d(in_channels=ch_in, out_channels=ch_out, kernel_size=1, stride=1, padding=0, bias=False) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> def identity(tensor): <NEW_LINE> <INDENT> return tensor <NEW_LINE> <DEDENT> self.identity = identity <NEW_LINE> <DEDENT> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> res = self.res(x) <NEW_LINE> x = self.identity(x) <NEW_LINE> return torch.add(x, res)
Residual BLock For SR without Norm Layer conv 1*1 conv 3*3 conv 1*1
62598fad56b00c62f0fb2892
class Region: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.chromosome: str <NEW_LINE> self.start_position: int <NEW_LINE> self.end_position: int <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return f'{self.chromosome}:{self.start_position}-{self.end_position}' <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return (f'{self.__class__}({self.chromosome}:' f'{self.start_position}-{self.end_position})')
Encapsulates a genomic region. Attributes: chromosome (str): The chromosome name. start_position (int): The start position. end_position (int): The end position.
62598fad851cf427c66b8299
class ApiClientMessage(object): <NEW_LINE> <INDENT> def __init__(self, headers=None, body=None): <NEW_LINE> <INDENT> if headers is None: <NEW_LINE> <INDENT> headers = [] <NEW_LINE> <DEDENT> self.headers = headers <NEW_LINE> self.body = body
Represents the interface between :py:class:`ask_sdk_model.services.api_client.ApiClient` implementation and a Service Client. :param headers: List of header tuples :type headers: list[tuple[str, str]] :param body: Body of the message :type body: str
62598fad460517430c43204c
class Cell(object): <NEW_LINE> <INDENT> def __init__(self, state: str): <NEW_LINE> <INDENT> self.state = state <NEW_LINE> self.neighbours = () <NEW_LINE> self.next_state = self.state <NEW_LINE> <DEDENT> def calculate_step(self): <NEW_LINE> <INDENT> if not self.neighbours: <NEW_LINE> <INDENT> raise ReferenceError('No neighbours defined') <NEW_LINE> <DEDENT> alive_neighbours = 0 <NEW_LINE> for neighbour in self.neighbours: <NEW_LINE> <INDENT> if neighbour.state and not neighbour.state.isspace(): <NEW_LINE> <INDENT> alive_neighbours += 1 <NEW_LINE> <DEDENT> <DEDENT> if not self.state or self.state.isspace(): <NEW_LINE> <INDENT> if alive_neighbours == 3: <NEW_LINE> <INDENT> self.next_state = random.choice([ n for n in self.neighbours if not n.state.isspace()]).state <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.next_state = ' ' <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> if alive_neighbours not in (2, 3): <NEW_LINE> <INDENT> self.next_state = ' ' <NEW_LINE> <DEDENT> <DEDENT> def take_step(self): <NEW_LINE> <INDENT> self.state = self.next_state <NEW_LINE> <DEDENT> def __str__(self) -> str: <NEW_LINE> <INDENT> return self.state or ' '
A single cell for use in cellular automata.
62598fad5fcc89381b26613b
class DiscoverView(Page): <NEW_LINE> <INDENT> def get_widget(self, params): <NEW_LINE> <INDENT> term = '' <NEW_LINE> if 'term' in params: <NEW_LINE> <INDENT> term = params['term'] <NEW_LINE> <DEDENT> results = None <NEW_LINE> if 'results' in params: <NEW_LINE> <INDENT> results = params['results'] <NEW_LINE> <DEDENT> widget = Ui_Discover(term, results, self.parent) <NEW_LINE> return widget
Discover view
62598fad090684286d5936cb
class CspAnonymousProcess(CspTree): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def take_tree_from(taker): <NEW_LINE> <INDENT> open_mark = CspMark.take_tree_from_chars(taker, chars="(", formatted="(") <NEW_LINE> process = CspProcess().take_tree_from(taker) <NEW_LINE> close_mark = CspMark.take_tree_from_chars(taker, chars=")", formatted=")") <NEW_LINE> anonymous_process = CspAnonymousProcess( open_mark=open_mark, process=process, close_mark=close_mark ) <NEW_LINE> return anonymous_process
anonymous_process := "(" process ")"
62598fad32920d7e50bc6032