code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class StateBodyPageExport(StateBodyPage): <NEW_LINE> <INDENT> template_name = 'theshow/bodies/body.state.export.html'
**Publish URL**: :code:`/election-results/{YEAR}/{STATE}/{BODY}/`
6259904ecad5886f8bdc5aaa
class Group(Base): <NEW_LINE> <INDENT> name = Column(Unicode(255), nullable=False, unique=True) <NEW_LINE> permissions = relationship(Permission, secondary=group__permission, lazy='select') <NEW_LINE> @classmethod <NEW_LINE> def by_name(cls, session, name): <NEW_LINE> <INDENT> return cls.first(session, where=(cls.name == name,))
Describe user's groups.
6259904e8e71fb1e983bcf1e
class Square: <NEW_LINE> <INDENT> def __init__(self, size=0): <NEW_LINE> <INDENT> if type(size) != int: <NEW_LINE> <INDENT> raise TypeError('size must be an integer') <NEW_LINE> <DEDENT> if size < 0: <NEW_LINE> <INDENT> raise ValueError('size must be >= 0') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.__size = size <NEW_LINE> <DEDENT> <DEDENT> def area(self): <NEW_LINE> <INDENT> return (self.__size**2)
square class
6259904e8e7ae83300eea4ed
class PasswordResetForm(forms.ModelForm): <NEW_LINE> <INDENT> email = forms.CharField( widget=forms.EmailInput(), help_text="Enter your account's email address." ) <NEW_LINE> password = forms.CharField(widget=forms.PasswordInput()) <NEW_LINE> confirm_password = forms.CharField( widget=forms.PasswordInput(), help_text="Re-enter your password for confirmation." ) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = User <NEW_LINE> fields = ('email', 'password') <NEW_LINE> <DEDENT> def clean(self): <NEW_LINE> <INDENT> cleaned_data = super(PasswordResetForm, self).clean() <NEW_LINE> password = cleaned_data.get('password') <NEW_LINE> confirm_password = cleaned_data.get('confirm_password') <NEW_LINE> email = cleaned_data.get('email') <NEW_LINE> recaptcha_response = self.data['g-recaptcha-response'] <NEW_LINE> if password != confirm_password: <NEW_LINE> <INDENT> self.add_error('confirm_password', "The entered passwords do not match.") <NEW_LINE> <DEDENT> if self.instance.email != email: <NEW_LINE> <INDENT> self.add_error( 'email', 'The entered email address does not correspond with the one in the system.' ) <NEW_LINE> <DEDENT> if not (recaptcha_response and recaptcha_check(recaptcha_response)): <NEW_LINE> <INDENT> self.add_error(None, 'The CAPTCHA validation failed, please try again.') <NEW_LINE> <DEDENT> return cleaned_data
Form for password reset
6259904e3c8af77a43b6896a
class MyMainWindow(VCPMainWindow): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(MyMainWindow, self).__init__(*args, **kwargs)
Main window class for the VCP.
6259904e4428ac0f6e65998b
class ProductionConfig(Config): <NEW_LINE> <INDENT> DEBUG = False <NEW_LINE> TESTING = False
Configurations for Production.
6259904ef7d966606f7492e4
class WebhookInstance(InstanceResource): <NEW_LINE> <INDENT> class Target(object): <NEW_LINE> <INDENT> WEBHOOK = "webhook" <NEW_LINE> TRIGGER = "trigger" <NEW_LINE> STUDIO = "studio" <NEW_LINE> <DEDENT> class Method(object): <NEW_LINE> <INDENT> GET = "GET" <NEW_LINE> POST = "POST" <NEW_LINE> <DEDENT> def __init__(self, version, payload, conversation_sid, sid=None): <NEW_LINE> <INDENT> super(WebhookInstance, self).__init__(version) <NEW_LINE> self._properties = { 'sid': payload.get('sid'), 'account_sid': payload.get('account_sid'), 'conversation_sid': payload.get('conversation_sid'), 'target': payload.get('target'), 'url': payload.get('url'), 'configuration': payload.get('configuration'), 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), } <NEW_LINE> self._context = None <NEW_LINE> self._solution = {'conversation_sid': conversation_sid, 'sid': sid or self._properties['sid'], } <NEW_LINE> <DEDENT> @property <NEW_LINE> def _proxy(self): <NEW_LINE> <INDENT> if self._context is None: <NEW_LINE> <INDENT> self._context = WebhookContext( self._version, conversation_sid=self._solution['conversation_sid'], sid=self._solution['sid'], ) <NEW_LINE> <DEDENT> return self._context <NEW_LINE> <DEDENT> @property <NEW_LINE> def sid(self): <NEW_LINE> <INDENT> return self._properties['sid'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def account_sid(self): <NEW_LINE> <INDENT> return self._properties['account_sid'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def conversation_sid(self): <NEW_LINE> <INDENT> return self._properties['conversation_sid'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def target(self): <NEW_LINE> <INDENT> return self._properties['target'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def url(self): <NEW_LINE> <INDENT> return self._properties['url'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def configuration(self): <NEW_LINE> <INDENT> return self._properties['configuration'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def date_created(self): <NEW_LINE> <INDENT> return self._properties['date_created'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def date_updated(self): <NEW_LINE> <INDENT> return self._properties['date_updated'] <NEW_LINE> <DEDENT> def fetch(self): <NEW_LINE> <INDENT> return self._proxy.fetch() <NEW_LINE> <DEDENT> def update(self, configuration_url=values.unset, configuration_method=values.unset, configuration_filters=values.unset, configuration_triggers=values.unset, configuration_flow_sid=values.unset): <NEW_LINE> <INDENT> return self._proxy.update( configuration_url=configuration_url, configuration_method=configuration_method, configuration_filters=configuration_filters, configuration_triggers=configuration_triggers, configuration_flow_sid=configuration_flow_sid, ) <NEW_LINE> <DEDENT> def delete(self): <NEW_LINE> <INDENT> return self._proxy.delete() <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) <NEW_LINE> return '<Twilio.Conversations.V1.WebhookInstance {}>'.format(context)
PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution.
6259904e3cc13d1c6d466b92
class WorldPointNumpy(NumpyFixedLenSchema): <NEW_LINE> <INDENT> long = SchemaNode(Float()) <NEW_LINE> lat = SchemaNode(Float()) <NEW_LINE> z = SchemaNode(Float())
Define same schema as WorldPoint; however, the base class NumpyFixedLenSchema serializes/deserializes it from/to a numpy array
6259904ee76e3b2f99fd9e59
class InputImageV2: <NEW_LINE> <INDENT> def __init__(self, image_size=(28, 28), train_size=0.8): <NEW_LINE> <INDENT> self.classes = [1, 2, 3, 4, 5, 6] <NEW_LINE> self.image_size = image_size <NEW_LINE> self.image_extension = '.bmp' <NEW_LINE> self.max_read_images = 500 <NEW_LINE> self.train_size = train_size <NEW_LINE> self.test_size = 1 - self.train_size <NEW_LINE> <DEDENT> def get_test_train_data(self): <NEW_LINE> <INDENT> X, y = self.load_data() <NEW_LINE> X_train, X_test, y_train, y_test = train_test_split( X, y, train_size=self.train_size, test_size=self.test_size, stratify=y ) <NEW_LINE> return X_train, X_test, y_train, y_test <NEW_LINE> <DEDENT> def load_data(self): <NEW_LINE> <INDENT> image_path = os.pardir + '/images/' <NEW_LINE> X = [] <NEW_LINE> y = [] <NEW_LINE> for index, class_label in enumerate(self.classes): <NEW_LINE> <INDENT> images_dir = image_path + str(class_label) <NEW_LINE> files = glob.glob(images_dir + "/*{}".format(self.image_extension)) <NEW_LINE> for j_index, file in enumerate(files): <NEW_LINE> <INDENT> if j_index == self.max_read_images: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> image = cv2.imread(file, cv2.IMREAD_COLOR) <NEW_LINE> image = cv2.resize(image, self.image_size) <NEW_LINE> X.append(image) <NEW_LINE> y.append(index) <NEW_LINE> <DEDENT> <DEDENT> X = np.array(X) <NEW_LINE> y = np.array(y) <NEW_LINE> return X, y
画像の読み込みを行うクラス
6259904ea219f33f346c7c5b
class getRowWithColumnsTs_result: <NEW_LINE> <INDENT> thrift_spec = ( (0, TType.LIST, 'success', (TType.STRUCT,(TRowResult, TRowResult.thrift_spec)), None, ), (1, TType.STRUCT, 'io', (IOError, IOError.thrift_spec), None, ), ) <NEW_LINE> def __init__(self, success=None, io=None,): <NEW_LINE> <INDENT> self.success = success <NEW_LINE> self.io = io <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 0: <NEW_LINE> <INDENT> if ftype == TType.LIST: <NEW_LINE> <INDENT> self.success = [] <NEW_LINE> (_etype112, _size109) = iprot.readListBegin() <NEW_LINE> for _i113 in xrange(_size109): <NEW_LINE> <INDENT> _elem114 = TRowResult() <NEW_LINE> _elem114.read(iprot) <NEW_LINE> self.success.append(_elem114) <NEW_LINE> <DEDENT> iprot.readListEnd() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.io = IOError() <NEW_LINE> self.io.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('getRowWithColumnsTs_result') <NEW_LINE> if self.success is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('success', TType.LIST, 0) <NEW_LINE> oprot.writeListBegin(TType.STRUCT, len(self.success)) <NEW_LINE> for iter115 in self.success: <NEW_LINE> <INDENT> iter115.write(oprot) <NEW_LINE> <DEDENT> oprot.writeListEnd() <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.io is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('io', TType.STRUCT, 1) <NEW_LINE> self.io.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other)
Attributes: - success - io
6259904ea79ad1619776b4da
class TestCartesianToCylindrical(unittest.TestCase): <NEW_LINE> <INDENT> def test_cartesian_to_cylindrical(self): <NEW_LINE> <INDENT> np.testing.assert_almost_equal( cartesian_to_cylindrical((3, 1, 6)), np.array([6., 0.32175055, 3.16227766]), decimal=7) <NEW_LINE> np.testing.assert_almost_equal( cartesian_to_cylindrical((-1, 9, 16)), np.array([16., 1.68145355, 9.05538514]), decimal=7) <NEW_LINE> np.testing.assert_almost_equal( cartesian_to_cylindrical((6.3434, -0.9345, 18.5675)), np.array([18.5675, -0.1462664, 6.41186508]), decimal=7)
Defines :func:`colour.algebra.coordinates.transformations.cartesian_to_cylindrical` definition unit tests methods.
6259904e498bea3a75a58f7a
class Categoriser: <NEW_LINE> <INDENT> def __init__(self, args: argparse.Namespace): <NEW_LINE> <INDENT> with open(args.config) as f: <NEW_LINE> <INDENT> CONFIG = yaml.full_load(f) <NEW_LINE> <DEDENT> assert "categories" in CONFIG, "Need categories to work with" <NEW_LINE> self.patterns = {pat.lower(): v for pat, v in CONFIG["categories"].items()} <NEW_LINE> self.source = Categoriser._open_shelf(args.source) <NEW_LINE> self.destination = Categoriser._open_shelf(args.destination) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.destination.clear() <NEW_LINE> for account, entries in self.source.items(): <NEW_LINE> <INDENT> print_stderr(f"Processing {account}") <NEW_LINE> new_entries = [] <NEW_LINE> for entry in entries: <NEW_LINE> <INDENT> if type(entry) in SUPPORTED_DIRECTIVES: <NEW_LINE> <INDENT> categorised_account = self.attempt_categorise(entry) <NEW_LINE> if categorised_account: <NEW_LINE> <INDENT> posting = Posting( categorised_account, None, None, None, None, None ) <NEW_LINE> new_postings = entry.postings + [posting] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> new_postings = entry.postings <NEW_LINE> <DEDENT> new_entry = Transaction( entry.meta, entry.date, entry.flag, entry.payee, entry.narration, entry.tags, entry.links, new_postings, ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> new_entry = entry <NEW_LINE> <DEDENT> new_entries.append(new_entry) <NEW_LINE> <DEDENT> self.destination[account] = new_entries <NEW_LINE> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> self.destination.close() <NEW_LINE> print_stderr("Categorised written to db file") <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def _open_shelf(filename) -> shelve.Shelf: <NEW_LINE> <INDENT> return shelve.open(filename) <NEW_LINE> <DEDENT> def attempt_categorise(self, entry) -> Optional[str]: <NEW_LINE> <INDENT> for pat, account in self.patterns.items(): <NEW_LINE> <INDENT> if pat in entry.payee.lower(): <NEW_LINE> <INDENT> return account <NEW_LINE> <DEDENT> <DEDENT> return None
Categorises transactions using patterns defined in the YAML config file.
6259904e45492302aabfd92d
class Layer: <NEW_LINE> <INDENT> def __init__(self, inbound_layers=[]): <NEW_LINE> <INDENT> self.inbound_layers = inbound_layers <NEW_LINE> self.value = None <NEW_LINE> self.outbound_layers = [] <NEW_LINE> self.gradients = {} <NEW_LINE> for layer in inbound_layers: <NEW_LINE> <INDENT> layer.outbound_layers.append(self) <NEW_LINE> <DEDENT> <DEDENT> def forward(): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def backward(): <NEW_LINE> <INDENT> raise NotImplementedError
Base class for layers in the network. Arguments: `inbound_layers`: A list of layers with edges into this layer.
6259904ed53ae8145f9198bc
class TestMultiDataset(PymatgenTest): <NEW_LINE> <INDENT> def test_api(self): <NEW_LINE> <INDENT> structure = Structure.from_file(abiref_file("si.cif")) <NEW_LINE> pseudo = abiref_file("14si.pspnc") <NEW_LINE> pseudo_dir = os.path.dirname(pseudo) <NEW_LINE> multi = BasicMultiDataset(structure=structure, pseudos=pseudo) <NEW_LINE> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> BasicMultiDataset(structure=structure, pseudos=pseudo, ndtset=-1) <NEW_LINE> <DEDENT> multi = BasicMultiDataset(structure=structure, pseudos=pseudo, pseudo_dir=pseudo_dir) <NEW_LINE> assert len(multi) == 1 and multi.ndtset == 1 <NEW_LINE> assert multi.isnc <NEW_LINE> for i, inp in enumerate(multi): <NEW_LINE> <INDENT> assert list(inp.keys()) == list(multi[i].keys()) <NEW_LINE> <DEDENT> multi.addnew_from(0) <NEW_LINE> assert multi.ndtset == 2 and multi[0] is not multi[1] <NEW_LINE> assert multi[0].structure == multi[1].structure <NEW_LINE> assert multi[0].structure is not multi[1].structure <NEW_LINE> multi.set_vars(ecut=2) <NEW_LINE> assert all(inp["ecut"] == 2 for inp in multi) <NEW_LINE> self.assertEqual(multi.get("ecut"), [2, 2]) <NEW_LINE> multi[1].set_vars(ecut=1) <NEW_LINE> assert multi[0]["ecut"] == 2 and multi[1]["ecut"] == 1 <NEW_LINE> self.assertEqual(multi.get("ecut"), [2, 1]) <NEW_LINE> self.assertEqual(multi.get("foo", "default"), ["default", "default"]) <NEW_LINE> multi[1].set_vars(paral_kgb=1) <NEW_LINE> assert "paral_kgb" not in multi[0] <NEW_LINE> self.assertEqual(multi.get("paral_kgb"), [None, 1]) <NEW_LINE> pert_structure = structure.copy() <NEW_LINE> pert_structure.perturb(distance=0.1) <NEW_LINE> assert structure != pert_structure <NEW_LINE> assert multi.set_structure(structure) == multi.ndtset * [structure] <NEW_LINE> assert all(s == structure for s in multi.structure) <NEW_LINE> assert multi.has_same_structures <NEW_LINE> multi[1].set_structure(pert_structure) <NEW_LINE> assert multi[0].structure != multi[1].structure and multi[1].structure == pert_structure <NEW_LINE> assert not multi.has_same_structures <NEW_LINE> split = multi.split_datasets() <NEW_LINE> assert len(split) == 2 and all(split[i] == multi[i] for i in range(multi.ndtset)) <NEW_LINE> repr(multi) <NEW_LINE> str(multi) <NEW_LINE> assert multi.to_string(with_pseudos=False) <NEW_LINE> tmpdir = tempfile.mkdtemp() <NEW_LINE> filepath = os.path.join(tmpdir, "run.abi") <NEW_LINE> inp.write(filepath=filepath) <NEW_LINE> multi.write(filepath=filepath) <NEW_LINE> new_multi = BasicMultiDataset.from_inputs([inp for inp in multi]) <NEW_LINE> assert new_multi.ndtset == multi.ndtset <NEW_LINE> assert new_multi.structure == multi.structure <NEW_LINE> for old_inp, new_inp in zip(multi, new_multi): <NEW_LINE> <INDENT> assert old_inp is not new_inp <NEW_LINE> self.assertDictEqual(old_inp.as_dict(), new_inp.as_dict()) <NEW_LINE> <DEDENT> ref_input = multi[0] <NEW_LINE> new_multi = BasicMultiDataset.replicate_input(input=ref_input, ndtset=4) <NEW_LINE> assert new_multi.ndtset == 4 <NEW_LINE> for inp in new_multi: <NEW_LINE> <INDENT> assert ref_input is not inp <NEW_LINE> self.assertDictEqual(ref_input.as_dict(), inp.as_dict()) <NEW_LINE> <DEDENT> self.serialize_with_pickle(multi, test_eq=False)
Unit tests for BasicMultiDataset.
6259904e3eb6a72ae038bab5
class Connection(object): <NEW_LINE> <INDENT> def __init__(self, sock, addr, server, timeout): <NEW_LINE> <INDENT> self._sock = sock <NEW_LINE> self._addr = addr <NEW_LINE> self.server = server <NEW_LINE> self._timeout = timeout <NEW_LINE> self.logger = logging.getLogger(LoggerName) <NEW_LINE> <DEDENT> def timeout_handler(self, signum, frame): <NEW_LINE> <INDENT> self.logger.error('Timeout Exceeded') <NEW_LINE> self.logger.error("\n".join(traceback.format_stack(frame))) <NEW_LINE> raise TimeoutException <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> if len(self._addr) == 2: <NEW_LINE> <INDENT> self.logger.debug('Connection starting up (%s:%d)', self._addr[0], self._addr[1]) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.processInput() <NEW_LINE> <DEDENT> except (EOFError, KeyboardInterrupt): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> except ProtocolError as e: <NEW_LINE> <INDENT> self.logger.error("Protocol error '%s'", str(e)) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> self.logger.exception('Exception caught in Connection') <NEW_LINE> <DEDENT> if len(self._addr) == 2: <NEW_LINE> <INDENT> self.logger.debug('Connection shutting down (%s:%d)', self._addr[0], self._addr[1]) <NEW_LINE> <DEDENT> self._sock.close() <NEW_LINE> <DEDENT> def processInput(self): <NEW_LINE> <INDENT> headers = readNetstring(self._sock) <NEW_LINE> headers = headers.split('\x00')[:-1] <NEW_LINE> if len(headers) % 2 != 0: <NEW_LINE> <INDENT> raise ProtocolError('invalid headers') <NEW_LINE> <DEDENT> environ = {} <NEW_LINE> for i in range(len(headers) / 2): <NEW_LINE> <INDENT> environ[headers[2*i]] = headers[2*i+1] <NEW_LINE> <DEDENT> clen = environ.get('CONTENT_LENGTH') <NEW_LINE> if clen is None: <NEW_LINE> <INDENT> raise ProtocolError('missing CONTENT_LENGTH') <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> clen = int(clen) <NEW_LINE> if clen < 0: <NEW_LINE> <INDENT> raise ValueError <NEW_LINE> <DEDENT> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise ProtocolError('invalid CONTENT_LENGTH') <NEW_LINE> <DEDENT> self._sock.setblocking(1) <NEW_LINE> if clen: <NEW_LINE> <INDENT> input = self._sock.makefile('r') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> input = StringIO.StringIO() <NEW_LINE> <DEDENT> output = self._sock.makefile('w') <NEW_LINE> req = Request(self, environ, input, output) <NEW_LINE> if self._timeout: <NEW_LINE> <INDENT> old_alarm = signal.signal(signal.SIGALRM, self.timeout_handler) <NEW_LINE> signal.alarm(self._timeout) <NEW_LINE> <DEDENT> req.run() <NEW_LINE> output.close() <NEW_LINE> input.close() <NEW_LINE> if self._timeout: <NEW_LINE> <INDENT> signal.alarm(0) <NEW_LINE> signal.signal(signal.SIGALRM, old_alarm)
Represents a single client (web server) connection. A single request is handled, after which the socket is closed.
6259904ed7e4931a7ef3d4d2
class Double2DWrapper(ParamWrapper): <NEW_LINE> <INDENT> def __init__(self, param): <NEW_LINE> <INDENT> ParamWrapper.__init__(self, param) <NEW_LINE> <DEDENT> @QtCore.Slot(result=float) <NEW_LINE> def getDefaultValue1(self): <NEW_LINE> <INDENT> return self._param.getDefaultValue1() <NEW_LINE> <DEDENT> @QtCore.Slot(result=float) <NEW_LINE> def getDefaultValue2(self): <NEW_LINE> <INDENT> return self._param.getDefaultValue2() <NEW_LINE> <DEDENT> def getValue1(self): <NEW_LINE> <INDENT> return self._param.getValue1() <NEW_LINE> <DEDENT> def getValue2(self): <NEW_LINE> <INDENT> return self._param.getValue2() <NEW_LINE> <DEDENT> def getMaximum1(self): <NEW_LINE> <INDENT> return self._param.getMaximum1() <NEW_LINE> <DEDENT> def getMinimum1(self): <NEW_LINE> <INDENT> return self._param.getMinimum1() <NEW_LINE> <DEDENT> def getMaximum2(self): <NEW_LINE> <INDENT> return self._param.getMaximum2() <NEW_LINE> <DEDENT> def getMinimum2(self): <NEW_LINE> <INDENT> return self._param.getMinimum2() <NEW_LINE> <DEDENT> def getValue1HasChanged(self): <NEW_LINE> <INDENT> return self._param.getValue1HasChanged() <NEW_LINE> <DEDENT> def getValue2HasChanged(self): <NEW_LINE> <INDENT> return self._param.getValue2HasChanged() <NEW_LINE> <DEDENT> def setValue1(self, value1): <NEW_LINE> <INDENT> self._param.setValue1(value1) <NEW_LINE> <DEDENT> def setValue2(self, value2): <NEW_LINE> <INDENT> self._param.setValue2(value2) <NEW_LINE> <DEDENT> def setValue1HasChanged(self, changed): <NEW_LINE> <INDENT> self._param.setValue1HasChanged(changed) <NEW_LINE> <DEDENT> def setValue2HasChanged(self, changed): <NEW_LINE> <INDENT> self._param.setValue2HasChanged(changed) <NEW_LINE> <DEDENT> @QtCore.Signal <NEW_LINE> def changed(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> value1 = QtCore.Property(float, getValue1, setValue1, notify=changed) <NEW_LINE> value2 = QtCore.Property(float, getValue2, setValue2, notify=changed) <NEW_LINE> maximum1 = QtCore.Property(float, getMaximum1, constant=True) <NEW_LINE> minimum1 = QtCore.Property(float, getMinimum1, constant=True) <NEW_LINE> maximum2 = QtCore.Property(float, getMaximum2, constant=True) <NEW_LINE> minimum2 = QtCore.Property(float, getMinimum2, constant=True) <NEW_LINE> value1HasChanged = QtCore.Property(bool, getValue1HasChanged, setValue1HasChanged, notify=changed) <NEW_LINE> value2HasChanged = QtCore.Property(bool, getValue2HasChanged, setValue2HasChanged, notify=changed)
Gui class, which maps a ParamDouble2D.
6259904e4e696a045264e84d
class Strict(Event): <NEW_LINE> <INDENT> def __init__(self, *arg_names): <NEW_LINE> <INDENT> if len(set(arg_names)) != len(arg_names): <NEW_LINE> <INDENT> raise ArgsError("Cannot accept args of same name") <NEW_LINE> <DEDENT> self.args = arg_names <NEW_LINE> Event.__init__(self) <NEW_LINE> <DEDENT> def fire(self, *args): <NEW_LINE> <INDENT> check_missing(self.args, args) <NEW_LINE> with ensure_fire(self.handlers, args) as results: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return results <NEW_LINE> <DEDENT> def add(self, handler): <NEW_LINE> <INDENT> argcount = handler.__code__.co_argcount <NEW_LINE> argnames = handler.__code__.co_varnames[:argcount] <NEW_LINE> if isinstance(handler, types.MethodType): <NEW_LINE> <INDENT> argnames = argnames[1:] <NEW_LINE> <DEDENT> check_missing(self.args, argnames) <NEW_LINE> return Event.add(self, handler) <NEW_LINE> <DEDENT> __call__ = fire <NEW_LINE> __iadd__ = add <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return "<StrictEvent object, {} handlers, accepts: [{}]>".format( len(self.handlers), ", ".join(self.args)) <NEW_LINE> <DEDENT> __unicode__ = __repr__ <NEW_LINE> __str__ = __repr__
The 'Strict Event' requires definition of the args on init. It will then raise an `ArgsError` whenever these requirements are not adhered to. This includes checking of `fire()` parameters and handler function args.
6259904e8a43f66fc4bf35f1
class GlobalLibraryVersionsRequest(RWSAuthorizedGetRequest): <NEW_LINE> <INDENT> def __init__(self, project_name): <NEW_LINE> <INDENT> self.project_name = project_name <NEW_LINE> <DEDENT> def url_path(self): <NEW_LINE> <INDENT> return make_url('metadata', 'libraries', self.project_name, 'versions') <NEW_LINE> <DEDENT> def result(self, request): <NEW_LINE> <INDENT> return RWSStudyMetadataVersions(request.text)
Return the list of global library versions
6259904e07f4c71912bb088e
class PMRequestListener(object): <NEW_LINE> <INDENT> def __init__(self, config, buildroot): <NEW_LINE> <INDENT> self.config = config <NEW_LINE> self.buildroot = buildroot <NEW_LINE> self.rundir = buildroot.make_chroot_path(RUNDIR) <NEW_LINE> self.socket_path = os.path.join(self.rundir, SOCKET_NAME) <NEW_LINE> self.executed_commands = [] <NEW_LINE> self.log_buffer = StringIO() <NEW_LINE> self.log = logging.getLogger("mockbuild.plugin.pm_request") <NEW_LINE> self.log.level = logging.DEBUG <NEW_LINE> self.log.addFilter(OutputFilter()) <NEW_LINE> self.log.propagate = False <NEW_LINE> self.log.addHandler(logging.StreamHandler(self.log_buffer)) <NEW_LINE> <DEDENT> def prepare_socket(self): <NEW_LINE> <INDENT> sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) <NEW_LINE> try: <NEW_LINE> <INDENT> sock.connect(self.socket_path) <NEW_LINE> <DEDENT> except (socket.error, OSError): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> os.unlink(self.socket_path) <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> sys.exit(0) <NEW_LINE> <DEDENT> file_util.mkdirIfAbsent(self.rundir) <NEW_LINE> os.chown(self.rundir, self.buildroot.chrootuid, self.buildroot.chrootgid) <NEW_LINE> os.chmod(self.rundir, 0o770) <NEW_LINE> sock.bind(self.socket_path) <NEW_LINE> os.chown(self.socket_path, self.buildroot.chrootuid, self.buildroot.chrootgid) <NEW_LINE> return sock <NEW_LINE> <DEDENT> def listen(self): <NEW_LINE> <INDENT> sock = self.prepare_socket() <NEW_LINE> sock.listen(MAX_CONNECTIONS) <NEW_LINE> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> connection, _ = sock.accept() <NEW_LINE> try: <NEW_LINE> <INDENT> line = connection.makefile().readline() <NEW_LINE> command = shlex.split(line) <NEW_LINE> if command == ["!LOG_EXECUTED"]: <NEW_LINE> <INDENT> connection.sendall('\n'.join(self.executed_commands).encode()) <NEW_LINE> <DEDENT> elif command: <NEW_LINE> <INDENT> success, out = self.execute_command(command) <NEW_LINE> connection.sendall(b"ok\n" if success else b"nok\n") <NEW_LINE> connection.sendall(out.encode()) <NEW_LINE> if success: <NEW_LINE> <INDENT> self.executed_commands.append(line.strip()) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> connection.close() <NEW_LINE> <DEDENT> <DEDENT> except socket.error: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def execute_command(self, command): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.buildroot.pkg_manager.execute( *command, printOutput=False, logger=self.log, returnOutput=False, pty=False, raiseExc=True) <NEW_LINE> success = True <NEW_LINE> <DEDENT> except Error: <NEW_LINE> <INDENT> success = False <NEW_LINE> <DEDENT> out = self.log_buffer.getvalue() <NEW_LINE> self.log_buffer.seek(0) <NEW_LINE> self.log_buffer.truncate() <NEW_LINE> return success, out
Daemon process that responds to requests
6259904ed4950a0f3b111870
class TestIncidentApi(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.api = swagger_client.api.incident_api.IncidentApi() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_close_incident(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_create_incident(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_delete_incident(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_get_incident(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_get_incident_request_status(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_list_incidents(self): <NEW_LINE> <INDENT> pass
IncidentApi unit test stubs
6259904e07d97122c42180fe
class Bakery(Restaurant): <NEW_LINE> <INDENT> def __init__(self, name, cuisine): <NEW_LINE> <INDENT> super().__init__(name, cuisine) <NEW_LINE> self.flavors = ['rose', 'lavender', 'peanut butter'] <NEW_LINE> <DEDENT> def list_flavors(self): <NEW_LINE> <INDENT> print(f"Today's flavors are: {self.flavors}")
Represents bakeries as a subclass of restaurant.
6259904e73bcbd0ca4bcb6e3
class IndQLearningAgent(Agent): <NEW_LINE> <INDENT> def __init__(self, action_space, n_states, learning_rate, epsilon, gamma, enemy_action_space=None): <NEW_LINE> <INDENT> Agent.__init__(self, action_space) <NEW_LINE> self.n_states = n_states <NEW_LINE> self.alpha = learning_rate <NEW_LINE> self.epsilon = epsilon <NEW_LINE> self.gamma = gamma <NEW_LINE> self.Q = np.zeros([self.n_states, len(self.action_space)]) <NEW_LINE> <DEDENT> def act(self, obs=None): <NEW_LINE> <INDENT> if np.random.rand() < self.epsilon: <NEW_LINE> <INDENT> return self.action_space[choice(range(len(self.action_space)))] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.action_space[np.argmax(self.Q[obs, :])] <NEW_LINE> <DEDENT> <DEDENT> def update(self, obs, actions, rewards, new_obs): <NEW_LINE> <INDENT> a0 = actions[0] <NEW_LINE> r0 = rewards[0] <NEW_LINE> idx = int(np.where(np.all(self.action_space == a0, axis=1))[0]) <NEW_LINE> self.Q[obs, idx] = (1 - self.alpha)*self.Q[obs, idx] + self.alpha*(r0 + self.gamma*np.max(self.Q[new_obs, :]))
A Q-learning agent that treats other players as part of the environment (independent Q-learning). She represents Q-values in a tabular fashion, i.e., using a matrix Q. Intended to use as a baseline
6259904e10dbd63aa1c72038
class TestBase(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self, worldbasePath=None, **kwargs): <NEW_LINE> <INDENT> self.tempdir = testutil.TempDir('pygrdata') <NEW_LINE> if worldbasePath is None: <NEW_LINE> <INDENT> worldbasePath = self.tempdir.path <NEW_LINE> <DEDENT> self.metabase = metabase.MetabaseList(worldbasePath, **kwargs) <NEW_LINE> self.pygrData = self.metabase.Data <NEW_LINE> self.schema = self.metabase.Schema <NEW_LINE> self.EQ = self.assertEqual
A base class to all metabase test classes
6259904e94891a1f408ba122
class MyChef(SushiChef): <NEW_LINE> <INDENT> channel_info = { 'CHANNEL_SOURCE_DOMAIN': CHANNEL_DOMAIN, 'CHANNEL_SOURCE_ID': CHANNEL_SOURCE_ID, 'CHANNEL_TITLE': CHANNEL_NAME, 'CHANNEL_LANGUAGE': CHANNEL_LANGUAGE, 'CHANNEL_THUMBNAIL': CHANNEL_THUMBNAIL, 'CHANNEL_DESCRIPTION': CHANNEL_DESCRIPTION, } <NEW_LINE> def construct_channel(self, *args, **kwargs): <NEW_LINE> <INDENT> channel = self.get_channel(*args, **kwargs) <NEW_LINE> topics = load_json_from_file(JSON_FILE) <NEW_LINE> for topic in topics: <NEW_LINE> <INDENT> book_title = topic['book_title'] <NEW_LINE> source_id = book_title.replace(" ", "_") <NEW_LINE> url = topic['path_or_url'] <NEW_LINE> topic_node = nodes.TopicNode(source_id=source_id, title=book_title, tags = [ "Teacher facing", "Professional development", "Life skills", "Intercultural skills", "Mentorship", "Formal contexts" ]) <NEW_LINE> channel.add_child(topic_node) <NEW_LINE> parser = pdf.PDFParser(url, toc=topic['chapters']) <NEW_LINE> parser.open() <NEW_LINE> chapters = parser.split_chapters() <NEW_LINE> for chapter in chapters: <NEW_LINE> <INDENT> title = chapter['title'] <NEW_LINE> pdf_path = chapter['path'] <NEW_LINE> pdf_file = files.DocumentFile(pdf_path) <NEW_LINE> pdf_node = nodes.DocumentNode( source_id="{} {}".format(book_title, title), title=title, author="INTO", tags = [ "Teacher facing", "Professional development", "Life skills", "Intercultural skills", "Mentorship", "Formal contexts" ], files=[pdf_file], license=licenses.get_license(CHANNEL_LICENSE, "INTO", LICENSE_DESCRIPTION), copyright_holder="INTO" ) <NEW_LINE> topic_node.add_child(pdf_node) <NEW_LINE> <DEDENT> <DEDENT> raise_for_invalid_channel(channel) <NEW_LINE> return channel
This class uploads the INTO Intercultural Mentoring channel to Kolibri Studio. Your command line script should call the `main` method as the entry point, which performs the following steps: - Parse command line arguments and options (run `./sushichef.py -h` for details) - Call the `SushiChef.run` method which in turn calls `pre_run` (optional) and then the ricecooker function `uploadchannel` which in turn calls this class' `get_channel` method to get channel info, then `construct_channel` to build the contentnode tree. For more info, see https://github.com/learningequality/ricecooker/tree/master/docs
6259904e097d151d1a2c24ca
class togzfile(TextOp): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def op(cls,text,filename, mode='wb', newline='\n',*args,**kwargs): <NEW_LINE> <INDENT> with gzip.open(filename,mode) as fh: <NEW_LINE> <INDENT> fh.write(TextOp.make_string(text,newline).encode())
send input to gz file ``togzfile()`` must be the last text operation Args: filename (str): The gz file to send COMPRESSED output to mode (str): File open mode (Default : 'wb') newline (str): The newline string to add for each line (default: '\n') Examples: >>> '/var/log/dmesg' | cat() | grep('error') | togzfile('/tmp/errors.log.gz') Note: Password encrypted zip creation is not supported.
6259904e3539df3088ecd6fe
class SafetyEventDriver(object): <NEW_LINE> <INDENT> openapi_types = { } <NEW_LINE> attribute_map = { } <NEW_LINE> def __init__(self, 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.discriminator = None <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, SafetyEventDriver): <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, SafetyEventDriver): <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.
6259904e63d6d428bbee3c26
class SystemTest(unittest.TestCase): <NEW_LINE> <INDENT> def testSyntaxErrorDiffPass(self): <NEW_LINE> <INDENT> stdout = run_foozzie('build1', '--skip-sanity-checks') <NEW_LINE> self.assertEquals('# V8 correctness - pass\n', cut_verbose_output(stdout)) <NEW_LINE> <DEDENT> def testDifferentOutputFail(self): <NEW_LINE> <INDENT> with open(os.path.join(TEST_DATA, 'failure_output.txt')) as f: <NEW_LINE> <INDENT> expected_output = f.read() <NEW_LINE> <DEDENT> with self.assertRaises(subprocess.CalledProcessError) as ctx: <NEW_LINE> <INDENT> run_foozzie('build2', '--skip-sanity-checks', '--first-config-extra-flags=--flag1', '--first-config-extra-flags=--flag2=0', '--second-config-extra-flags=--flag3') <NEW_LINE> <DEDENT> e = ctx.exception <NEW_LINE> self.assertEquals(v8_foozzie.RETURN_FAIL, e.returncode) <NEW_LINE> self.assertEquals(expected_output, cut_verbose_output(e.output)) <NEW_LINE> <DEDENT> def testSanityCheck(self): <NEW_LINE> <INDENT> with open(os.path.join(TEST_DATA, 'sanity_check_output.txt')) as f: <NEW_LINE> <INDENT> expected_output = f.read() <NEW_LINE> <DEDENT> with self.assertRaises(subprocess.CalledProcessError) as ctx: <NEW_LINE> <INDENT> run_foozzie('build2') <NEW_LINE> <DEDENT> e = ctx.exception <NEW_LINE> self.assertEquals(v8_foozzie.RETURN_FAIL, e.returncode) <NEW_LINE> self.assertEquals(expected_output, e.output) <NEW_LINE> <DEDENT> def testDifferentArch(self): <NEW_LINE> <INDENT> stdout = run_foozzie('build3', '--skip-sanity-checks') <NEW_LINE> lines = stdout.split('\n') <NEW_LINE> self.assertIn('v8_mock_archs.js', lines[1]) <NEW_LINE> self.assertIn('v8_mock_archs.js', lines[3])
This tests the whole correctness-fuzzing harness with fake build artifacts. Overview of fakes: baseline: Example foozzie output including a syntax error. build1: Difference to baseline is a stack trace differece expected to be suppressed. build2: Difference to baseline is a non-suppressed output difference causing the script to fail. build3: As build1 but with an architecture difference as well.
6259904e91af0d3eaad3b27f
class TableBinaryOutputFileFormat(IBinaryOutputFileFormat): <NEW_LINE> <INDENT> def __init__(self, dtype=None, transposed=False): <NEW_LINE> <INDENT> IBinaryOutputFileFormat.__init__(self,"bin") <NEW_LINE> self.dtype=dtype <NEW_LINE> self.transposed=transposed <NEW_LINE> <DEDENT> def get_dtype(self, table): <NEW_LINE> <INDENT> if self.dtype is None: <NEW_LINE> <INDENT> return np.asarray(table).dtype.newbyteorder("<").str <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.dtype <NEW_LINE> <DEDENT> <DEDENT> def get_preamble(self, location_file, data): <NEW_LINE> <INDENT> preamble=dictionary.Dictionary() <NEW_LINE> preamble["nrows"]=data.shape[0] <NEW_LINE> preamble["ncols"]=data.shape[1] <NEW_LINE> preamble["dtype"]=self.get_dtype(data) <NEW_LINE> if self.transposed: <NEW_LINE> <INDENT> preamble["packing"]="transposed" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> preamble["packing"]="flatten" <NEW_LINE> <DEDENT> return preamble <NEW_LINE> <DEDENT> def write_data(self, location_file, data): <NEW_LINE> <INDENT> stream=location_file.stream <NEW_LINE> data=np.asarray(data) <NEW_LINE> dtype=self.get_dtype(data) <NEW_LINE> if self.transposed: <NEW_LINE> <INDENT> data=data.transpose() <NEW_LINE> <DEDENT> data.flatten().astype(dtype).tofile(stream,format=dtype) <NEW_LINE> <DEDENT> def write_file(self, location_file, to_save): <NEW_LINE> <INDENT> data=to_save.data <NEW_LINE> if _is_table(data): <NEW_LINE> <INDENT> with location_file.open("wb"): <NEW_LINE> <INDENT> self.write_data(location_file,data) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("can't save data {}".format(data))
Class for binary output file format. Args: dtype: a string with numpy dtype (e.g., ``"<f8"``) used to save the data. By default, use little-endian (``"<"``) variant kind of the supplied data array dtype transposed (bool): If ``False``, write the data row-wise; otherwise, write it column-wise.
6259904ee76e3b2f99fd9e5b
class Whitelist(Greylist): <NEW_LINE> <INDENT> def __init__(self, initialList=None): <NEW_LINE> <INDENT> if initialList is None: <NEW_LINE> <INDENT> initialList = [] <NEW_LINE> <DEDENT> Greylist.__init__(self, initialList)
A class representing a whitelist of file extensions that should be included in any watching. :group Constructor: __init__
6259904e0c0af96317c5778e
class HyperPlane: <NEW_LINE> <INDENT> tol = 1e-8 <NEW_LINE> def __init__(self, normal: np.ndarray, constant: float = 0.0): <NEW_LINE> <INDENT> self.normal = normal <NEW_LINE> self.constant = constant <NEW_LINE> <DEDENT> @property <NEW_LINE> def dim(self) -> Tuple[int, ...]: <NEW_LINE> <INDENT> return self.normal.shape <NEW_LINE> <DEDENT> def contains(self, point: np.ndarray) -> bool: <NEW_LINE> <INDENT> assert self.dim == point.shape, f'Dimension mismatch: {self.dim} != {point.shape}' <NEW_LINE> scalar_product = np.dot(self.normal, point) <NEW_LINE> return abs(scalar_product - self.constant) < self.tol <NEW_LINE> <DEDENT> def project(self, point: np.ndarray) -> np.ndarray: <NEW_LINE> <INDENT> t = (np.dot(point, self.normal) - self.constant) / np.dot(self.normal, self.normal) <NEW_LINE> return point - t * self.normal
Affine space of codimension 1. Defined by its normal vector 'normal' and the 'constant', such that a point x belongs to the hyperplane iff $normal ⋅ x = constant$.
6259904e7d847024c075d82e
class VotationDetailView(DetailView): <NEW_LINE> <INDENT> model = Votation <NEW_LINE> template_name = 'votations/votation_detail.html' <NEW_LINE> context_object_name = 'votation' <NEW_LINE> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super(VotationDetailView, self).get_context_data(**kwargs) <NEW_LINE> votation = self.get_object() <NEW_LINE> context['n_absents'] = votation.chargevote_set.filter(vote=ChargeVote.VOTES.absent).count() <NEW_LINE> context['votation_difference'] = abs(votation.n_yes - votation.n_no) <NEW_LINE> return context
Renders a Votation page
6259904e24f1403a926862fb
class ImageResizer(object): <NEW_LINE> <INDENT> def __init__(self, width, height, color=(255, 255, 255,)): <NEW_LINE> <INDENT> self.proportions = float(width)/float(height) <NEW_LINE> self.color = color <NEW_LINE> <DEDENT> def get_white_layer(self, width, height): <NEW_LINE> <INDENT> size = (width, height) <NEW_LINE> return Image.new('RGB', size, self.color) <NEW_LINE> <DEDENT> def complete(self, img_buf): <NEW_LINE> <INDENT> img_buf.seek(0) <NEW_LINE> img_obj = Image.open(img_buf) <NEW_LINE> width, height = img_obj.size <NEW_LINE> img_proportions = float(width)/float(height) <NEW_LINE> if img_proportions >= self.proportions: <NEW_LINE> <INDENT> return img_buf <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> new_width = int(height * self.proportions) <NEW_LINE> new_height = height <NEW_LINE> padding = (new_width - width) / 2 <NEW_LINE> layer = self.get_white_layer(new_width, new_height) <NEW_LINE> layer.paste(img_obj, (padding, 0)) <NEW_LINE> mybuffer = StringIO() <NEW_LINE> layer.save(mybuffer, format="PNG") <NEW_LINE> mybuffer.seek(0) <NEW_LINE> return mybuffer
Allows to resize images regarding given proportions r = ImageResize(height_proportion, width_proportion, default_color) resized_image_buffer = r.complete(image_buffer) resized_image_buffer will respect the given proportions and will be filed with the default color
6259904e07d97122c42180ff
class StatusFilterBackend(filters.BaseFilterBackend): <NEW_LINE> <INDENT> def filter_queryset(self, request, queryset, view): <NEW_LINE> <INDENT> status_param = request.query_params.get('status') <NEW_LINE> if status_param: <NEW_LINE> <INDENT> status_list = status_param.split(',') <NEW_LINE> status_list = [status.strip() for status in status_list] <NEW_LINE> queryset = queryset.filter(status__in=status_list) <NEW_LINE> <DEDENT> return queryset
Filters queryset with status parameter applied on model status field
6259904e07f4c71912bb0890
class TokensManager(base.Manager): <NEW_LINE> <INDENT> resource_class = Token <NEW_LINE> def create(self, project_id=None, account_name=None, return_raw=False): <NEW_LINE> <INDENT> body = {'token': {}} <NEW_LINE> if project_id: <NEW_LINE> <INDENT> body['token']['project_id'] = project_id <NEW_LINE> <DEDENT> if account_name: <NEW_LINE> <INDENT> body['token']['account_name'] = account_name <NEW_LINE> <DEDENT> return self._post('/tokens', body, 'token', return_raw=return_raw) <NEW_LINE> <DEDENT> def delete(self, token_id): <NEW_LINE> <INDENT> self._delete('/tokens/{}'.format(token_id)) <NEW_LINE> <DEDENT> def delete_many(self, token_ids, raise_if_not_found=True): <NEW_LINE> <INDENT> for token_id in token_ids: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.delete(token_id) <NEW_LINE> log.info("Token %s has been deleted", token_id) <NEW_LINE> <DEDENT> except ClientException as err: <NEW_LINE> <INDENT> if raise_if_not_found: <NEW_LINE> <INDENT> raise err <NEW_LINE> <DEDENT> log.error("%s %s", err, token_id)
Manager class for manipulating token.
6259904eb57a9660fecd2ed8
class ConeNode(CylinderNode): <NEW_LINE> <INDENT> __description__ = "Cone Primitve" <NEW_LINE> __instantiable__ = True
ConeNode implements a specialized CylinderNode.
6259904e23e79379d538d959
class Admin(Base): <NEW_LINE> <INDENT> def __init__(self, username, pwd): <NEW_LINE> <INDENT> self.name = username <NEW_LINE> self.pwd = pwd <NEW_LINE> <DEDENT> def create_campus(self, username, addr): <NEW_LINE> <INDENT> school = Campus(username, addr) <NEW_LINE> school.save() <NEW_LINE> <DEDENT> def create_course(self, campus_obj, course_name, course_price): <NEW_LINE> <INDENT> course = Course(course_name.lower(), course_price) <NEW_LINE> course.save() <NEW_LINE> campus_obj.course_list.append(course.name) <NEW_LINE> campus_obj.save() <NEW_LINE> <DEDENT> def create_teacher(self, name, pwd): <NEW_LINE> <INDENT> teach_obj = Teacher(name, pwd) <NEW_LINE> teach_obj.save()
管理员类,包含创建校区、创建教师、创建课程方法
6259904e94891a1f408ba123
class rjplAPIError(Exception): <NEW_LINE> <INDENT> pass
Raised when the API returned an error.
6259904e96565a6dacd2d9b7
class Anisotropic(material.Material): <NEW_LINE> <INDENT> sr = None <NEW_LINE> def __get_s(self): <NEW_LINE> <INDENT> return self.sr.full() <NEW_LINE> <DEDENT> def __set_s(self,s): <NEW_LINE> <INDENT> self.sr = s.reduced() <NEW_LINE> <DEDENT> def __get_c(self): <NEW_LINE> <INDENT> return self.cr.full() <NEW_LINE> <DEDENT> def __set_c(self,c): <NEW_LINE> <INDENT> self.cr = c.reduced() <NEW_LINE> <DEDENT> def __get_cr(self): <NEW_LINE> <INDENT> return np.linalg.inv(self.sr) <NEW_LINE> <DEDENT> def __set_cr(self,cr): <NEW_LINE> <INDENT> self.sr = np.linalg.inv(cr) <NEW_LINE> <DEDENT> s = property(__get_s,__set_s) <NEW_LINE> c = property(__get_c,__set_c) <NEW_LINE> cr = property(__get_cr,__set_cr) <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.sr = ReducedElasticMatrix() <NEW_LINE> pass
Elastic material Attributes: s: full compliance matrix sr: reduced compliance matrix c: full stiffness matrix cr: reduced stiffness matrixrotat
6259904e63b5f9789fe865ca
class Configuration(object): <NEW_LINE> <INDENT> def __init__(self, xrandr): <NEW_LINE> <INDENT> self.outputs = {} <NEW_LINE> self._xrandr = xrandr <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<%s for %d Outputs, %d active>'%(type(self).__name__, len(self.outputs), len([x for x in self.outputs.values() if x.active])) <NEW_LINE> <DEDENT> def commandlineargs(self): <NEW_LINE> <INDENT> args = [] <NEW_LINE> for on,o in self.outputs.items(): <NEW_LINE> <INDENT> args.append("--output") <NEW_LINE> args.append(on) <NEW_LINE> if not o.active: <NEW_LINE> <INDENT> args.append("--off") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if Feature.PRIMARY in self._xrandr.features: <NEW_LINE> <INDENT> if o.primary: <NEW_LINE> <INDENT> args.append("--primary") <NEW_LINE> <DEDENT> <DEDENT> args.append("--mode") <NEW_LINE> args.append(str(o.mode.name)) <NEW_LINE> args.append("--pos") <NEW_LINE> args.append(str(o.position)) <NEW_LINE> args.append("--rotate") <NEW_LINE> args.append(o.rotation) <NEW_LINE> args.append("--scale") <NEW_LINE> args.append(str(o.scale)) <NEW_LINE> <DEDENT> <DEDENT> return args <NEW_LINE> <DEDENT> class OutputConfiguration(object): <NEW_LINE> <INDENT> def __init__(self, active, primary, geometry, rotation, modename, scale): <NEW_LINE> <INDENT> self.active = active <NEW_LINE> self.primary = primary <NEW_LINE> if active: <NEW_LINE> <INDENT> self.position = geometry.position <NEW_LINE> self.rotation = rotation <NEW_LINE> if rotation.is_odd: <NEW_LINE> <INDENT> self.mode = NamedSize(Size(reversed(geometry.size)), name=modename) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.mode = NamedSize(geometry.size, name=modename) <NEW_LINE> <DEDENT> self.scale = scale <NEW_LINE> <DEDENT> <DEDENT> size = property(lambda self: NamedSize(Size(reversed(self.mode)), name=self.mode.name) if self.rotation.is_odd else self.mode)
Represents everything that can be set by xrandr (and is therefore subject to saving and loading from files)
6259904ed10714528d69f0bc
class cmndClassDocStr(Cmnd): <NEW_LINE> <INDENT> cmndParamsMandatory = None <NEW_LINE> cmndParamsOptional = None <NEW_LINE> cmndArgsLen = ["1"] <NEW_LINE> @subjectToTracking(fnLoc=True, fnEntry=True, fnExit=True) <NEW_LINE> def cmnd(self, interactive=False, cmndName=None, ): <NEW_LINE> <INDENT> G = IcmGlobalContext() <NEW_LINE> if not cmndName: <NEW_LINE> <INDENT> if not interactive: <NEW_LINE> <INDENT> EH_problem_usageError("") <NEW_LINE> return None <NEW_LINE> <DEDENT> cmndName = G.icmRunArgsGet().cmndArgs[0] <NEW_LINE> <DEDENT> cmndClass = cmndNameToClass(cmndName) <NEW_LINE> if not cmndClass: return None <NEW_LINE> docStr = cmndClass().docStrClass() <NEW_LINE> if interactive: print(docStr) <NEW_LINE> return docStr
Given a list of cmnds as Args, for each return the the class docStr.
6259904e3cc13d1c6d466b96
class VehicleStatus: <NEW_LINE> <INDENT> def __init__(self, last_updated_date: datetime, dashboard_date: datetime, odometer: Tuple[float, str], fuel_gauge: Tuple[float, str], drive_range: Tuple[float, str], trip_a: Tuple[float, str], trip_b: Tuple[float, str], hazards_on: bool, doors: Dict[str, Component], windows: Dict[str, Component], other: Dict[str, Component]): <NEW_LINE> <INDENT> self.last_updated_date = last_updated_date <NEW_LINE> self.dashboard_date = dashboard_date <NEW_LINE> self.odometer = odometer <NEW_LINE> self.fuel_gauge = fuel_gauge <NEW_LINE> self.drive_range = drive_range <NEW_LINE> self.trip_a = trip_a <NEW_LINE> self.trip_b = trip_b <NEW_LINE> self.hazards_on = hazards_on <NEW_LINE> self.doors = doors <NEW_LINE> self.windows = windows <NEW_LINE> self.other = other <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> ret = 'Last Updated: {}\n'.format(self.last_updated_date) <NEW_LINE> ret += 'Odometer: {} {}\n'.format(self.odometer[0], self.odometer[1]) <NEW_LINE> ret += 'Fuel: {} {}\n'.format(self.fuel_gauge[0], self.fuel_gauge[1]) <NEW_LINE> ret += 'Doors:\n' <NEW_LINE> for _, door in self.doors.items(): <NEW_LINE> <INDENT> ret += ' {}: '.format(door.name) <NEW_LINE> if door.closed is True: <NEW_LINE> <INDENT> ret += 'Closed' <NEW_LINE> <DEDENT> elif door.closed is False: <NEW_LINE> <INDENT> ret += 'Open' <NEW_LINE> <DEDENT> if door.closed is not None and door.locked is not None: <NEW_LINE> <INDENT> ret += ', ' <NEW_LINE> <DEDENT> if door.locked is True: <NEW_LINE> <INDENT> ret += 'Locked' <NEW_LINE> <DEDENT> elif door.closed is False: <NEW_LINE> <INDENT> ret += 'Unlocked' <NEW_LINE> <DEDENT> ret += '\n' <NEW_LINE> <DEDENT> ret += 'Windows:\n' <NEW_LINE> for _, door in self.windows.items(): <NEW_LINE> <INDENT> ret += ' {}: '.format(door.name) <NEW_LINE> if door.closed is True: <NEW_LINE> <INDENT> ret += 'Closed' <NEW_LINE> <DEDENT> elif door.closed is False: <NEW_LINE> <INDENT> ret += 'Open' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ret += 'Unknown' <NEW_LINE> <DEDENT> ret += '\n' <NEW_LINE> <DEDENT> return ret
Details on a vehicle's status
6259904e6e29344779b01aa0
class Borders: <NEW_LINE> <INDENT> def __init__(self, low_b, high_b, path, state): <NEW_LINE> <INDENT> self.low_b = low_b; self.high_b = high_b; self.path = path; self.state = state
Class of cases, containing lower border, higher border, path of numeric calculations followed to this state and number of state
6259904eac7a0e7691f73938
class GroupViewSet(DefaultsMixin, viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = Group.objects.all() <NEW_LINE> serializer_class = GroupSerializer
API endpoint that allows groups to be viewed or edited.
6259904ea79ad1619776b4de
@logged <NEW_LINE> @traced <NEW_LINE> class AnsibleAPI(Execution): <NEW_LINE> <INDENT> def __init__(self, hostname): <NEW_LINE> <INDENT> Execution.__init__(self, hostname=hostname)
@TODO Ansible API Usage
6259904ed6c5a102081e357b
class ControllerApi(object): <NEW_LINE> <INDENT> notify_widget = None <NEW_LINE> lyric_widget = None <NEW_LINE> desktop_mini = None <NEW_LINE> current_playlist_widget = None <NEW_LINE> player = None <NEW_LINE> network_manager = None <NEW_LINE> api = None <NEW_LINE> state = {"is_login": False, "current_mid": 0, "current_pid": 0, "platform": "", "other_mode": False} <NEW_LINE> @classmethod <NEW_LINE> def set_login(cls): <NEW_LINE> <INDENT> cls.state['is_login'] = True <NEW_LINE> cls.view.ui.LOVE_SONG_BTN.show() <NEW_LINE> cls.view.ui.LOGIN_BTN.hide() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def play_mv_by_mvid(cls, mvid): <NEW_LINE> <INDENT> mv_model = ControllerApi.api.get_mv_detail(mvid) <NEW_LINE> if not ControllerApi.api.is_response_ok(mv_model): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> url_high = mv_model['url_high'] <NEW_LINE> clipboard = QApplication.clipboard() <NEW_LINE> clipboard.setText(url_high) <NEW_LINE> if platform.system() == "Linux": <NEW_LINE> <INDENT> ControllerApi.player.pause() <NEW_LINE> ControllerApi.notify_widget.show_message("通知", "正在尝试调用VLC视频播放器播放MV") <NEW_LINE> subprocess.Popen(['vlc', url_high, '--play-and-exit', '-f']) <NEW_LINE> <DEDENT> elif platform.system().lower() == 'Darwin'.lower(): <NEW_LINE> <INDENT> ControllerApi.player.pause() <NEW_LINE> cls.view.ui.STATUS_BAR.showMessage(u"准备调用 QuickTime Player 播放mv", 4000) <NEW_LINE> subprocess.Popen(['open', '-a', 'QuickTime Player', url_high]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cls.view.ui.STATUS_BAR.showMessage(u"程序已经将视频的播放地址复制到剪切板", 5000) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def toggle_lyric_widget(cls): <NEW_LINE> <INDENT> if ControllerApi.lyric_widget.isVisible(): <NEW_LINE> <INDENT> ControllerApi.lyric_widget.close() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ControllerApi.lyric_widget.show() <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def toggle_desktop_mini(cls): <NEW_LINE> <INDENT> if ControllerApi.desktop_mini.isVisible(): <NEW_LINE> <INDENT> ControllerApi.desktop_mini.close() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ControllerApi.desktop_mini.show() <NEW_LINE> ControllerApi.notify_widget.show_message("Tips", "按ESC可以退出mini模式哦 ~") <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> @pyqtSlot(int) <NEW_LINE> def seek(cls, seconds): <NEW_LINE> <INDENT> cls.player.setPosition(seconds * 1000) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def play_specific_song_by_mid(cls, mid): <NEW_LINE> <INDENT> song = ControllerApi.api.get_song_detail(mid) <NEW_LINE> if not ControllerApi.api.is_response_ok(song): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> ControllerApi.player.play(song) <NEW_LINE> return True
暴露给plugin或者其他外部模块的接口和数据
6259904e71ff763f4b5e8c05
class BestiaryEntry(abc.Serializable): <NEW_LINE> <INDENT> def __init__(self, name, kills, step): <NEW_LINE> <INDENT> self.name: str = name <NEW_LINE> self.kills: int = kills <NEW_LINE> self.step: int = step <NEW_LINE> <DEDENT> __slots__ = ( "name", "kills", "step", ) <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return f"<{self.__class__.__name__} name={self.name!r} kills={self.kills} step={self.step}>" <NEW_LINE> <DEDENT> @property <NEW_LINE> def completed(self): <NEW_LINE> <INDENT> return self.step == 4
The bestiary progress for a specific creature. Attributes ---------- name: :class:`str` The name of the creature. kills: :class:`int` The number of kills of this creature the player has done. step: :class:`int` The current step to unlock this creature the character is in, where 4 is fully unlocked.
6259904e07d97122c4218102
class InconsistentVmDetails(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'vm_name': {'key': 'vmName', 'type': 'str'}, 'cloud_name': {'key': 'cloudName', 'type': 'str'}, 'details': {'key': 'details', 'type': '[str]'}, 'error_ids': {'key': 'errorIds', 'type': '[str]'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(InconsistentVmDetails, self).__init__(**kwargs) <NEW_LINE> self.vm_name = kwargs.get('vm_name', None) <NEW_LINE> self.cloud_name = kwargs.get('cloud_name', None) <NEW_LINE> self.details = kwargs.get('details', None) <NEW_LINE> self.error_ids = kwargs.get('error_ids', None)
This class stores the monitoring details for consistency check of inconsistent Protected Entity. :param vm_name: The Vm name. :type vm_name: str :param cloud_name: The Cloud name. :type cloud_name: str :param details: The list of details regarding state of the Protected Entity in SRS and On prem. :type details: list[str] :param error_ids: The list of error ids. :type error_ids: list[str]
6259904e23e79379d538d95b
class RandomHorizontalFlip(object): <NEW_LINE> <INDENT> def __call__(self, img, random_samples): <NEW_LINE> <INDENT> if random_samples < 0.5: <NEW_LINE> <INDENT> return img.transpose(Image.FLIP_LEFT_RIGHT) <NEW_LINE> <DEDENT> return img <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def name(): <NEW_LINE> <INDENT> return 'RandomHorizontalFlip'
Horizontally flip the given PIL.Image randomly with a probability of 0.5.
6259904e07f4c71912bb0893
class Stock: <NEW_LINE> <INDENT> def __init__(self, stockSummaryDict, stockHistoricalPricesDict, stockHistoricalDividendsDict, stockFinancialProfileDict, stockCompanyProfileDict, stockDirectorDict) : <NEW_LINE> <INDENT> self.stockSummaryDict = stockSummaryDict <NEW_LINE> self.stockHistoricalPricesDict = stockHistoricalPricesDict <NEW_LINE> self.stockHistoricalDividendsDict = stockHistoricalDividendsDict <NEW_LINE> self.stockFinancialProfileDict = stockFinancialProfileDict <NEW_LINE> self.stockCompanyProfileDict = stockCompanyProfileDict <NEW_LINE> self.stockDirectorDict = stockDirectorDict <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.__dict__)
This class is now DEPRECATED, we now use a dictionary to store the neccesary company information. See scrape_data(419)
6259904e76d4e153a661dca7
class CheckSphericalContainer(ConfTest): <NEW_LINE> <INDENT> m_radius2: float = 0 <NEW_LINE> ndim = 0 <NEW_LINE> def __init__(self, radius: float, ndim): <NEW_LINE> <INDENT> self.m_radius2 = radius <NEW_LINE> self.ndim = ndim <NEW_LINE> return None <NEW_LINE> <DEDENT> def conf_test(self, trial_coords: np.ndarray) -> bool: <NEW_LINE> <INDENT> r2: float = 0 <NEW_LINE> i =0 <NEW_LINE> r2 = np.inner(trial_coords, trial_coords) <NEW_LINE> if (r2> self.m_radius2): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True
Check that the system is within a spherical container Parameters ---------- radius2 : double radius of the spherical container, centered at **0** ndim : int dimensionality of the space (box dimensionality)
6259904e009cb60464d02997
class MulForm(Form): <NEW_LINE> <INDENT> p = FloatField(label='p value', default=1) <NEW_LINE> q = FloatField(label='q value', default=1)
A class for the multiply program
6259904e15baa723494633eb
class ScannerTest(unittest.TestCase): <NEW_LINE> <INDENT> def test_single_character(self): <NEW_LINE> <INDENT> text = 'b' <NEW_LINE> testdata = [ dict(index=0, line=0, column=0, text=text), ] <NEW_LINE> s = parsing.Scanner(text=text) <NEW_LINE> for i in range(len(text)): <NEW_LINE> <INDENT> c = s.get() <NEW_LINE> expected = parsing.Character(**testdata[i]) <NEW_LINE> self.assertEqual(c, expected)
Unittests for Scanner class.
6259904ecad5886f8bdc5aad
class PoolSpace(ctypes.Structure): <NEW_LINE> <INDENT> _fields_ = [("ps_space", Daos_Space), ("ps_free_min", ctypes.c_uint64 * 2), ("ps_free_max", ctypes.c_uint64 * 2), ("ps_free_mean", ctypes.c_uint64 * 2), ("ps_ntargets", ctypes.c_uint32), ("ps_padding", ctypes.c_uint32)]
Structure to represent Pool space usage info
6259904e596a897236128fde
class CardQuery: <NEW_LINE> <INDENT> def __init__(self, max_count=30, max_score=1.0, max_proficiency=10, card_type=None): <NEW_LINE> <INDENT> self.max_count = max_count <NEW_LINE> self.max_score = max_score <NEW_LINE> self.max_proficiency = max_proficiency <NEW_LINE> self.card_type = None <NEW_LINE> <DEDENT> def matches(self, card: Card, study_data) -> bool: <NEW_LINE> <INDENT> if self.card_type is not None and card.get_word_type() != self.card_type: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if self.max_score is not None and study_data.get_history_score() > self.max_score: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if self.max_proficiency is not None and study_data.get_proficiency_level() > self.max_proficiency: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True
Queries a list of cards.
6259904ef7d966606f7492e7
class BidsList(APIView): <NEW_LINE> <INDENT> def get(self, request, format=None): <NEW_LINE> <INDENT> data = create_fake_auction_bids(fake, CONST.NUM_OF_AUCTION_BIDS) <NEW_LINE> return Response(data)
List all Bids or create a new Bid
6259904e63d6d428bbee3c2a
class MyMplCanvas(FigureCanvas): <NEW_LINE> <INDENT> def __init__(self, parent=None, img=np.ones((576, 384))*1.2, width=3, aspect=576/384.): <NEW_LINE> <INDENT> height = width*aspect <NEW_LINE> self.aspect = aspect <NEW_LINE> self.img = img <NEW_LINE> self.imgsize = self.img.shape <NEW_LINE> self.datafilepath = None <NEW_LINE> self.rois = {'ncount':None, 'analysis':None, 'noatom':None} <NEW_LINE> self.roiboxes = {'ncount':None, 'analysis':None, 'noatom':None} <NEW_LINE> self.roicols = {'ncount':coldict['purple'], 'analysis':coldict['blue'], 'noatom':coldict['orange']} <NEW_LINE> self.marker = None <NEW_LINE> self.markerlines = None <NEW_LINE> self.colmaps = {'gray':mpl.cm.gray, 'copper':mpl.cm.copper, 'hot':mpl.cm.hot, 'jet':mpl.cm.jet, 'spectral':mpl.cm.spectral, 'earth':mpl.cm.gist_earth} <NEW_LINE> mpl.pyplot.rc('figure.subplot', left=1e-3) <NEW_LINE> mpl.pyplot.rc('figure.subplot', bottom=1e-3) <NEW_LINE> mpl.pyplot.rc('figure.subplot', right=1-1e-3) <NEW_LINE> mpl.pyplot.rc('figure.subplot', top=1-1e-3) <NEW_LINE> mpl.pyplot.rc('figure', fc=coldict['bgcolor'], ec=coldict['bgcolor']) <NEW_LINE> mpl.pyplot.rc('axes', fc=coldict['bgcolor']) <NEW_LINE> mpl.pyplot.rc('axes', lw=0.5) <NEW_LINE> mpl.pyplot.rc('axes', labelsize=10) <NEW_LINE> mpl.pyplot.rc('xtick', labelsize=8) <NEW_LINE> mpl.pyplot.rc('ytick', labelsize=8) <NEW_LINE> self.fig = Figure(figsize=(width, height)) <NEW_LINE> self.ax = self.fig.add_subplot(111) <NEW_LINE> self.ax.hold(False) <NEW_LINE> self.init_figure() <NEW_LINE> FigureCanvas.__init__(self, self.fig) <NEW_LINE> self.setParent(parent) <NEW_LINE> FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding) <NEW_LINE> FigureCanvas.updateGeometry(self) <NEW_LINE> self.setMinimumSize(200, 200) <NEW_LINE> self.setFocusPolicy(Qt.ClickFocus) <NEW_LINE> <DEDENT> def sizeHint(self): <NEW_LINE> <INDENT> w, h = self.get_width_height() <NEW_LINE> return QSize(w, round(w*self.aspect)) <NEW_LINE> <DEDENT> def heightForWidth(self, width): <NEW_LINE> <INDENT> return round(width*self.aspect)
Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.).
6259904e91af0d3eaad3b283
class Timer(pythics.libcontrol.Control): <NEW_LINE> <INDENT> def __init__(self, parent, label=None, **kwargs): <NEW_LINE> <INDENT> pythics.libcontrol.Control.__init__(self, parent, **kwargs) <NEW_LINE> if label is None or label == '': <NEW_LINE> <INDENT> self._widget = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._widget = QtWidgets.QLabel(label) <NEW_LINE> <DEDENT> <DEDENT> def _register(self, process, element_id, proxy_key): <NEW_LINE> <INDENT> self._element_id = element_id <NEW_LINE> self._process = process <NEW_LINE> if 'triggered' in self.actions: <NEW_LINE> <INDENT> action = self.actions['triggered'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> action = None <NEW_LINE> <DEDENT> self._proxy = pythics.proxies.TimerProxy(action)
A control which makes calls to an action at regular time intervals. Most settings are controlled in a call to `start`, which begins the timer. The timer can be stopped by calling the `stop` method. The timer may be started and stopped multiple times. Due to the mult-threaded nature of Timers, most control properties are read-only and can only be set by calling `start`. HTML parameters: *label*: [ str | *None* (default) ] text to show in GUI *actions*: dict a dictionary of key:value pairs where the key is the name of a signal and value is the function to run when the signal is emitted actions in this control: ================ =================================================== signal when emitted ================ =================================================== 'triggered' action is triggered ================ ===================================================
6259904eec188e330fdf9cfd
class DirectoryUserDeviceLinkData(object): <NEW_LINE> <INDENT> def __init__(self, data): <NEW_LINE> <INDENT> self.qrcode = data['qrcode'] <NEW_LINE> self.code = data['code'] <NEW_LINE> self.device_id = data['device_id']
Directory user device data used to finish the linking process
6259904e379a373c97d9a48a
class IDataAccess(metaclass=ABCMeta): <NEW_LINE> <INDENT> @abstractmethod <NEW_LINE> def read(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def save(self, data: list): <NEW_LINE> <INDENT> pass
Interface for data access implementation :Author: Zhiming Liu
6259904e0a366e3fb87dde45
class PadInsn(Insn): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def decode(cls, i): <NEW_LINE> <INDENT> return ( uint_field(i, 6, 22), uint_field(i, 28, 4), ) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def is_valid(cls, opu, addr, p): <NEW_LINE> <INDENT> return all_defined([ opu.reg.ofm_addr, opu.reg.ofm_mem_h, opu.reg.ofm_mem_w ]) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def apply(cls, opu, addr, p): <NEW_LINE> <INDENT> ver = opu.itype.from_real(np.zeros([64 * p])).to_real() <NEW_LINE> hor = opu.itype.from_real(np.zeros([opu.reg.ofm_mem_w * 64])).to_real() <NEW_LINE> addr_base = opu.reg.ofm_addr + addr * 64 <NEW_LINE> for i in range(p): <NEW_LINE> <INDENT> a = addr_base + i * 64 * opu.reg.ofm_mem_w <NEW_LINE> opu.vmem[a:a+64*opu.reg.ofm_mem_w] = hor <NEW_LINE> a += (opu.reg.ofm_mem_h - p) * 64 * opu.reg.ofm_mem_w <NEW_LINE> opu.vmem[a:a+64*opu.reg.ofm_mem_w] = hor <NEW_LINE> <DEDENT> for i in range(opu.reg.ofm_mem_h): <NEW_LINE> <INDENT> a = addr_base + i * 64 * opu.reg.ofm_mem_w <NEW_LINE> opu.vmem[a:a+64*p] = ver <NEW_LINE> a += (opu.reg.ofm_mem_w - p) * 64 <NEW_LINE> opu.vmem[a:a+64*p] = ver
pad instruction
6259904ed53ae8145f9198c1
class AsuswrtTotalTXSensor(AsuswrtSensor): <NEW_LINE> <INDENT> _name = "Asuswrt Upload" <NEW_LINE> _unit = DATA_GIGABYTES <NEW_LINE> @property <NEW_LINE> def unit_of_measurement(self): <NEW_LINE> <INDENT> return self._unit <NEW_LINE> <DEDENT> async def async_update(self): <NEW_LINE> <INDENT> await super().async_update() <NEW_LINE> if self._rates: <NEW_LINE> <INDENT> self._state = round(self._rates[1] / 1000000000, 1)
Representation of a asuswrt total upload sensor.
6259904e99cbb53fe6832344
class MessageViewlet(object): <NEW_LINE> <INDENT> available = True <NEW_LINE> render = ViewPageTemplateFile("templates/messages.pt") <NEW_LINE> def update(self): <NEW_LINE> <INDENT> self.messages = self.getMessages() <NEW_LINE> if not len(self.messages): <NEW_LINE> <INDENT> self.available = False <NEW_LINE> <DEDENT> <DEDENT> def getMessages(self): <NEW_LINE> <INDENT> raise NotImplementedError("Child class must implement this")
display a message with optional level info
6259904eb5575c28eb7136f9
class Rectangle(object): <NEW_LINE> <INDENT> def __init__(self, lo, hi): <NEW_LINE> <INDENT> if not isinstance(lo, Vector): <NEW_LINE> <INDENT> lo = Vector(lo) <NEW_LINE> <DEDENT> if not isinstance(hi, Vector): <NEW_LINE> <INDENT> hi = Vector(hi) <NEW_LINE> <DEDENT> self.lo = lo <NEW_LINE> self.hi = hi <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> params = (self.lo, self.hi) <NEW_LINE> return "Rectangle(%s, %s)" % params <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> params = (self.lo, self.hi) <NEW_LINE> return "Rectangle(%r, %r)" % params <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def as_bounding(cls, points): <NEW_LINE> <INDENT> xs, ys = zip(*points) <NEW_LINE> lo = (min(xs), min(ys)) <NEW_LINE> hi = (max(xs), max(ys)) <NEW_LINE> return cls(lo, hi)
Two-dimensional vector (axis-aligned) rectangle implementation.
6259904e73bcbd0ca4bcb6e9
class User(models.Model): <NEW_LINE> <INDENT> username = models.CharField(max_length=32, unique=True) <NEW_LINE> password = models.CharField(max_length=64) <NEW_LINE> realname = models.CharField(max_length=64) <NEW_LINE> sex_choices = ( (0, '女'), (1, '男'), ) <NEW_LINE> sex = models.SmallIntegerField(choices=sex_choices, default=0) <NEW_LINE> email = models.EmailField(max_length=64) <NEW_LINE> phone = models.IntegerField() <NEW_LINE> position = models.CharField(max_length=64, blank=True, null=True) <NEW_LINE> date = models.DateField(auto_now_add=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name_plural = '用户表' <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.username
用户表
6259904e76d4e153a661dca8
class RegexExtract(object): <NEW_LINE> <INDENT> schema = { 'type': 'object', 'properties': { 'prefix': {'type': 'string'}, 'field': {'type': 'string'}, 'regex': one_or_more({'type': 'string', 'format': 'regex'}), }, } <NEW_LINE> def on_task_start(self, task, config): <NEW_LINE> <INDENT> regex = config.get('regex') <NEW_LINE> if isinstance(regex, basestring): <NEW_LINE> <INDENT> regex = [regex] <NEW_LINE> <DEDENT> self.regex_list = ReList(regex) <NEW_LINE> try: <NEW_LINE> <INDENT> for _ in self.regex_list: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> except re.error as e: <NEW_LINE> <INDENT> raise plugin.PluginError('Error compiling regex: %s' % str(e)) <NEW_LINE> <DEDENT> <DEDENT> def on_task_modify(self, task, config): <NEW_LINE> <INDENT> prefix = config.get('prefix') <NEW_LINE> modified = 0 <NEW_LINE> for entry in task.entries: <NEW_LINE> <INDENT> for rx in self.regex_list: <NEW_LINE> <INDENT> entry_field = entry.get('title') <NEW_LINE> log.debug('Matching %s with regex: %s' % (entry_field, rx)) <NEW_LINE> try: <NEW_LINE> <INDENT> match = rx.match(entry_field) <NEW_LINE> <DEDENT> except re.error as e: <NEW_LINE> <INDENT> raise plugin.PluginError('Error encountered processing regex: %s' % str(e)) <NEW_LINE> <DEDENT> if match: <NEW_LINE> <INDENT> log.debug('Successfully matched %s' % entry_field) <NEW_LINE> data = match.groupdict() <NEW_LINE> if prefix: <NEW_LINE> <INDENT> for key in list(data.keys()): <NEW_LINE> <INDENT> data[prefix + key] = data[key] <NEW_LINE> del data[key] <NEW_LINE> <DEDENT> <DEDENT> log.debug('Values added to entry: %s' % data) <NEW_LINE> entry.update(data) <NEW_LINE> modified += 1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> log.info('%d entries matched and modified' % modified)
Updates an entry with the values of regex matched named groups Usage: regex_extract: field: <string> regex: - <regex> [prefix]: <string> Example: regex_extract: prefix: f1_ field: title regex: - Formula\.?1.(?P<location>*?)
6259904e23849d37ff85251e
class BoardListView(ListView): <NEW_LINE> <INDENT> model = Board <NEW_LINE> context_object_name = 'boards' <NEW_LINE> template_name = 'home.html'
/
6259904e462c4b4f79dbce60
class QueryUniversities(View): <NEW_LINE> <INDENT> def get(self, request): <NEW_LINE> <INDENT> response = {} <NEW_LINE> query_word = request.GET.get('query_word') <NEW_LINE> list_of_uni = find_universities(query_word) <NEW_LINE> response['universities'] = list(list_of_uni) <NEW_LINE> return HttpResponse(HttpResponse(json.dumps(response), status=201))
AJAX View
6259904ed99f1b3c44d06afa
class Token(Model): <NEW_LINE> <INDENT> required_keys = ('id', 'expires') <NEW_LINE> optional_keys = ('extra',)
Token object. Required keys: id expires (datetime) Optional keys: user project metadata
6259904e1f037a2d8b9e529c
class Not(Query): <NEW_LINE> <INDENT> def __init__(self, query, boost = 1.0): <NEW_LINE> <INDENT> self.query = query <NEW_LINE> self.boost = boost <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "%s(%s)" % (self.__class__.__name__, repr(self.query)) <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return u"NOT " + unicode(self.query) <NEW_LINE> <DEDENT> def normalize(self): <NEW_LINE> <INDENT> if self.query is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> def docs(self, searcher): <NEW_LINE> <INDENT> return self.query.docs(searcher) <NEW_LINE> <DEDENT> def replace(self, oldtext, newtext): <NEW_LINE> <INDENT> return Not(self.query.replace(oldtext, newtext), boost = self.boost) <NEW_LINE> <DEDENT> def all_terms(self, termset): <NEW_LINE> <INDENT> self.query.all_terms(termset) <NEW_LINE> <DEDENT> def existing_terms(self, searcher, termset, reverse = False): <NEW_LINE> <INDENT> self.query.existing_terms(searcher, termset, reverse = reverse)
Excludes any documents that match the subquery.
6259904ed53ae8145f9198c4
class AnimeList(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.anime = None <NEW_LINE> self.statistics = None
Model that represents an AnimeList object.
6259904e71ff763f4b5e8c09
class EpicsMotorShutter(OneSignalShutter): <NEW_LINE> <INDENT> signal = Component(EpicsMotor, "") <NEW_LINE> tolerance = 0.01 <NEW_LINE> @property <NEW_LINE> def state(self): <NEW_LINE> <INDENT> if abs(self.signal.user_readback.get() - self.open_value) <= self.tolerance: <NEW_LINE> <INDENT> result = self.valid_open_values[0] <NEW_LINE> <DEDENT> elif abs(self.signal.user_readback.get() - self.close_value) <= self.tolerance: <NEW_LINE> <INDENT> result = self.valid_close_values[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result = self.unknown_state <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def open(self): <NEW_LINE> <INDENT> if not self.isOpen: <NEW_LINE> <INDENT> self.signal.move(self.open_value) <NEW_LINE> if self.delay_s > 0: <NEW_LINE> <INDENT> time.sleep(self.delay_s) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def close(self): <NEW_LINE> <INDENT> self.signal.move(self.close_value) <NEW_LINE> if not self.isClosed: <NEW_LINE> <INDENT> self.signal.move(self.close_value) <NEW_LINE> if self.delay_s > 0: <NEW_LINE> <INDENT> time.sleep(self.delay_s)
Shutter, implemented with an EPICS motor moved between two positions .. index:: Ophyd Device; EpicsMotorShutter EXAMPLE:: tomo_shutter = EpicsMotorShutter("2bma:m23", name="tomo_shutter") tomo_shutter.close_value = 1.0 # default tomo_shutter.open_value = 0.0 # default tomo_shutter.tolerance = 0.01 # default tomo_shutter.open() tomo_shutter.close() # or, when used in a plan def planA(): yield from abs_set(tomo_shutter, "open", group="O") yield from wait("O") yield from abs_set(tomo_shutter, "close", group="X") yield from wait("X") def planA(): yield from abs_set(tomo_shutter, "open", wait=True) yield from abs_set(tomo_shutter, "close", wait=True) def planA(): yield from mv(tomo_shutter, "open") yield from mv(tomo_shutter, "close")
6259904e435de62698e9d26a
class Weight(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.swagger_types = { 'query': 'str', 'value': 'float' } <NEW_LINE> self.attribute_map = { 'query': 'Query', 'value': 'Value' } <NEW_LINE> self._query = None <NEW_LINE> self._value = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def query(self): <NEW_LINE> <INDENT> return self._query <NEW_LINE> <DEDENT> @query.setter <NEW_LINE> def query(self, query): <NEW_LINE> <INDENT> self._query = query <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> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
6259904e0fa83653e46f6340
class StdTuplePrinter: <NEW_LINE> <INDENT> class _iterator: <NEW_LINE> <INDENT> def __init__ (self, head): <NEW_LINE> <INDENT> self.head = head <NEW_LINE> nodes = self.head.type.fields () <NEW_LINE> if len (nodes) == 1: <NEW_LINE> <INDENT> self.head = self.head.cast (nodes[0].type) <NEW_LINE> <DEDENT> elif len (nodes) != 0: <NEW_LINE> <INDENT> raise ValueError("Top of tuple tree does not consist of a single node.") <NEW_LINE> <DEDENT> self.count = 0 <NEW_LINE> <DEDENT> def __iter__ (self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def next (self): <NEW_LINE> <INDENT> nodes = self.head.type.fields () <NEW_LINE> if len (nodes) == 0: <NEW_LINE> <INDENT> raise StopIteration <NEW_LINE> <DEDENT> if len (nodes) != 2: <NEW_LINE> <INDENT> raise ValueError("Cannot parse more than 2 nodes in a tuple tree.") <NEW_LINE> <DEDENT> impl = self.head.cast (nodes[1].type) <NEW_LINE> self.head = self.head.cast (nodes[0].type) <NEW_LINE> self.count = self.count + 1 <NEW_LINE> fields = impl.type.fields () <NEW_LINE> if len (fields) < 1 or fields[0].name != "_M_head_impl": <NEW_LINE> <INDENT> return ('[%d]' % self.count, impl) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return ('[%d]' % self.count, impl['_M_head_impl']) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __init__ (self, typename, val): <NEW_LINE> <INDENT> self.typename = typename <NEW_LINE> self.val = val; <NEW_LINE> <DEDENT> def children (self): <NEW_LINE> <INDENT> return self._iterator (self.val) <NEW_LINE> <DEDENT> def to_string (self): <NEW_LINE> <INDENT> if len (self.val.type.fields ()) == 0: <NEW_LINE> <INDENT> return 'empty %s' % (self.typename) <NEW_LINE> <DEDENT> return '%s containing' % (self.typename)
Print a std::tuple
6259904e99cbb53fe6832346
class SighthoundEntity(ImageProcessingEntity): <NEW_LINE> <INDENT> def __init__(self, api, camera_entity, name): <NEW_LINE> <INDENT> self._api = api <NEW_LINE> self._camera = camera_entity <NEW_LINE> if name: <NEW_LINE> <INDENT> self._name = name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> camera_name = split_entity_id(camera_entity)[1] <NEW_LINE> self._name = f"sighthound_{camera_name}" <NEW_LINE> <DEDENT> self._state = None <NEW_LINE> self._image_width = None <NEW_LINE> self._image_height = None <NEW_LINE> <DEDENT> def process_image(self, image): <NEW_LINE> <INDENT> detections = self._api.detect(image) <NEW_LINE> people = hound.get_people(detections) <NEW_LINE> self._state = len(people) <NEW_LINE> metadata = hound.get_metadata(detections) <NEW_LINE> self._image_width = metadata["image_width"] <NEW_LINE> self._image_height = metadata["image_height"] <NEW_LINE> for person in people: <NEW_LINE> <INDENT> self.fire_person_detected_event(person) <NEW_LINE> <DEDENT> <DEDENT> def fire_person_detected_event(self, person): <NEW_LINE> <INDENT> self.hass.bus.fire( EVENT_PERSON_DETECTED, { ATTR_ENTITY_ID: self.entity_id, ATTR_BOUNDING_BOX: hound.bbox_to_tf_style( person["boundingBox"], self._image_width, self._image_height ), }, ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def camera_entity(self): <NEW_LINE> <INDENT> return self._camera <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @property <NEW_LINE> def should_poll(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> @property <NEW_LINE> def state(self): <NEW_LINE> <INDENT> return self._state <NEW_LINE> <DEDENT> @property <NEW_LINE> def unit_of_measurement(self): <NEW_LINE> <INDENT> return ATTR_PEOPLE
Create a sighthound entity.
6259904ecb5e8a47e493cbb7
class InpatientDiet (ModelSQL, ModelView): <NEW_LINE> <INDENT> __name__="gnuhealth.inpatient.diet" <NEW_LINE> name = fields.Many2One('gnuhealth.inpatient.registration', 'Registration Code') <NEW_LINE> diet = fields.Many2One('gnuhealth.diet.therapeutic', 'Diet', required=True) <NEW_LINE> remarks = fields.Text('Remarks / Directions', help='specific remarks for this diet / patient')
Inpatient Diet
6259904e07f4c71912bb0896
class DBConnector(db.RealDatabaseMixin, unittest.TestCase): <NEW_LINE> <INDENT> @defer.inlineCallbacks <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> yield self.setUpRealDatabase(table_names=[ 'changes', 'change_properties', 'change_files', 'patches', 'sourcestamps', 'buildset_properties', 'buildsets', 'sourcestampsets']) <NEW_LINE> self.master = fakemaster.make_master() <NEW_LINE> self.master.config = config.MasterConfig() <NEW_LINE> self.db = connector.DBConnector(self.master, os.path.abspath('basedir')) <NEW_LINE> <DEDENT> @defer.inlineCallbacks <NEW_LINE> def tearDown(self): <NEW_LINE> <INDENT> if self.db.running: <NEW_LINE> <INDENT> yield self.db.stopService() <NEW_LINE> <DEDENT> yield self.tearDownRealDatabase() <NEW_LINE> <DEDENT> @defer.inlineCallbacks <NEW_LINE> def startService(self, check_version=False): <NEW_LINE> <INDENT> self.master.config.db['db_url'] = self.db_url <NEW_LINE> yield self.db.setup(check_version=check_version) <NEW_LINE> self.db.startService() <NEW_LINE> yield self.db.reconfigServiceWithBuildbotConfig(self.master.config) <NEW_LINE> <DEDENT> def test_doCleanup_service(self): <NEW_LINE> <INDENT> d = self.startService() <NEW_LINE> @d.addCallback <NEW_LINE> def check(_): <NEW_LINE> <INDENT> self.assertTrue(self.db.cleanup_timer.running) <NEW_LINE> <DEDENT> <DEDENT> def test_doCleanup_unconfigured(self): <NEW_LINE> <INDENT> self.db.changes.pruneChanges = mock.Mock( return_value=defer.succeed(None)) <NEW_LINE> self.db._doCleanup() <NEW_LINE> self.assertFalse(self.db.changes.pruneChanges.called) <NEW_LINE> <DEDENT> def test_doCleanup_configured(self): <NEW_LINE> <INDENT> self.db.changes.pruneChanges = mock.Mock( return_value=defer.succeed(None)) <NEW_LINE> d = self.startService() <NEW_LINE> @d.addCallback <NEW_LINE> def check(_): <NEW_LINE> <INDENT> self.db._doCleanup() <NEW_LINE> self.assertTrue(self.db.changes.pruneChanges.called) <NEW_LINE> <DEDENT> return d <NEW_LINE> <DEDENT> def test_setup_check_version_bad(self): <NEW_LINE> <INDENT> d = self.startService(check_version=True) <NEW_LINE> return self.assertFailure(d, exceptions.DatabaseNotReadyError) <NEW_LINE> <DEDENT> def test_setup_check_version_good(self): <NEW_LINE> <INDENT> self.db.model.is_current = lambda: defer.succeed(True) <NEW_LINE> return self.startService(check_version=True)
Basic tests of the DBConnector class - all start with an empty DB
6259904e73bcbd0ca4bcb6eb
class RenderingTestCase(TestCase): <NEW_LINE> <INDENT> def doRendering(self, fragmentClass): <NEW_LINE> <INDENT> siteStore = Store() <NEW_LINE> loginSystem = LoginSystem(store=siteStore) <NEW_LINE> installOn(loginSystem, siteStore) <NEW_LINE> p = Product(store=siteStore, types=["xmantissa.webadmin.LocalUserBrowser", "xmantissa.signup.SignupConfiguration"]) <NEW_LINE> account = loginSystem.addAccount(u'testuser', u'localhost', None) <NEW_LINE> p.installProductOn(account.avatars.open()) <NEW_LINE> f = fragmentClass(None, u'testuser', account) <NEW_LINE> p = LivePage( docFactory=stan( html[ head(render=directive('liveglue')), body(render=lambda ctx, data: f)])) <NEW_LINE> f.setFragmentParent(p) <NEW_LINE> ctx = WovenContext() <NEW_LINE> req = FakeRequest() <NEW_LINE> ctx.remember(req, IRequest) <NEW_LINE> d = p.renderHTTP(ctx) <NEW_LINE> def rendered(ign): <NEW_LINE> <INDENT> p.action_close(None) <NEW_LINE> <DEDENT> d.addCallback(rendered) <NEW_LINE> return d <NEW_LINE> <DEDENT> def test_endowRendering(self): <NEW_LINE> <INDENT> return self.doRendering(EndowFragment) <NEW_LINE> <DEDENT> def test_depriveRendering(self): <NEW_LINE> <INDENT> return self.doRendering(DepriveFragment) <NEW_LINE> <DEDENT> def test_suspendRendering(self): <NEW_LINE> <INDENT> return self.doRendering(SuspendFragment) <NEW_LINE> <DEDENT> def test_unsuspendRendering(self): <NEW_LINE> <INDENT> return self.doRendering(UnsuspendFragment)
Test cases for HTML rendering of various fragments.
6259904e23e79379d538d95f
class deprecated(object): <NEW_LINE> <INDENT> def __init__( self, alternative_feature=None, removal_date='soon', exception=UserWarning ): <NEW_LINE> <INDENT> self.alternative_feature_message = ( alternative_feature and 'use %r instead' % alternative_feature or '' ) <NEW_LINE> self.exception = exception <NEW_LINE> self.removal_date = removal_date <NEW_LINE> <DEDENT> def __call__(self, func): <NEW_LINE> <INDENT> class_name = '' <NEW_LINE> if getattr(func, 'im_class', None): <NEW_LINE> <INDENT> class_name = '%s.' % func.im_class.__name__ <NEW_LINE> <DEDENT> if getattr(func, 'im_func', None): <NEW_LINE> <INDENT> func_name = func.im_func.func_name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> func_name = func.func_name <NEW_LINE> <DEDENT> module_name = getattr(func, '__module__') <NEW_LINE> warning = "`%s.%s%s()` is deprecated and will be removed %s. %s" % ( module_name, class_name, func_name, self.removal_date, self.alternative_feature_message ) <NEW_LINE> @functools.wraps(func) <NEW_LINE> def inner(*args, **kwargs): <NEW_LINE> <INDENT> if not getattr(func, 'deprecation_warned', False): <NEW_LINE> <INDENT> warnings.warn(warning, self.exception, 2) <NEW_LINE> func.deprecation_warned = True <NEW_LINE> <DEDENT> return func(*args, **kwargs) <NEW_LINE> <DEDENT> return inner
method or function decorator used to warn of pending feature removal: >>> @deprecated() ... def myfunc(): ... return 'hello' ... >>> myfunc() DeprecationWarning: `__main__.myfunc()` is deprecated and will be removed soon. 'hello' >>> class MyClass(object): ... @deprecated(alternative_feature='print') ... def myprint(self, *args, **kwargs): ... print(*args, **kwargs) ... >>> obj = MyClass() >>> obj.myprint("hello") DeprecationWarning: `__main__.MyClass.myfunc()` is deprecated and will be removed soon. Use 'print' instead. hello
6259904e76d4e153a661dca9
class settings_json(ProtectedPage): <NEW_LINE> <INDENT> def GET(self): <NEW_LINE> <INDENT> web.header(u"Access-Control-Allow-Origin", u"*") <NEW_LINE> web.header(u"Content-Type", u"application/json") <NEW_LINE> return json.dumps(params)
Returns plugin settings in JSON format
6259904e07f4c71912bb0897
class DateTimeProperty(Property): <NEW_LINE> <INDENT> form_field_class = 'DateTimeField' <NEW_LINE> def __init__(self, default_now=False, **kwargs): <NEW_LINE> <INDENT> if default_now: <NEW_LINE> <INDENT> if 'default' in kwargs: <NEW_LINE> <INDENT> raise ValueError('too many defaults') <NEW_LINE> <DEDENT> kwargs['default'] = lambda: datetime.utcnow().replace(tzinfo=pytz.utc) <NEW_LINE> <DEDENT> super(DateTimeProperty, self).__init__(**kwargs) <NEW_LINE> <DEDENT> @validator <NEW_LINE> def inflate(self, value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> epoch = float(value) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise ValueError("Float or integer expected, got {0} can't inflate to " "datetime.".format(type(value))) <NEW_LINE> <DEDENT> return datetime.utcfromtimestamp(epoch).replace(tzinfo=pytz.utc) <NEW_LINE> <DEDENT> @validator <NEW_LINE> def deflate(self, value): <NEW_LINE> <INDENT> if not isinstance(value, datetime): <NEW_LINE> <INDENT> raise ValueError('datetime object expected, got {0}.'.format(type(value))) <NEW_LINE> <DEDENT> if value.tzinfo: <NEW_LINE> <INDENT> value = value.astimezone(pytz.utc) <NEW_LINE> epoch_date = datetime(1970, 1, 1, tzinfo=pytz.utc) <NEW_LINE> <DEDENT> elif config.FORCE_TIMEZONE: <NEW_LINE> <INDENT> raise ValueError("Error deflating {}: No timezone provided.".format(value)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> epoch_date = datetime(1970, 1, 1) <NEW_LINE> <DEDENT> return float((value - epoch_date).total_seconds())
A property representing a :class:`datetime.datetime` object as unix epoch. :param default_now: If ``True``, the creation time (UTC) will be used as default. Defaults to ``False``. :type default_now: :class:`bool`
6259904e30dc7b76659a0c97
class LeaveJourneyView(LoginRequiredMixin, View): <NEW_LINE> <INDENT> return_to = "journeys:recommended" <NEW_LINE> def post(self, request, pk): <NEW_LINE> <INDENT> journey = get_object_or_404(Journey, pk=pk) <NEW_LINE> leave_from = request.POST.get("leave_from") <NEW_LINE> try: <NEW_LINE> <INDENT> journey.leave_passenger(request.user, leave_from=leave_from) <NEW_LINE> if leave_from == "one": <NEW_LINE> <INDENT> messages.success(request, _('Has dejado el viaje')) <NEW_LINE> <DEDENT> elif leave_from == "all": <NEW_LINE> <INDENT> messages.success(request, _('Has dejado todos los viajes')) <NEW_LINE> <DEDENT> <DEDENT> except NotAPassenger: <NEW_LINE> <INDENT> messages.success(request, _('No estás en este viaje')) <NEW_LINE> <DEDENT> return_to = request.POST.get("return_to", self.return_to) <NEW_LINE> return redirect(return_to)
View to handle the action of leaving a journey.
6259904e1f037a2d8b9e529d
class grubEntry: <NEW_LINE> <INDENT> def __init__(self, title): <NEW_LINE> <INDENT> self.title = title <NEW_LINE> self.commands = [] <NEW_LINE> <DEDENT> def listCommands(self): <NEW_LINE> <INDENT> return map(lambda x: x.key, self.commands) <NEW_LINE> <DEDENT> def setCommand(self, key, value, opts=[], append=False): <NEW_LINE> <INDENT> if not append: <NEW_LINE> <INDENT> self.unsetCommand(key) <NEW_LINE> <DEDENT> self.commands.append(grubCommand(key, opts, value)) <NEW_LINE> <DEDENT> def getCommand(self, key, only_last=True): <NEW_LINE> <INDENT> commands = filter(lambda x: x.key == key, self.commands) <NEW_LINE> if only_last: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return commands[-1] <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> return commands <NEW_LINE> <DEDENT> def unsetCommand(self, key): <NEW_LINE> <INDENT> self.commands = filter(lambda x: x.key != key, self.commands) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> conf = [] <NEW_LINE> conf.append("title %s" % self.title) <NEW_LINE> for command in self.commands: <NEW_LINE> <INDENT> conf.append(str(command)) <NEW_LINE> <DEDENT> return "\n".join(conf)
Grub menu entry
6259904e8e71fb1e983bcf28
class Auth(object): <NEW_LINE> <INDENT> def trigger(self, request): <NEW_LINE> <INDENT> raise NotImplemented() <NEW_LINE> <DEDENT> def __call__(self, request, *args, **kw): <NEW_LINE> <INDENT> raise NotImplemented()
An object with two significant methods, 'trigger' and 'run'. Using a similar object to this, plugins can register specific authentication logic, for example the GET param 'access_token' for OAuth. - trigger: Analyze the 'request' argument, return True if you think you can handle the request, otherwise return False - run: The authentication logic, set the request.user object to the user you intend to authenticate and return True, otherwise return False. If run() returns False, an HTTP 403 Forbidden error will be shown. You may also display custom errors, just raise them within the run() method.
6259904eb57a9660fecd2edf
@dataclass(frozen=True) <NEW_LINE> class not_stitched(Iterable[E]): <NEW_LINE> <INDENT> entities: Iterable[E] <NEW_LINE> def __iter__(self) -> Iterator[E]: <NEW_LINE> <INDENT> return (e for e in self.entities if not e.is_stitched)
An iterable of the entities in the argument iterable that are not stitched. This is an iterable, so it can be consumed repeatedly.
6259904e2ae34c7f260ac552
class Status(IntEnum): <NEW_LINE> <INDENT> EX_OK = 0 <NEW_LINE> EX_USAGE = 64 <NEW_LINE> EX_DATAERR = 65 <NEW_LINE> EX_NOINPUT = 66 <NEW_LINE> EX_NOUSER = 67 <NEW_LINE> EX_NOHOST = 68 <NEW_LINE> EX_UNAVAILABLE = 69 <NEW_LINE> EX_SOFTWARE = 70 <NEW_LINE> EX_OSERR = 71 <NEW_LINE> EX_OSFILE = 72 <NEW_LINE> EX_CANTCREAT = 73 <NEW_LINE> EX_IOERR = 74 <NEW_LINE> EX_TEMPFAIL = 75 <NEW_LINE> EX_PROTOCOL = 76 <NEW_LINE> EX_NOPERM = 77 <NEW_LINE> EX_CONFIG = 78 <NEW_LINE> EX_TIMEOUT = 79
Enumeration for the status values defined by SPAMD.
6259904e379a373c97d9a48e
class VowelerTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def test_first_case(self): <NEW_LINE> <INDENT> input = ["boy", "age"] <NEW_LINE> output = (["by", "age"], 1.5) <NEW_LINE> self.assertTrue(remove_and_average(input), output) <NEW_LINE> <DEDENT> def test_second_case(self): <NEW_LINE> <INDENT> input = ["boy", "age", "o", "aaaaaaaa"] <NEW_LINE> output = (["by", "age", "", "aaaaaaaa"], 3) <NEW_LINE> self.assertTrue(remove_and_average(input), output)
testing voweler challenge.
6259904ea79ad1619776b4e3
class HandlerClass: <NEW_LINE> <INDENT> def __init__(self, halcomp,builder,useropts): <NEW_LINE> <INDENT> self.halcomp = halcomp <NEW_LINE> self.builder = builder <NEW_LINE> self.nhits = 0
class with gladevcp callback handlers
6259904ed6c5a102081e3581
class Munge(Package): <NEW_LINE> <INDENT> homepage = "https://code.google.com/p/munge/" <NEW_LINE> url = "https://github.com/dun/munge/releases/download/munge-0.5.11/munge-0.5.11.tar.bz2" <NEW_LINE> version('0.5.11', 'bd8fca8d5f4c1fcbef1816482d49ee01', url='https://github.com/dun/munge/releases/download/munge-0.5.11/munge-0.5.11.tar.bz2') <NEW_LINE> depends_on('openssl') <NEW_LINE> depends_on('libgcrypt') <NEW_LINE> def install(self, spec, prefix): <NEW_LINE> <INDENT> os.makedirs(os.path.join(prefix, "lib/systemd/system")) <NEW_LINE> configure("--prefix=%s" % prefix) <NEW_LINE> make() <NEW_LINE> make("install")
MUNGE Uid 'N' Gid Emporium
6259904ebe383301e0254c7e
class PMBMultiReferentialConstraint(PMBConstraint): <NEW_LINE> <INDENT> constraintType = 'Multi Referential' <NEW_LINE> AddRigidObject = _RefFuncIndexWrapper(_AddMultiRef, 0) <NEW_LINE> GetRigidObject = _RefFuncIndexWrapper(_GetMultiRef, 0) <NEW_LINE> RemoveRigidObject = _RefFuncIndexWrapper(_RemoveMultiRef, 0) <NEW_LINE> AddParentObject = _RefFuncIndexWrapper(_AddMultiRef, 1) <NEW_LINE> GetParentObject = _RefFuncIndexWrapper(_GetMultiRef, 1) <NEW_LINE> RemoveParentObject = _RefFuncIndexWrapper(_RemoveMultiRef, 1) <NEW_LINE> def SetActiveReference(self, model): <NEW_LINE> <INDENT> raise NotImplementedError('This method is not yet completed') <NEW_LINE> <DEDENT> def GetActiveReference(self): <NEW_LINE> <INDENT> raise NotImplementedError('This method is not yet completed') <NEW_LINE> <DEDENT> def SetOffsetTranslation(self, model, vector): <NEW_LINE> <INDENT> if hasattr(model, 'Name'): <NEW_LINE> <INDENT> model = model.Name <NEW_LINE> <DEDENT> propertyName = '%s.Offset.Translation' % model <NEW_LINE> self.component.PropertyList.Find(propertyName).Data = vector <NEW_LINE> <DEDENT> def GetOffsetTranslation(self, model): <NEW_LINE> <INDENT> if hasattr(model, 'Name'): <NEW_LINE> <INDENT> model = model.Name <NEW_LINE> <DEDENT> propertyName = '%s.Offset.Translation' % model <NEW_LINE> return self.component.PropertyList.Find(propertyName).Data <NEW_LINE> <DEDENT> def SetOffsetRotation(self, model, vector): <NEW_LINE> <INDENT> if hasattr(model, 'Name'): <NEW_LINE> <INDENT> model = model.Name <NEW_LINE> <DEDENT> propertyName = '%s.Offset.Rotation' % model <NEW_LINE> self.component.PropertyList.Find(propertyName).Data = vector <NEW_LINE> <DEDENT> def GetOffsetRotation(self, model): <NEW_LINE> <INDENT> if hasattr(model, 'Name'): <NEW_LINE> <INDENT> model = model.Name <NEW_LINE> <DEDENT> propertyName = '%s.Offset.Rotation' % model <NEW_LINE> return self.component.PropertyList.Find(propertyName).Data
Multi referential constraint class
6259904e004d5f362081fa1a
class BaseRadar(Transmitter): <NEW_LINE> <INDENT> _count = 0 <NEW_LINE> def __init__(self, x, y): <NEW_LINE> <INDENT> self.x = x <NEW_LINE> self.y = y <NEW_LINE> self.no = BaseRadar._count <NEW_LINE> BaseRadar._count += 1
雷达类包括方法: 发送波形 接收波形 计算参数 上传数据库
6259904e0a366e3fb87dde49
class TaskCollectData(d6tflow.tasks.TaskCSVPandas): <NEW_LINE> <INDENT> do_collection = luigi.BoolParameter(default=True) <NEW_LINE> input_kwargs = luigi.DictParameter() <NEW_LINE> def run(self): <NEW_LINE> <INDENT> if self.do_collection: <NEW_LINE> <INDENT> from .input_collector import DataAccessor <NEW_LINE> housing = DataAccessor(**self.input_kwargs).load_housing_data() <NEW_LINE> self.save(housing) <NEW_LINE> <DEDENT> return housing
Task to collect input data.
6259904e71ff763f4b5e8c0b
class Runner: <NEW_LINE> <INDENT> def __init__(self, config, endpoints, reset_on_start=False, reset_on_shutdown=True): <NEW_LINE> <INDENT> self.reset_on_shutdown = reset_on_shutdown <NEW_LINE> self.start_coco(config, endpoints, reset_on_start) <NEW_LINE> time.sleep(1) <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> if self.reset_on_shutdown: <NEW_LINE> <INDENT> self.client("reset-state", silent=True) <NEW_LINE> <DEDENT> self.stop_coco() <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __exit__(self, type, value, traceback): <NEW_LINE> <INDENT> self.__del__() <NEW_LINE> <DEDENT> def client(self, command, data=[], silent=False): <NEW_LINE> <INDENT> cmd = CLIENT_ARGS + ["-c", self.configfile.name, command] + data <NEW_LINE> logger.debug("calling coco client: {}".format(cmd)) <NEW_LINE> try: <NEW_LINE> <INDENT> result = subprocess.check_output(cmd, encoding="utf-8") <NEW_LINE> <DEDENT> except subprocess.CalledProcessError as e: <NEW_LINE> <INDENT> print(f"coco client errored: {e}") <NEW_LINE> return None <NEW_LINE> <DEDENT> if not silent: <NEW_LINE> <INDENT> print(result) <NEW_LINE> <DEDENT> if result == "": <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> result = json.loads(result) <NEW_LINE> <DEDENT> except json.JSONDecodeError as err: <NEW_LINE> <INDENT> print(f"Failure parsing json returned by client: {err}.\n{result}") <NEW_LINE> return None <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def start_coco(self, config, endpoint_configs, reset): <NEW_LINE> <INDENT> CONFIG.update(config) <NEW_LINE> self.endpointdir = tempfile.TemporaryDirectory() <NEW_LINE> CONFIG["endpoint_dir"] = self.endpointdir.name <NEW_LINE> for name, endpoint_conf in endpoint_configs.items(): <NEW_LINE> <INDENT> with open( os.path.join(self.endpointdir.name, name + ".conf"), "w" ) as outfile: <NEW_LINE> <INDENT> json.dump(endpoint_conf, outfile) <NEW_LINE> <DEDENT> <DEDENT> self.configfile = tempfile.NamedTemporaryFile("w") <NEW_LINE> json.dump(CONFIG, self.configfile) <NEW_LINE> self.configfile.flush() <NEW_LINE> args = [] <NEW_LINE> if reset: <NEW_LINE> <INDENT> args.append("--reset") <NEW_LINE> <DEDENT> self.coco = subprocess.Popen([COCO, "-c", self.configfile.name, *args]) <NEW_LINE> <DEDENT> def stop_coco(self): <NEW_LINE> <INDENT> self.coco.terminate() <NEW_LINE> self.coco.communicate()
Coco Runner for unit tests.
6259904e29b78933be26aaf4
class pdfPrintout(wx.Printout): <NEW_LINE> <INDENT> def __init__(self, title, view): <NEW_LINE> <INDENT> wx.Printout.__init__(self, title) <NEW_LINE> self.view = view <NEW_LINE> <DEDENT> def HasPage(self, pageno): <NEW_LINE> <INDENT> if pageno <= self.view.numpages: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def GetPageInfo(self): <NEW_LINE> <INDENT> maxnum = self.view.numpages <NEW_LINE> return (1, maxnum, 1, maxnum) <NEW_LINE> <DEDENT> def OnPrintPage(self, page): <NEW_LINE> <INDENT> if not mupdf and self.view.UsePrintDirect: <NEW_LINE> <INDENT> self.PrintDirect(page) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.PrintViaBuffer(page) <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> def PrintDirect(self, page): <NEW_LINE> <INDENT> pageno = page - 1 <NEW_LINE> width = self.view.pagewidth <NEW_LINE> height = self.view.pageheight <NEW_LINE> self.FitThisSizeToPage(wx.Size(width, height)) <NEW_LINE> dc = self.GetDC() <NEW_LINE> gc = dcGraphicsContext.Create(dc, height, have_cairo) <NEW_LINE> self.view.pdfdoc.RenderPage(gc, pageno) <NEW_LINE> <DEDENT> def PrintViaBuffer(self, page): <NEW_LINE> <INDENT> sfac = 4.0 <NEW_LINE> pageno = page - 1 <NEW_LINE> dc = self.GetDC() <NEW_LINE> width = self.view.pagewidth*sfac <NEW_LINE> height = self.view.pageheight*sfac <NEW_LINE> self.FitThisSizeToPage(wx.Size(width, height)) <NEW_LINE> abuffer = wx.Bitmap(width, height) <NEW_LINE> mdc = wx.MemoryDC(abuffer) <NEW_LINE> gc = GraphicsContext.Create(mdc) <NEW_LINE> path = gc.CreatePath() <NEW_LINE> path.AddRectangle(0, 0, width, height) <NEW_LINE> gc.SetBrush(wx.WHITE_BRUSH) <NEW_LINE> gc.FillPath(path) <NEW_LINE> if mupdf: <NEW_LINE> <INDENT> self.view.pdfdoc.RenderPage(gc, pageno, sfac) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> gc.Translate(0, height) <NEW_LINE> gc.Scale(sfac, sfac) <NEW_LINE> self.view.pdfdoc.RenderPage(gc, pageno) <NEW_LINE> <DEDENT> dc.DrawBitmap(abuffer, 0, 0)
Class encapsulating the functionality of printing out the document. The methods below over-ride those of the base class and supply document-specific information to the printing framework that calls them internally.
6259904e0c0af96317c57792
class SnapshotModelCheckpoint(Callback): <NEW_LINE> <INDENT> def __init__(self, nb_epochs, nb_snapshots, fn_prefix, fold): <NEW_LINE> <INDENT> super(SnapshotModelCheckpoint, self).__init__() <NEW_LINE> self.check = nb_epochs // nb_snapshots <NEW_LINE> self.fn_prefix = fn_prefix <NEW_LINE> self.fold = fold <NEW_LINE> <DEDENT> def on_epoch_end(self, epoch, logs={}): <NEW_LINE> <INDENT> if epoch != 0 and (epoch + 1) % self.check == 0: <NEW_LINE> <INDENT> filepath = self.fn_prefix + "_{snap}_fold_{fold}.hdf5".format(snap=((epoch + 1) // self.check), fold=self.fold) <NEW_LINE> self.model.save_weights(filepath, overwrite=True)
Callback that saves the snapshot weights of the model. Saves the model weights on certain epochs (which can be considered the snapshot of the model at that epoch). Should be used with the cosine annealing learning rate schedule to save the weight just before learning rate is sharply increased. # Arguments: nb_epochs: total number of epochs that the model will be trained for. nb_snapshots: number of times the weights of the model will be saved. fn_prefix: prefix for the filename of the weights.
6259904e4e696a045264e852
class ViewsTestCase(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> user = User.objects.create(username="testuser") <NEW_LINE> self.client = APIClient() <NEW_LINE> self.client.force_authenticate(user=user) <NEW_LINE> self.bucketlist_data = {'name': 'Test Text Two2', 'owner': user.id} <NEW_LINE> self.response = self.client.post( reverse('create'), self.bucketlist_data, format="json") <NEW_LINE> <DEDENT> def test_api_can_create_a_bucketlist(self): <NEW_LINE> <INDENT> self.assertEqual(self.response.status_code, status.HTTP_201_CREATED) <NEW_LINE> <DEDENT> def test_authorization_is_enforced(self): <NEW_LINE> <INDENT> new_client = APIClient() <NEW_LINE> res = new_client.get('/bucketlists/', kwargs={'pk': 3}, format="json") <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED) <NEW_LINE> <DEDENT> def test_api_can_get_a_bucketlist(self): <NEW_LINE> <INDENT> bucketlist = Bucketlist.objects.get(id=1) <NEW_LINE> response = self.client.get( '/bucketlists/', kwargs={'pk': bucketlist.id}, format="json") <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_200_OK) <NEW_LINE> self.assertContains(response, bucketlist) <NEW_LINE> <DEDENT> def test_api_can_update_bucketlist(self): <NEW_LINE> <INDENT> bucketlist = Bucketlist.objects.get() <NEW_LINE> change_bucketlist = {'name': 'New Text1'} <NEW_LINE> res = self.client.put( reverse('details', kwargs={'pk': bucketlist.id}), change_bucketlist, format='json' ) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_200_OK) <NEW_LINE> <DEDENT> def test_api_can_delete_bucketlist(self): <NEW_LINE> <INDENT> bucketlist = Bucketlist.objects.get() <NEW_LINE> response = self.client.delete( reverse('details', kwargs={'pk': bucketlist.id}), format='json', follow=True) <NEW_LINE> self.assertEquals(response.status_code, status.HTTP_204_NO_CONTENT)
Test suite for the api views.
6259904e07d97122c4218108
class SelectMixin(ElementMixin): <NEW_LINE> <INDENT> def _get_selenium_select(self): <NEW_LINE> <INDENT> if self.exists(): <NEW_LINE> <INDENT> element = self.element() <NEW_LINE> if element.tag_name == u'select': <NEW_LINE> <INDENT> return SeleniumSelect(element) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def deselect_all(self): <NEW_LINE> <INDENT> select = self._get_selenium_select() <NEW_LINE> if select: <NEW_LINE> <INDENT> select.deselect_all() <NEW_LINE> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def deselect_by_index(self, option): <NEW_LINE> <INDENT> select = self._get_selenium_select() <NEW_LINE> option = to_int(option) <NEW_LINE> if select and isinstance(option, int): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> select.deselect_by_index(option) <NEW_LINE> return True <NEW_LINE> <DEDENT> except NoSuchElementException: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> def deselect_by_text(self, option): <NEW_LINE> <INDENT> select = self._get_selenium_select() <NEW_LINE> if select and isinstance(option, string_types): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> select.deselect_by_visible_text(option) <NEW_LINE> return True <NEW_LINE> <DEDENT> except NoSuchElementException: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> def deselect_by_value(self, option): <NEW_LINE> <INDENT> select = self._get_selenium_select() <NEW_LINE> if select and isinstance(option, string_types): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> select.deselect_by_value(option) <NEW_LINE> return True <NEW_LINE> <DEDENT> except NoSuchElementException: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> def options(self): <NEW_LINE> <INDENT> select = self._get_selenium_select() <NEW_LINE> options = [] <NEW_LINE> if select: <NEW_LINE> <INDENT> for option in select.options: <NEW_LINE> <INDENT> options.append(option.text.encode('ascii', 'ignore')) <NEW_LINE> <DEDENT> <DEDENT> return options <NEW_LINE> <DEDENT> def selected_first(self): <NEW_LINE> <INDENT> selected = self.selected_options() <NEW_LINE> return selected[0] if selected else None <NEW_LINE> <DEDENT> def selected_options(self): <NEW_LINE> <INDENT> select = self._get_selenium_select() <NEW_LINE> options = [] <NEW_LINE> if select: <NEW_LINE> <INDENT> options = [option.text.encode('ascii', 'ignore') for option in select.all_selected_options] <NEW_LINE> <DEDENT> return options <NEW_LINE> <DEDENT> def select_by_index(self, option): <NEW_LINE> <INDENT> select = self._get_selenium_select() <NEW_LINE> option = to_int(option) <NEW_LINE> if select and isinstance(option, int): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> select.select_by_index(option) <NEW_LINE> return True <NEW_LINE> <DEDENT> except NoSuchElementException: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> def select_by_text(self, option): <NEW_LINE> <INDENT> select = self._get_selenium_select() <NEW_LINE> if select and isinstance(option, string_types): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> select.select_by_visible_text(option) <NEW_LINE> return True <NEW_LINE> <DEDENT> except NoSuchElementException: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> def select_by_value(self, option): <NEW_LINE> <INDENT> select = self._get_selenium_select() <NEW_LINE> if select and isinstance(option, string_types): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> select.select_by_value(option) <NEW_LINE> return True <NEW_LINE> <DEDENT> except NoSuchElementException: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> return False
The SelectMixin implementation
6259904e6fece00bbaccce1e
class ProposeCommand(NewCommand): <NEW_LINE> <INDENT> pass
Propose a new ADR (same as 'new' command) propose {words* : Words in the title}
6259904e76d4e153a661dcaa
class OrgaViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> permission_classes = (IsAuthenticated,) <NEW_LINE> serializer_class = OrgaSerializer <NEW_LINE> pagination_class = None <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> return Orga.objects.all()
API endpoint that allows orgas to be viewed or edited.
6259904e462c4b4f79dbce64
class UniqueObject: <NEW_LINE> <INDENT> def __init__(self, name: str = None, unique_id: int = None): <NEW_LINE> <INDENT> self.unique_id = unique_id <NEW_LINE> self.name = name
Base class for all entities. It declares fields that every entity must have. Should be used only for subclassing, not for creating instances of this class
6259904e23849d37ff852522
class CartCollision(Exception): <NEW_LINE> <INDENT> def __init__(self, coordinates): <NEW_LINE> <INDENT> self.coordinates = coordinates
Raised when two carts collide
6259904e21a7993f00c673cd