code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class StateFormula(PathFormula): <NEW_LINE> <INDENT> __desc__ = 'CTL* state formula' <NEW_LINE> def is_a_state_formula(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def __init__(self, *phi): <NEW_LINE> <INDENT> self.wrap_subformulas(phi, sys.modules[self.__module__].Formula)
A class representing CTL* state formulas.
6259907c67a9b606de5477c5
class ParseRawTraj(ParseTraj): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> <DEDENT> def parse(self, input_path): <NEW_LINE> <INDENT> time_format = '%Y/%m/%d %H:%M:%S' <NEW_LINE> tid_to_remove = '[:/ ]' <NEW_LINE> with open(input_path, 'r') as f: <NEW_LINE> <INDENT> trajs = [] <NEW_LINE> pt_list = [] <NEW_LINE> for line in f.readlines(): <NEW_LINE> <INDENT> attrs = line.rstrip().split(',') <NEW_LINE> if attrs[0] == '#': <NEW_LINE> <INDENT> if len(pt_list) > 1: <NEW_LINE> <INDENT> traj = Trajectory(oid, tid, pt_list) <NEW_LINE> trajs.append(traj) <NEW_LINE> <DEDENT> oid = attrs[2] <NEW_LINE> tid = attrs[1] <NEW_LINE> pt_list = [] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> lat = float(attrs[1]) <NEW_LINE> lng = float(attrs[2]) <NEW_LINE> pt = STPoint(lat, lng, datetime.strptime(attrs[0], time_format)) <NEW_LINE> pt_list.append(pt) <NEW_LINE> <DEDENT> <DEDENT> if len(pt_list) > 1: <NEW_LINE> <INDENT> traj = Trajectory(oid, tid, pt_list) <NEW_LINE> trajs.append(traj) <NEW_LINE> <DEDENT> <DEDENT> return trajs
Parse original GPS points to trajectories list. No extra data preprocessing
6259907cd486a94d0ba2d9f6
class TestX8664Arch(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.Triton = TritonContext() <NEW_LINE> self.assertFalse(self.Triton.isArchitectureValid()) <NEW_LINE> self.Triton.setArchitecture(ARCH.X86_64) <NEW_LINE> self.assertTrue(self.Triton.isArchitectureValid()) <NEW_LINE> <DEDENT> def test_registers(self): <NEW_LINE> <INDENT> self.assertEqual(self.Triton.registers.rax.getName(), "rax") <NEW_LINE> self.assertEqual(self.Triton.registers.zmm1.getName(), "zmm1") <NEW_LINE> self.assertEqual(self.Triton.registers.xmm15.getName(), "xmm15") <NEW_LINE> <DEDENT> def test_register_bit_size(self): <NEW_LINE> <INDENT> self.assertEqual(self.Triton.getRegisterBitSize(), 64) <NEW_LINE> <DEDENT> def test_register_size(self): <NEW_LINE> <INDENT> self.assertEqual(self.Triton.getRegisterSize(), 8)
Testing the X8664 Architecture.
6259907c091ae3566870667d
class GlucosuriaForm(BaseForm): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = Glucosuria <NEW_LINE> fields = '__all__' <NEW_LINE> <DEDENT> control = forms.CharField(widget=forms.TextInput) <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(GlucosuriaForm, self).__init__(*args, **kwargs) <NEW_LINE> self.helper.layout = Fieldset(u'Registrar Administración de Insulina', *self.field_names)
Muestra un formulario que permite registrar :class:`Glucosuria`s a una :class:`Persona` durante una :class:`Admision`
6259907c32920d7e50bc7a81
class StreamNotBuiltException(Exception): <NEW_LINE> <INDENT> pass
@author starchmd An exception thrown when the stream is not built but other functions are called
6259907c4a966d76dd5f0925
class TestReferenceOpener(TestCaseWithTransport): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(TestReferenceOpener, self).setUp() <NEW_LINE> SafeBranchOpener.install_hook() <NEW_LINE> <DEDENT> def createBranchReference(self, url): <NEW_LINE> <INDENT> t = get_transport(self.get_url('.')) <NEW_LINE> t.mkdir('reference') <NEW_LINE> a_bzrdir = BzrDir.create(self.get_url('reference')) <NEW_LINE> branch_reference_format = BranchReferenceFormat() <NEW_LINE> branch_transport = a_bzrdir.get_branch_transport( branch_reference_format) <NEW_LINE> branch_transport.put_bytes('location', url) <NEW_LINE> branch_transport.put_bytes( 'format', branch_reference_format.get_format_string()) <NEW_LINE> return a_bzrdir.root_transport.base <NEW_LINE> <DEDENT> def testCreateBranchReference(self): <NEW_LINE> <INDENT> target_branch = self.make_branch('repo') <NEW_LINE> reference_url = self.createBranchReference(target_branch.base) <NEW_LINE> self.assertNotEqual(reference_url, target_branch.base) <NEW_LINE> opened_branch = bzrlib.branch.Branch.open(reference_url) <NEW_LINE> self.assertEqual(opened_branch.base, target_branch.base) <NEW_LINE> <DEDENT> def testFollowReferenceValue(self): <NEW_LINE> <INDENT> opener = SafeBranchOpener(BranchOpenPolicy()) <NEW_LINE> reference_value = 'http://example.com/branch' <NEW_LINE> reference_url = self.createBranchReference(reference_value) <NEW_LINE> self.assertEqual( reference_value, opener.followReference(reference_url)) <NEW_LINE> <DEDENT> def testFollowReferenceNone(self): <NEW_LINE> <INDENT> self.make_branch('repo') <NEW_LINE> branch_url = self.get_url('repo') <NEW_LINE> opener = SafeBranchOpener(BranchOpenPolicy()) <NEW_LINE> self.assertIs(None, opener.followReference(branch_url))
Feature tests for safe opening of branch references.
6259907c7d847024c075de1c
class ToTorchFormatTensor(object): <NEW_LINE> <INDENT> def __init__(self, div=True): <NEW_LINE> <INDENT> self.div = div <NEW_LINE> <DEDENT> def __call__(self, pic): <NEW_LINE> <INDENT> if isinstance(pic, np.ndarray): <NEW_LINE> <INDENT> img = torch.from_numpy(pic).permute(2, 0, 1).contiguous() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> img = torch.ByteTensor(torch.ByteStorage.from_buffer(pic.tobytes())) <NEW_LINE> img = img.view(pic.size[1], pic.size[0], len(pic.mode)) <NEW_LINE> img = img.transpose(0, 1).transpose(0, 2).contiguous() <NEW_LINE> <DEDENT> return img.float().div(255) if self.div else img.float()
Converts a PIL.Image (RGB) or numpy.ndarray (H x W x C) in the range [0, 255] to a torch.FloatTensor of shape (C x H x W) in the range [0.0, 1.0]
6259907c66673b3332c31e3e
class ZIPCodec(Codec): <NEW_LINE> <INDENT> def encode(self, data, *args, **kwargs): <NEW_LINE> <INDENT> import zlib <NEW_LINE> format = 'zip' <NEW_LINE> if len(data[0]): format += '_%s' % data[0] <NEW_LINE> return format, zlib.compress(data[1]) <NEW_LINE> <DEDENT> def decode(self, data, *args, **kwargs): <NEW_LINE> <INDENT> import zlib <NEW_LINE> if not data[0].startswith('zip'): <NEW_LINE> <INDENT> return data <NEW_LINE> <DEDENT> format = data[0].partition('_')[2] <NEW_LINE> return format, zlib.decompress(data[1])
A codec able to encode/decode to/from gzip format. It uses the :mod:`zlib` module Example:: >>> from taurus.core.util.codecs import CodecFactory >>> # first encode something >>> data = 100 * "Hello world\n" >>> cf = CodecFactory() >>> codec = cf.getCodec('zip') >>> format, encoded_data = codec.encode(("", data)) >>> print len(data), len(encoded_data) 1200, 31 >>> format, decoded_data = codec.decode((format, encoded_data)) >>> print decoded_data[20] 'Hello world\nHello wo'
6259907c442bda511e95da77
class linkedlist: <NEW_LINE> <INDENT> class _node: <NEW_LINE> <INDENT> __slots__ = "_element", "_next" <NEW_LINE> def __init__(self, element, next): <NEW_LINE> <INDENT> self._element = element <NEW_LINE> self._next = next <NEW_LINE> <DEDENT> <DEDENT> def __init__(self): <NEW_LINE> <INDENT> self._head=None <NEW_LINE> self._size=0 <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return self._size <NEW_LINE> <DEDENT> def is_empty(self): <NEW_LINE> <INDENT> return self._size==0 <NEW_LINE> <DEDENT> def push(self,e): <NEW_LINE> <INDENT> self._head=self._node(e,self._head) <NEW_LINE> self._size+=1 <NEW_LINE> <DEDENT> def top(self): <NEW_LINE> <INDENT> if self.is_empty(): <NEW_LINE> <INDENT> raise Empty('Stack is empty') <NEW_LINE> <DEDENT> return self._head._element <NEW_LINE> <DEDENT> def pop(self): <NEW_LINE> <INDENT> if self.is_empty(): <NEW_LINE> <INDENT> raise Empty("stack is empty") <NEW_LINE> <DEDENT> answer = self._head._element <NEW_LINE> self._head=self._head._next <NEW_LINE> self._size-=1 <NEW_LINE> return answer
LIFO stack implementation using a single linked list for storage
6259907c4527f215b58eb6c0
class ModificarLB(flask.views.MethodView): <NEW_LINE> <INDENT> @login_required <NEW_LINE> def post(self): <NEW_LINE> <INDENT> idLb=flask.request.form['idLB'] <NEW_LINE> descripcion=flask.request.form['descripcion'] <NEW_LINE> estado=flask.request.form['estado'] <NEW_LINE> sesion=Session() <NEW_LINE> l=sesion.query(LineaBase).filter(LineaBase.id==int(idLb)).first() <NEW_LINE> if l is None: <NEW_LINE> <INDENT> return "t, Linea Base no existe" <NEW_LINE> <DEDENT> if controlRol(str(l.idFase),'lb','administrar')==0: <NEW_LINE> <INDENT> return "t, No posee permiso para realizar esta accion" <NEW_LINE> <DEDENT> if estado!="abierta": <NEW_LINE> <INDENT> return "t,No puede modificarse una Linea Base " + estado <NEW_LINE> <DEDENT> lb=LineaBase(descripcion,estado) <NEW_LINE> lb.descripcion=lb.descripcion.strip() <NEW_LINE> lb.estado=lb.estado.strip() <NEW_LINE> idLb=idLb.strip() <NEW_LINE> lbc=LBControllerClass() <NEW_LINE> return lbc.controlarLB(lb, idLb)
Clase utilizada cuando se hace una peticion de modificacion de Linea Base al servidor. Los metodos get y post indican como debe comportarse la clase segun el tipo de peticion que se realizo
6259907c1f5feb6acb164638
class itkConstrainedValueDifferenceImageFilterIUC2IUC2IUC2(itkConstrainedValueDifferenceImageFilterIUC2IUC2IUC2_Superclass): <NEW_LINE> <INDENT> thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> Input1ConvertibleToDoubleCheck = _itkConstrainedValueDifferenceImageFilterPython.itkConstrainedValueDifferenceImageFilterIUC2IUC2IUC2_Input1ConvertibleToDoubleCheck <NEW_LINE> Input2ConvertibleToDoubleCheck = _itkConstrainedValueDifferenceImageFilterPython.itkConstrainedValueDifferenceImageFilterIUC2IUC2IUC2_Input2ConvertibleToDoubleCheck <NEW_LINE> DoubleConvertibleToOutputCheck = _itkConstrainedValueDifferenceImageFilterPython.itkConstrainedValueDifferenceImageFilterIUC2IUC2IUC2_DoubleConvertibleToOutputCheck <NEW_LINE> DoubleGreaterThanOutputCheck = _itkConstrainedValueDifferenceImageFilterPython.itkConstrainedValueDifferenceImageFilterIUC2IUC2IUC2_DoubleGreaterThanOutputCheck <NEW_LINE> def __New_orig__(): <NEW_LINE> <INDENT> return _itkConstrainedValueDifferenceImageFilterPython.itkConstrainedValueDifferenceImageFilterIUC2IUC2IUC2___New_orig__() <NEW_LINE> <DEDENT> __New_orig__ = staticmethod(__New_orig__) <NEW_LINE> __swig_destroy__ = _itkConstrainedValueDifferenceImageFilterPython.delete_itkConstrainedValueDifferenceImageFilterIUC2IUC2IUC2 <NEW_LINE> def cast(*args): <NEW_LINE> <INDENT> return _itkConstrainedValueDifferenceImageFilterPython.itkConstrainedValueDifferenceImageFilterIUC2IUC2IUC2_cast(*args) <NEW_LINE> <DEDENT> cast = staticmethod(cast) <NEW_LINE> def GetPointer(self): <NEW_LINE> <INDENT> return _itkConstrainedValueDifferenceImageFilterPython.itkConstrainedValueDifferenceImageFilterIUC2IUC2IUC2_GetPointer(self) <NEW_LINE> <DEDENT> def New(*args, **kargs): <NEW_LINE> <INDENT> obj = itkConstrainedValueDifferenceImageFilterIUC2IUC2IUC2.__New_orig__() <NEW_LINE> import itkTemplate <NEW_LINE> itkTemplate.New(obj, *args, **kargs) <NEW_LINE> return obj <NEW_LINE> <DEDENT> New = staticmethod(New)
Proxy of C++ itkConstrainedValueDifferenceImageFilterIUC2IUC2IUC2 class
6259907c009cb60464d02f7f
class ClassInfo(object): <NEW_LINE> <INDENT> def __init__(self, name, base, is_abstract, doc_string, properties, decodings): <NEW_LINE> <INDENT> for prp in properties: <NEW_LINE> <INDENT> prp.cls = self <NEW_LINE> <DEDENT> self.__all_decodings = None <NEW_LINE> self.__all_properties = None <NEW_LINE> self.__base = base <NEW_LINE> self.__circular_imports = [] <NEW_LINE> self.__decodings = sorted(decodings, key=lambda dc: dc.property_name) <NEW_LINE> self.__doc_string = doc_string if doc_string is not None else '' <NEW_LINE> self.__imports = [] <NEW_LINE> self.__is_abstract = is_abstract <NEW_LINE> self.__is_entity = False <NEW_LINE> self.__name = name <NEW_LINE> self.__package = None <NEW_LINE> self.__properties = sorted(properties, key=lambda p: p.name) <NEW_LINE> self.__is_entity = is_abstract == False and self.has_property('cim_info') <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self.__name <NEW_LINE> <DEDENT> @property <NEW_LINE> def base(self): <NEW_LINE> <INDENT> return self.__base <NEW_LINE> <DEDENT> @base.setter <NEW_LINE> def base(self, value): <NEW_LINE> <INDENT> self.__base = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_abstract(self): <NEW_LINE> <INDENT> return self.__is_abstract <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_entity(self): <NEW_LINE> <INDENT> return self.__is_entity <NEW_LINE> <DEDENT> @property <NEW_LINE> def properties(self): <NEW_LINE> <INDENT> return self.__properties <NEW_LINE> <DEDENT> @property <NEW_LINE> def all_properties(self): <NEW_LINE> <INDENT> if self.__all_properties is None: <NEW_LINE> <INDENT> self.__all_properties = list(self.properties) <NEW_LINE> if self.base is not None: <NEW_LINE> <INDENT> self.__all_properties += self.base.all_properties <NEW_LINE> <DEDENT> <DEDENT> return self.__all_properties <NEW_LINE> <DEDENT> @property <NEW_LINE> def imports(self): <NEW_LINE> <INDENT> return self.__imports <NEW_LINE> <DEDENT> @property <NEW_LINE> def circular_imports(self): <NEW_LINE> <INDENT> return self.__circular_imports <NEW_LINE> <DEDENT> @property <NEW_LINE> def doc_string(self): <NEW_LINE> <INDENT> return self.__doc_string <NEW_LINE> <DEDENT> @property <NEW_LINE> def decodings(self): <NEW_LINE> <INDENT> return self.__decodings <NEW_LINE> <DEDENT> @property <NEW_LINE> def all_decodings(self): <NEW_LINE> <INDENT> if self.__all_decodings is None: <NEW_LINE> <INDENT> self.__all_decodings = list(self.decodings) <NEW_LINE> if self.base is not None: <NEW_LINE> <INDENT> self.__all_decodings += self.base.all_decodings <NEW_LINE> <DEDENT> <DEDENT> return self.__all_decodings <NEW_LINE> <DEDENT> @property <NEW_LINE> def ontology(self): <NEW_LINE> <INDENT> return None if self.package is None else self.package.ontology <NEW_LINE> <DEDENT> @property <NEW_LINE> def package(self): <NEW_LINE> <INDENT> return self.__package <NEW_LINE> <DEDENT> @package.setter <NEW_LINE> def package(self, value): <NEW_LINE> <INDENT> self.__package = value <NEW_LINE> <DEDENT> def get_property_decodings(self, prp): <NEW_LINE> <INDENT> result = [] <NEW_LINE> for dc in [dc for dc in self.all_decodings if dc.property_name == prp.name]: <NEW_LINE> <INDENT> result.append(dc) <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def has_property(self, property_name): <NEW_LINE> <INDENT> for prp in self.properties: <NEW_LINE> <INDENT> if prp.name == property_name: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False
Represents a class within an ontology.
6259907cd268445f2663a87e
class _GetchUnix(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> import sys <NEW_LINE> import tty <NEW_LINE> <DEDENT> def __call__(self): <NEW_LINE> <INDENT> import sys <NEW_LINE> import tty <NEW_LINE> import termios <NEW_LINE> fd = sys.stdin.fileno() <NEW_LINE> old_settings = termios.tcgetattr(fd) <NEW_LINE> try: <NEW_LINE> <INDENT> tty.setraw(sys.stdin.fileno()) <NEW_LINE> ch = sys.stdin.read(1) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) <NEW_LINE> <DEDENT> return ch
Implementing a getch call to read a single character from stdin
6259907ce1aae11d1e7cf531
class Class(object): <NEW_LINE> <INDENT> def method(self): <NEW_LINE> <INDENT> pass
class documentation
6259907c91f36d47f2231bae
class LoopLimiter(ExplorationTechnique): <NEW_LINE> <INDENT> def __init__(self, count=5, discard_stash='spinning'): <NEW_LINE> <INDENT> super(LoopLimiter, self).__init__() <NEW_LINE> self.count = count <NEW_LINE> self.discard_stash = discard_stash <NEW_LINE> <DEDENT> def step(self, pg, stash, **kwargs): <NEW_LINE> <INDENT> pg = pg.step(stash=stash, **kwargs).move(stash, self.discard_stash, lambda path: path.detect_loops() >= self.count) <NEW_LINE> return pg
Limit the number of loops a path may go through. Paths that exceed the loop limit are moved to a discard stash. Note that this uses the default detect_loops method from Path, which approximates loop counts by counting the number of times each basic block is executed in a given stack frame.
6259907c4c3428357761bcfa
class ShibbolethRemoteUserMiddleware(RemoteUserMiddleware): <NEW_LINE> <INDENT> def process_request(self, request): <NEW_LINE> <INDENT> if not hasattr(request, 'user'): <NEW_LINE> <INDENT> raise ImproperlyConfigured( "The Django remote user auth middleware requires the" " authentication middleware to be installed. Edit your" " MIDDLEWARE_CLASSES setting to insert" " 'django.contrib.auth.middleware.AuthenticationMiddleware'" " before the RemoteUserMiddleware class.") <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> username = request.META[self.header] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if not username: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> is_authenticated = request.user.is_authenticated <NEW_LINE> if is_authenticated: <NEW_LINE> <INDENT> if request.user.username == self.clean_username(username, request): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> shib_meta, error = self.parse_attributes(request) <NEW_LINE> request.session['shib'] = shib_meta <NEW_LINE> if error: <NEW_LINE> <INDENT> raise ShibbolethValidationError("All required Shibboleth elements" " not found. %s" % shib_meta) <NEW_LINE> <DEDENT> user = auth.authenticate(request, remote_user=username, shib_meta=shib_meta) <NEW_LINE> if user: <NEW_LINE> <INDENT> request.user = user <NEW_LINE> auth.login(request, user) <NEW_LINE> if GROUP_ATTRIBUTES: <NEW_LINE> <INDENT> self.update_user_groups(request, user) <NEW_LINE> <DEDENT> self.make_profile(user, shib_meta) <NEW_LINE> self.setup_session(request) <NEW_LINE> <DEDENT> <DEDENT> def make_profile(self, user, shib_meta): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def setup_session(self, request): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def update_user_groups(self, request, user): <NEW_LINE> <INDENT> groups = self.parse_group_attributes(request) <NEW_LINE> for group in user.groups.all(): <NEW_LINE> <INDENT> if group.name not in groups: <NEW_LINE> <INDENT> group.user_set.remove(user) <NEW_LINE> <DEDENT> <DEDENT> for g in groups: <NEW_LINE> <INDENT> group, created = Group.objects.get_or_create(name=g) <NEW_LINE> group.user_set.add(user) <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def parse_attributes(request): <NEW_LINE> <INDENT> shib_attrs = {} <NEW_LINE> error = False <NEW_LINE> meta = request.META <NEW_LINE> for header, attr in list(SHIB_ATTRIBUTE_MAP.items()): <NEW_LINE> <INDENT> if len(attr) == 3: <NEW_LINE> <INDENT> required, name, attr_processor = attr <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> required, name = attr <NEW_LINE> attr_processor = lambda x: x <NEW_LINE> <DEDENT> value = meta.get(header, None) <NEW_LINE> if value: <NEW_LINE> <INDENT> shib_attrs[name] = attr_processor(value) <NEW_LINE> <DEDENT> elif required: <NEW_LINE> <INDENT> error = True <NEW_LINE> <DEDENT> <DEDENT> return shib_attrs, error <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def parse_group_attributes(request): <NEW_LINE> <INDENT> groups = [] <NEW_LINE> for attr in GROUP_ATTRIBUTES: <NEW_LINE> <INDENT> parsed_groups = re.split('|'.join(GROUP_DELIMITERS), request.META.get(attr, '')) <NEW_LINE> groups += filter(bool, parsed_groups) <NEW_LINE> <DEDENT> return groups
Authentication Middleware for use with Shibboleth. Uses the recommended pattern for remote authentication from: http://code.djangoproject.com/svn/django/tags/releases/1.3/django/contrib/auth/middleware.py
6259907c7d43ff2487428135
class Request(pydantic.BaseModel): <NEW_LINE> <INDENT> aclass: typing.Optional[ASSETCLASS] <NEW_LINE> asset: ASSET <NEW_LINE> key: str <NEW_LINE> amount: Decimal <NEW_LINE> nonce: pydantic.PositiveInt
Request model for endpoint POST https://api.kraken.com/0/private/WithdrawInfo Model Fields: ------------- aclass : str Default = currency (optional) asset : str enum Asset being withdrawn key : str Withdrawal key name, as set up on account amount : Decimal Amount to withdraw nonce : int Always increasing unsigned 64 bit integer
6259907cec188e330fdfa2e9
class default_resource(Resource): <NEW_LINE> <INDENT> pass
Default foreman resource
6259907c3317a56b869bf266
class ReverseAndRedirect(HttpResponseException): <NEW_LINE> <INDENT> def __init__(self, view_name, *args, **kwargs): <NEW_LINE> <INDENT> url = reverse(view_name, args=args, kwargs=kwargs) <NEW_LINE> self.http_response = HttpResponseRedirect(url)
A shortcut allowing to do a reverse, then redirect the user by raising an exception.
6259907c99fddb7c1ca63af8
class AssociateElasticIpRequest(JDCloudRequest): <NEW_LINE> <INDENT> def __init__(self, parameters, header=None, version="v1"): <NEW_LINE> <INDENT> super(AssociateElasticIpRequest, self).__init__( '/regions/{regionId}/loadBalancers/{loadBalancerId}:associateElasticIp', 'POST', header, version) <NEW_LINE> self.parameters = parameters
负载均衡绑定弹性公网IP
6259907ca05bb46b3848be49
class Reference: <NEW_LINE> <INDENT> _TYPES_TITLES = [('cover', __('Cover')), ('title-page', __('Title page')), ('toc', __('Table of Contents')), ('index', __('Index')), ('glossary', __('Glossary')), ('acknowledgements', __('Acknowledgements')), ('bibliography', __('Bibliography')), ('colophon', __('Colophon')), ('copyright-page', __('Copyright')), ('dedication', __('Dedication')), ('epigraph', __('Epigraph')), ('foreword', __('Foreword')), ('loi', __('List of illustrations')), ('lot', __('List of tables')), ('notes', __('Notes')), ('preface', __('Preface')), ('text', __('Main text'))] <NEW_LINE> TITLES = dict(_TYPES_TITLES) <NEW_LINE> TYPES = frozenset(TITLES) <NEW_LINE> ORDER = {t: i for i, (t, _) in enumerate(_TYPES_TITLES)} <NEW_LINE> def __init__(self, oeb, type, title, href): <NEW_LINE> <INDENT> self.oeb = oeb <NEW_LINE> if type.lower() in self.TYPES: <NEW_LINE> <INDENT> type = type.lower() <NEW_LINE> <DEDENT> elif type not in self.TYPES and not type.startswith('other.'): <NEW_LINE> <INDENT> type = 'other.' + type <NEW_LINE> <DEDENT> if not title and type in self.TITLES: <NEW_LINE> <INDENT> title = oeb.translate(self.TITLES[type]) <NEW_LINE> <DEDENT> self.type = type <NEW_LINE> self.title = title <NEW_LINE> self.href = urlnormalize(href) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'Reference(type=%r, title=%r, href=%r)' % (self.type, self.title, self.href) <NEW_LINE> <DEDENT> @property <NEW_LINE> def item(self): <NEW_LINE> <INDENT> path = urldefrag(self.href)[0] <NEW_LINE> hrefs = self.oeb.manifest.hrefs <NEW_LINE> return hrefs.get(path, None)
Reference to a standard book section. Provides the following instance data members: :attr:`type`: Reference type identifier, as chosen from the list allowed in the OPF 2.0 specification. :attr:`title`: Human-readable section title. :attr:`href`: Book-internal URL of the referenced section. May include a fragment identifier.
6259907c1b99ca4002290256
class RegisterView(View): <NEW_LINE> <INDENT> def get(self, request): <NEW_LINE> <INDENT> register_form = RegisterForm() <NEW_LINE> return render(request, 'register.html', {'register_form': register_form}) <NEW_LINE> <DEDENT> def post(self, request): <NEW_LINE> <INDENT> register_form = RegisterForm(request.POST) <NEW_LINE> if register_form.is_valid(): <NEW_LINE> <INDENT> username = request.POST.get('email', '') <NEW_LINE> password = request.POST.get('password', '') <NEW_LINE> if UserProfile.objects.filter(email=username): <NEW_LINE> <INDENT> return render(request, 'register.html', {'register_form': register_form, 'msg': '用户已经存在'}) <NEW_LINE> <DEDENT> user_profile = UserProfile() <NEW_LINE> user_profile.username = username <NEW_LINE> user_profile.email = username <NEW_LINE> pwd = make_password(password) <NEW_LINE> user_profile.password = pwd <NEW_LINE> user_profile.is_active = False <NEW_LINE> user_profile.save() <NEW_LINE> user_msg = UserMessage() <NEW_LINE> user_msg.user = request.user.id <NEW_LINE> user_msg.message = "欢迎注册" <NEW_LINE> user_msg.save() <NEW_LINE> send_register_email(username, 'register') <NEW_LINE> return render(request, 'login.html') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return render(request, 'register.html', '{}')
注册
6259907c3617ad0b5ee07b8f
class SeriesBook(models.Model): <NEW_LINE> <INDENT> book = models.ForeignKey(Book, on_delete=models.CASCADE, verbose_name=_('book_title')) <NEW_LINE> series = models.ForeignKey(Series, on_delete=models.CASCADE, verbose_name=_('series_name')) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> db_table = 'series_book' <NEW_LINE> verbose_name = 'series and book'
Series and Book Relational Model
6259907ce1aae11d1e7cf532
class Hamiltonian(object): <NEW_LINE> <INDENT> def __init__(self, H, eig=False, nstates=None, baths=None, units='au', convert=None): <NEW_LINE> <INDENT> const.hbar = const.get_hbar(units) <NEW_LINE> if nstates==None: <NEW_LINE> <INDENT> self.nstates = H.shape[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.nstates = nstates <NEW_LINE> <DEDENT> self.check_hermiticity(H) <NEW_LINE> self.ham = H <NEW_LINE> self.baths = baths <NEW_LINE> if self.baths != None: self.nbaths = len(self.baths) <NEW_LINE> if eig: <NEW_LINE> <INDENT> self.eigensystem() <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Hamiltonian class" <NEW_LINE> <DEDENT> @property <NEW_LINE> def Heig(self): <NEW_LINE> <INDENT> return np.diag(self.ev) <NEW_LINE> <DEDENT> def check_hermiticity(self, H): <NEW_LINE> <INDENT> if is_hermitian(H): <NEW_LINE> <INDENT> self.is_hermitian = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print_warning('Hamiltonian is not Hermitian') <NEW_LINE> <DEDENT> <DEDENT> def eigensystem(self): <NEW_LINE> <INDENT> self.ev,self.ek = np.linalg.eigh(self.ham) <NEW_LINE> self.ev = self.ev[:self.nstates] <NEW_LINE> self.compute_frequencies() <NEW_LINE> <DEDENT> def compute_frequencies(self): <NEW_LINE> <INDENT> self.omegas = np.array([[(self.ev[i]-self.ev[j]) for j in range(self.nstates)] for i in range(self.nstates)])/const.hbar <NEW_LINE> <DEDENT> def compute_unique_freqs(self): <NEW_LINE> <INDENT> self.frequencies = np.unique(self.omegas) <NEW_LINE> <DEDENT> def to_eigenbasis(self, op): <NEW_LINE> <INDENT> if is_vector(op): <NEW_LINE> <INDENT> return np.dot(dag(self.ek), op)[:self.nstates,:] <NEW_LINE> <DEDENT> elif is_matrix(op): <NEW_LINE> <INDENT> return np.dot(dag(self.ek), np.dot(op, self.ek))[:self.nstates,:self.nstates] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise AttributeError("Not a valid operator") <NEW_LINE> <DEDENT> <DEDENT> def from_eigenbasis(self, op, trunc=True): <NEW_LINE> <INDENT> if is_vector(op): <NEW_LINE> <INDENT> return np.dot(self.ek, op)[:self.nstates,:] <NEW_LINE> <DEDENT> elif is_matrix(op): <NEW_LINE> <INDENT> return np.dot(self.ek, np.dot(op, dag(self.ek)))[:self.nstates,:self.nstates] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise AttributeError("Not a valid operator") <NEW_LINE> <DEDENT> <DEDENT> def commutator(self, op, eig=True): <NEW_LINE> <INDENT> if eig: <NEW_LINE> <INDENT> return self.Heig@op - [email protected] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.ham@op - [email protected] <NEW_LINE> <DEDENT> <DEDENT> def thermal_dm(self): <NEW_LINE> <INDENT> if self.baths != None: <NEW_LINE> <INDENT> rho_eq = np.zeros((self.nstates,self.nstates), dtype=complex) <NEW_LINE> rho_eq += np.diag(np.exp(-self.ev/self.baths[0].kT)) <NEW_LINE> return rho_eq/np.trace(rho_eq) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise NotImplementedError("Bath must be initialized before calling")
Base Hamiltonian class.
6259907daad79263cf4301fc
class Notifier: <NEW_LINE> <INDENT> def __init__(self, lock): <NEW_LINE> <INDENT> self.observers = [] <NEW_LINE> self.lock = lock <NEW_LINE> <DEDENT> def clear(self): <NEW_LINE> <INDENT> self.observers = [] <NEW_LINE> <DEDENT> def add(self, observer): <NEW_LINE> <INDENT> self.observers.append(observer) <NEW_LINE> <DEDENT> def notify(self, key): <NEW_LINE> <INDENT> self.lock.acquire() <NEW_LINE> for observer in self.observers: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if observer.notify(key): <NEW_LINE> <INDENT> self.lock.release() <NEW_LINE> return True <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> self.lock.release() <NEW_LINE> return False
Class composed of PhraseHandlers. Each observer called when new key input is ready to be checked against phrase database. Notifier acquires a global lock while iterating observers. This prevents infinite loops when a value being "typed out" contains a phrase-key. i.e. we don't want the automated keyboard typing to be picked up by this app.
6259907d091ae35668706681
class Fibonacci_Sequence: <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def __nth_fibonacci(cls, n): <NEW_LINE> <INDENT> a = 0 <NEW_LINE> b = 1 <NEW_LINE> if n == 0: <NEW_LINE> <INDENT> return a <NEW_LINE> <DEDENT> elif n == 1: <NEW_LINE> <INDENT> return b <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for _ in range(2, n+1): <NEW_LINE> <INDENT> c = a + b <NEW_LINE> a = b <NEW_LINE> b = c <NEW_LINE> <DEDENT> return b <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def generate_fibonnaci_seq(cls, start, end): <NEW_LINE> <INDENT> sequence = [] <NEW_LINE> if start < 0: <NEW_LINE> <INDENT> raise IndexError <NEW_LINE> <DEDENT> elif start > end: <NEW_LINE> <INDENT> raise IndexError <NEW_LINE> <DEDENT> elif end > 100000: <NEW_LINE> <INDENT> raise IndexError <NEW_LINE> <DEDENT> elif end == 0: <NEW_LINE> <INDENT> return {'length': 0, 'sequence': []} <NEW_LINE> <DEDENT> elif end == 1: <NEW_LINE> <INDENT> return {'length': 0, 'sequence': [0]} <NEW_LINE> <DEDENT> if start > 0: <NEW_LINE> <INDENT> sequence.append(Fibonacci_Sequence.__nth_fibonacci(start)) <NEW_LINE> sequence.append(Fibonacci_Sequence.__nth_fibonacci(start+1)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sequence.append(0) <NEW_LINE> sequence.append(1) <NEW_LINE> <DEDENT> if end - start > 2: <NEW_LINE> <INDENT> for _ in range(start+2, end): <NEW_LINE> <INDENT> sequence.append(sequence[-1] + sequence[-2]) <NEW_LINE> <DEDENT> <DEDENT> result = { 'length': end - start, 'sequence': sequence } <NEW_LINE> return result
Fibonacci sequence generator class
6259907d656771135c48ad51
class HostAlreadyExists(Exception): <NEW_LINE> <INDENT> def __init__(self, name): <NEW_LINE> <INDENT> super(HostAlreadyExists, self).__init__() <NEW_LINE> self.name = name
The specified host already exists.
6259907d7c178a314d78e90c
class Restart(base.BaseCommand): <NEW_LINE> <INDENT> name = 'restart' <NEW_LINE> log_to_stdout = True <NEW_LINE> @utils.log_command_exception <NEW_LINE> def do(self): <NEW_LINE> <INDENT> conf_file = _get_running_conf() <NEW_LINE> if not conf_file: <NEW_LINE> <INDENT> LOG.info("No running agent found, please start a agent first.") <NEW_LINE> return 3 <NEW_LINE> <DEDENT> _stop() <NEW_LINE> return _start(conf_file)
Dell-EMC SNMP agent: Restart the running SNMP agent. usage: snmpagent-unity restart examples: snmpagent-unity restart
6259907da8370b77170f1e12
class TestAnalyticsModel(BaseAnalyticsSetup): <NEW_LINE> <INDENT> def test_analytics_model_can_create_report(self): <NEW_LINE> <INDENT> report = ReadsReport.objects.create(user=self.author, article=self.article) <NEW_LINE> self.assertEqual(report.article, self.article) <NEW_LINE> <DEDENT> def test_report_model_string_representation(self): <NEW_LINE> <INDENT> report = ReadsReport.objects.create(user=self.author, article=self.article) <NEW_LINE> rep = f'{report.article.slug} viewed by {report.user.username}: ' f'read entire article == {report.full_read}' <NEW_LINE> self.assertIn(str(rep), str(report))
Test the Analytics model functions and methods
6259907d7047854f46340df8
class Solution(object): <NEW_LINE> <INDENT> def __init__(self, num, cache): <NEW_LINE> <INDENT> divisor = least_divisor(num) <NEW_LINE> if divisor == num: <NEW_LINE> <INDENT> self.sequences = [(num)] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> quotient = num // divisor <NEW_LINE> sub_solution = cache[quotient]
Data structure specifically for this problem. Components: - traditional factorization - all the product-sum factorizations
6259907d283ffb24f3cf52e3
class SensitiveWordsDB(DBbase): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> <DEDENT> def get_sensitive_words_by_channel(self, channel_id): <NEW_LINE> <INDENT> sql = f'select sensitive_words from sms_sensitiveWords where is_active=1 and channel_id={channel_id};' <NEW_LINE> r = self.execute(sql, fetch=True) <NEW_LINE> return [i[0] for i in r] if r else [] <NEW_LINE> <DEDENT> def search_page(self, channel_id, limit=Page.sensitive_limit): <NEW_LINE> <INDENT> if channel_id is not None: <NEW_LINE> <INDENT> sql = f'select count(id) from sms_sensitiveWords where is_active=1 and channel_id={channel_id};' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sql = 'select count(id) from sms_sensitiveWords where is_active=1;' <NEW_LINE> <DEDENT> num = self.execute(sql, fetch=True) <NEW_LINE> num = num[0][0] if num else 0 <NEW_LINE> page_list = [i + 1 for i in range(int(num) // limit)] <NEW_LINE> page_list = page_list if page_list else [1] <NEW_LINE> if int(num) > limit and (int(num) % limit != 0): <NEW_LINE> <INDENT> page_list.append(page_list[-1] + 1) <NEW_LINE> <DEDENT> return page_list, int(num) <NEW_LINE> <DEDENT> def backstage_show_all_sensitive_words(self, channel_id, page, limit=Page.sensitive_limit): <NEW_LINE> <INDENT> if channel_id is not None: <NEW_LINE> <INDENT> sql = 'select id,sensitive_words,(select name from sms_channel where id=channel_id) as channel_name,' f'create_time from sms_sensitiveWords where is_active=1 and channel_id={channel_id} ' f'limit {page * limit if page else 0},{limit};' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sql = 'select id,sensitive_words,(select name from sms_channel where id=channel_id) as channel_name,' f'create_time from sms_sensitiveWords where is_active=1 limit {page * limit if page else 0},{limit};' <NEW_LINE> <DEDENT> r = self.execute(sql, fetch=True) <NEW_LINE> data = [] <NEW_LINE> for i in r: <NEW_LINE> <INDENT> if i: <NEW_LINE> <INDENT> data.append({ 'id': i[0], 'sensitive_word': i[1], 'channel_name': i[2], 'create_time': i[3].strftime('%Y-%m-%d %H:%M:%S'), }) <NEW_LINE> <DEDENT> <DEDENT> return data <NEW_LINE> <DEDENT> def backstage_create_sensitive_words(self, channel_id, sensitive): <NEW_LINE> <INDENT> for i in sensitive.split(','): <NEW_LINE> <INDENT> new_sensitive = escape_string(i) <NEW_LINE> if self.execute(f'select id from sms_sensitiveWords where channel_id={channel_id} and sensitive_words="{new_sensitive}";', fetch=True): <NEW_LINE> <INDENT> r = True <NEW_LINE> continue <NEW_LINE> <DEDENT> sql = f'insert into sms_sensitiveWords (channel_id,sensitive_words) values ({channel_id},"{new_sensitive}");' <NEW_LINE> r = self.execute(sql) <NEW_LINE> <DEDENT> self.commit() <NEW_LINE> return r <NEW_LINE> <DEDENT> def backstage_delete_sensitive_words(self, sensitive_id): <NEW_LINE> <INDENT> for i in sensitive_id.split(','): <NEW_LINE> <INDENT> sql = f'delete from sms_sensitiveWords where id={i};' <NEW_LINE> r = self.execute(sql) <NEW_LINE> <DEDENT> self.commit() <NEW_LINE> return r
发敏感词数据表管理
6259907d4527f215b58eb6c2
class SQLConnection: <NEW_LINE> <INDENT> def __init__(self,path): <NEW_LINE> <INDENT> self.path = path <NEW_LINE> self.db = None <NEW_LINE> <DEDENT> def open_database(self): <NEW_LINE> <INDENT> if self.db: <NEW_LINE> <INDENT> self.close_database() <NEW_LINE> <DEDENT> self.db = QSqlDatabase.addDatabase("QSQLITE") <NEW_LINE> self.db.setDatabaseName(self.path) <NEW_LINE> opened_ok = self.db.open() <NEW_LINE> return opened_ok <NEW_LINE> <DEDENT> def close_database(self): <NEW_LINE> <INDENT> if self.db: <NEW_LINE> <INDENT> self.db.close() <NEW_LINE> QSqlDatabase.removeDatabase("conn") <NEW_LINE> closed = self.db.open() <NEW_LINE> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def closeEvent(self,event): <NEW_LINE> <INDENT> self.close_database() <NEW_LINE> <DEDENT> def show_all_items(self): <NEW_LINE> <INDENT> query = QSqlQuery() <NEW_LINE> query.prepare(""" SELECT * FROM PrepItems""") <NEW_LINE> query.exec_() <NEW_LINE> return query <NEW_LINE> <DEDENT> def find_products_by_number(self,values): <NEW_LINE> <INDENT> query = QSqlQuery() <NEW_LINE> query.prepare(""" SELECT * FROM PrepItems WHERE PrepItemID =? """) <NEW_LINE> query.addBindValue(values[0]) <NEW_LINE> query.exec_() <NEW_LINE> return query
Handles the conncetion to the SQL database
6259907d5fdd1c0f98e5f9c3
class GoatDetector(Subject): <NEW_LINE> <INDENT> def detect(self, line): <NEW_LINE> <INDENT> if line.find('goat') >= 0: <NEW_LINE> <INDENT> self.notifyObservers('goats detected')
This class notifies its observers if a string contains the word 'goat'.
6259907df548e778e596cfd5
class ChangeTimeoutOnTimeoutHandler(ActionIndependentDNSResponseHandler): <NEW_LINE> <INDENT> def __init__(self, timeout, timeouts): <NEW_LINE> <INDENT> self._timeout = timeout <NEW_LINE> self._timeouts = timeouts <NEW_LINE> <DEDENT> def handle(self, response_wire, response, response_time): <NEW_LINE> <INDENT> timeouts = self._get_num_timeouts(response) <NEW_LINE> if isinstance(response, dns.exception.Timeout) and timeouts == self._timeouts: <NEW_LINE> <INDENT> self._params['timeout'] = self._timeout
Modify timeout value when a certain number of timeouts is reached.
6259907d7b180e01f3e49d87
class Singleton(object): <NEW_LINE> <INDENT> def __new__(cls, *args, **kwds): <NEW_LINE> <INDENT> it = cls.__dict__.get("__it__") <NEW_LINE> if it is not None: <NEW_LINE> <INDENT> return it <NEW_LINE> <DEDENT> cls.__it__ = it = object.__new__(cls) <NEW_LINE> it.init(*args, **kwds) <NEW_LINE> return it <NEW_LINE> <DEDENT> def init(self, *args, **kwds): <NEW_LINE> <INDENT> pass
From Brian Bruggeman's answer here http://stackoverflow.com/questions/31875/is-there-a-simple-elegant-way-to -define-singletons-in-python
6259907d7d43ff2487428137
class Settings(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(Settings, self).__init__() <NEW_LINE> self._setup(global_settings) <NEW_LINE> user_settings = os.environ.get(ENVIRONMENT_VARIABLE, None) <NEW_LINE> if user_settings: <NEW_LINE> <INDENT> user_settings = importlib.import_module(user_settings) <NEW_LINE> self._setup(user_settings) <NEW_LINE> <DEDENT> self._create_database_managers() <NEW_LINE> <DEDENT> def _setup(self, settings): <NEW_LINE> <INDENT> for setting in dir(settings): <NEW_LINE> <INDENT> if setting.isupper(): <NEW_LINE> <INDENT> setattr(self, setting, getattr(settings, setting)) <NEW_LINE> <DEDENT> <DEDENT> self._wrapped = self <NEW_LINE> <DEDENT> def _create_database_managers(self): <NEW_LINE> <INDENT> if not self.USE_ORM_ENGINE: <NEW_LINE> <INDENT> for name, db_settings in self.DATABASES.items(): <NEW_LINE> <INDENT> backend = db_settings['backend'] <NEW_LINE> init_kwargs = ('name', 'user', 'password', 'host', 'port') <NEW_LINE> kwargs = { key: db_settings[key] for key in db_settings if key in init_kwargs } <NEW_LINE> managers_module = importlib.import_module( backend + '.managers' ) <NEW_LINE> manager_cls = db_settings.get('manager') or 'SQLiteManager' <NEW_LINE> if type(manager_cls) is str: <NEW_LINE> <INDENT> manager_instance = getattr( managers_module, manager_cls )(**kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> manager_instance = manager_cls <NEW_LINE> <DEDENT> db_settings['manager'] = manager_instance
Settings class of application.
6259907d656771135c48ad52
class Building(Location): <NEW_LINE> <INDENT> __tablename__ = _TN <NEW_LINE> __mapper_args__ = {'polymorphic_identity': _TN} <NEW_LINE> valid_parents = [City, Campus] <NEW_LINE> id = Column(ForeignKey(Location.id, ondelete='CASCADE'), primary_key=True) <NEW_LINE> address = Column(String(255), nullable=False) <NEW_LINE> next_rackid = Column(Integer, nullable=False, default=2) <NEW_LINE> netdev_rack = Column(Boolean, nullable=False, default=True) <NEW_LINE> __table_args__ = ({'info': {'unique_fields': ['name']}},)
Building is a subtype of location
6259907dec188e330fdfa2ed
class TestSampleSimilarityResult(BaseTestCase): <NEW_LINE> <INDENT> def test_add_sample_similarity(self): <NEW_LINE> <INDENT> sample_similarity_result = SampleSimilarityResult(categories=CATEGORIES, tools=TOOLS, data_records=DATA_RECORDS) <NEW_LINE> wrapper = AnalysisResultWrapper(data=sample_similarity_result).save() <NEW_LINE> result = AnalysisResultMeta(sample_similarity=wrapper).save() <NEW_LINE> self.assertTrue(result.id) <NEW_LINE> self.assertTrue(result.sample_similarity) <NEW_LINE> <DEDENT> def test_add_missing_category(self): <NEW_LINE> <INDENT> categories = { 'city': ['Montevideo', 'Sacramento'], } <NEW_LINE> data_records = [{ 'SampleID': 'MetaSUB_Pilot__01_cZ__unknown__seq1end', }] <NEW_LINE> sample_similarity_result = SampleSimilarityResult(categories=categories, tools={}, data_records=data_records) <NEW_LINE> wrapper = AnalysisResultWrapper(data=sample_similarity_result) <NEW_LINE> self.assertRaises(ValidationError, wrapper.save) <NEW_LINE> <DEDENT> def test_add_malformed_tool(self): <NEW_LINE> <INDENT> tools = { 'metaphlan2': { 'x_label': 'metaphlan2 tsne x', } } <NEW_LINE> data_records = [{ 'SampleID': 'MetaSUB_Pilot__01_cZ__unknown__seq1end', 'metaphlan2_x': 0.15631940943278633, }] <NEW_LINE> sample_similarity_result = SampleSimilarityResult(categories={}, tools=tools, data_records=data_records) <NEW_LINE> wrapper = AnalysisResultWrapper(data=sample_similarity_result) <NEW_LINE> self.assertRaises(ValidationError, wrapper.save) <NEW_LINE> <DEDENT> def test_add_missing_tool_x_value(self): <NEW_LINE> <INDENT> tools = { 'metaphlan2': { 'x_label': 'metaphlan2 tsne x', 'y_label': 'metaphlan2 tsne y' } } <NEW_LINE> data_records = [{ 'SampleID': 'MetaSUB_Pilot__01_cZ__unknown__seq1end', 'metaphlan2_y': 0.15631940943278633, }] <NEW_LINE> sample_similarity_result = SampleSimilarityResult(categories={}, tools=tools, data_records=data_records) <NEW_LINE> wrapper = AnalysisResultWrapper(data=sample_similarity_result) <NEW_LINE> self.assertRaises(ValidationError, wrapper.save) <NEW_LINE> <DEDENT> def test_add_missing_tool_y_value(self): <NEW_LINE> <INDENT> tools = { 'metaphlan2': { 'x_label': 'metaphlan2 tsne x', 'y_label': 'metaphlan2 tsne y' } } <NEW_LINE> data_records = [{ 'SampleID': 'MetaSUB_Pilot__01_cZ__unknown__seq1end', 'metaphlan2_x': 0.15631940943278633, }] <NEW_LINE> sample_similarity_result = SampleSimilarityResult(categories={}, tools=tools, data_records=data_records) <NEW_LINE> wrapper = AnalysisResultWrapper(data=sample_similarity_result) <NEW_LINE> self.assertRaises(ValidationError, wrapper.save)
Test suite for Sample Similarity model.
6259907d32920d7e50bc7a87
class UserProfile(AbstractBaseUser, PermissionsMixin): <NEW_LINE> <INDENT> email = models.EmailField(max_length=255, unique=True) <NEW_LINE> name = models.CharField(max_length=255) <NEW_LINE> is_active = models.BooleanField(default=True) <NEW_LINE> is_staff = models.BooleanField(default=False) <NEW_LINE> objects = UserProfileManager() <NEW_LINE> USERNAME_FIELD = 'email' <NEW_LINE> REQUIRED_FIELDS = ['name'] <NEW_LINE> def get_full_name(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def get_short_name(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.email)
Database model for users in the system
6259907dbe7bc26dc9252b78
class BaseRenderer(object): <NEW_LINE> <INDENT> media_type = None <NEW_LINE> format = None <NEW_LINE> charset = 'utf-8' <NEW_LINE> def render(self, data, accepted_media_type=None, renderer_context=None): <NEW_LINE> <INDENT> raise NotImplemented('Renderer class requires .render() to be implemented')
All renderers should extend this class, setting the `media_type` and `format` attributes, and override the `.render()` method.
6259907d71ff763f4b5e91f1
class ZionConfigHelper: <NEW_LINE> <INDENT> def __init__(self, config_file, host): <NEW_LINE> <INDENT> self.host=host <NEW_LINE> with open(config_file) as config_file: <NEW_LINE> <INDENT> self.zion_conf = json.load(config_file) <NEW_LINE> <DEDENT> <DEDENT> def get_conf(self, key): <NEW_LINE> <INDENT> return self.zion_conf['shared_conf'][key] <NEW_LINE> <DEDENT> def get_host_conf(self, key): <NEW_LINE> <INDENT> return self.zion_conf['host_conf'][self.host][key]
This helper class will return shared config or config for the current host. The config file should be a json document with this shape: { "shared_conf": { "key": "value" }, "host_conf": { "env.host": { "key": "value" } } }
6259907d55399d3f05627f59
class ServerException(Exception): <NEW_LINE> <INDENT> pass
inner server error
6259907d1b99ca4002290258
@pulumi.output_type <NEW_LINE> class GetGroupResult: <NEW_LINE> <INDENT> def __init__(__self__, arn=None, group_id=None, group_name=None, id=None, path=None, users=None): <NEW_LINE> <INDENT> if arn and not isinstance(arn, str): <NEW_LINE> <INDENT> raise TypeError("Expected argument 'arn' to be a str") <NEW_LINE> <DEDENT> pulumi.set(__self__, "arn", arn) <NEW_LINE> if group_id and not isinstance(group_id, str): <NEW_LINE> <INDENT> raise TypeError("Expected argument 'group_id' to be a str") <NEW_LINE> <DEDENT> pulumi.set(__self__, "group_id", group_id) <NEW_LINE> if group_name and not isinstance(group_name, str): <NEW_LINE> <INDENT> raise TypeError("Expected argument 'group_name' to be a str") <NEW_LINE> <DEDENT> pulumi.set(__self__, "group_name", group_name) <NEW_LINE> if id and not isinstance(id, str): <NEW_LINE> <INDENT> raise TypeError("Expected argument 'id' to be a str") <NEW_LINE> <DEDENT> pulumi.set(__self__, "id", id) <NEW_LINE> if path and not isinstance(path, str): <NEW_LINE> <INDENT> raise TypeError("Expected argument 'path' to be a str") <NEW_LINE> <DEDENT> pulumi.set(__self__, "path", path) <NEW_LINE> if users and not isinstance(users, list): <NEW_LINE> <INDENT> raise TypeError("Expected argument 'users' to be a list") <NEW_LINE> <DEDENT> pulumi.set(__self__, "users", users) <NEW_LINE> <DEDENT> @property <NEW_LINE> @pulumi.getter <NEW_LINE> def arn(self) -> str: <NEW_LINE> <INDENT> return pulumi.get(self, "arn") <NEW_LINE> <DEDENT> @property <NEW_LINE> @pulumi.getter(name="groupId") <NEW_LINE> def group_id(self) -> str: <NEW_LINE> <INDENT> return pulumi.get(self, "group_id") <NEW_LINE> <DEDENT> @property <NEW_LINE> @pulumi.getter(name="groupName") <NEW_LINE> def group_name(self) -> str: <NEW_LINE> <INDENT> return pulumi.get(self, "group_name") <NEW_LINE> <DEDENT> @property <NEW_LINE> @pulumi.getter <NEW_LINE> def id(self) -> str: <NEW_LINE> <INDENT> return pulumi.get(self, "id") <NEW_LINE> <DEDENT> @property <NEW_LINE> @pulumi.getter <NEW_LINE> def path(self) -> str: <NEW_LINE> <INDENT> return pulumi.get(self, "path") <NEW_LINE> <DEDENT> @property <NEW_LINE> @pulumi.getter <NEW_LINE> def users(self) -> Sequence['outputs.GetGroupUserResult']: <NEW_LINE> <INDENT> return pulumi.get(self, "users")
A collection of values returned by getGroup.
6259907d67a9b606de5477c9
class GameHistoryForm(messages.Message): <NEW_LINE> <INDENT> user_name = messages.StringField(1, required=True) <NEW_LINE> history = messages.MessageField(GameRoundForm, 2, repeated=True)
Returns a history of rounds played
6259907d76e4537e8c3f0fc5
class ContainsKeyValueTest(unittest.TestCase): <NEW_LINE> <INDENT> def testValidPair(self): <NEW_LINE> <INDENT> self.assertTrue(mox.ContainsKeyValue("key", 1) == {"key": 1}) <NEW_LINE> <DEDENT> def testInvalidValue(self): <NEW_LINE> <INDENT> self.assertFalse(mox.ContainsKeyValue("key", 1) == {"key": 2}) <NEW_LINE> <DEDENT> def testInvalidKey(self): <NEW_LINE> <INDENT> self.assertFalse(mox.ContainsKeyValue("qux", 1) == {"key": 2})
Test ContainsKeyValue correctly identifies key/value pairs in a dict.
6259907d7d43ff2487428138
@register <NEW_LINE> class ContinueArguments(BaseSchema): <NEW_LINE> <INDENT> __props__ = { "threadId": { "type": "integer", "description": "Continue execution for the specified thread (if possible).\nIf the backend cannot continue on a single thread but will continue on all threads, it should set the 'allThreadsContinued' attribute in the response to true." } } <NEW_LINE> __refs__ = set() <NEW_LINE> __slots__ = list(__props__.keys()) + ['kwargs'] <NEW_LINE> def __init__(self, threadId, **kwargs): <NEW_LINE> <INDENT> self.threadId = threadId <NEW_LINE> self.kwargs = kwargs <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> dct = { 'threadId': self.threadId, } <NEW_LINE> dct.update(self.kwargs) <NEW_LINE> return dct
Arguments for 'continue' request. Note: automatically generated code. Do not edit manually.
6259907d97e22403b383c947
class product(object): <NEW_LINE> <INDENT> def __init__(self, name, price, quantity): <NEW_LINE> <INDENT> self.id = id(self) <NEW_LINE> self.name = name <NEW_LINE> self.price = price <NEW_LINE> self.quantity = quantity
A class to represent a product ..... Attributes ----------- id : This is created automatically using in-built function id(), which creates unique id for each object name : name of the product price(only positive integer) : price of the product in dollars quantity(only positive integer) : indicates the quantity of a product
6259907d3317a56b869bf269
class HighScoreWindow(MainWindow): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> score = highscores.HighScoreManager() <NEW_LINE> highestdata = score.get_sorted_data()[0] <NEW_LINE> highestgrid = highestdata['grid'] <NEW_LINE> highestname = highestdata['name'] <NEW_LINE> highestscore = highestdata['score'] <NEW_LINE> game = RegularGame.deserialize(highestgrid) <NEW_LINE> data = score.get_sorted_data() <NEW_LINE> name_list = [] <NEW_LINE> score_list = [] <NEW_LINE> for i in range(len(data)): <NEW_LINE> <INDENT> name_list.append(data[i]['name']) <NEW_LINE> score_list.append(str(data[i]['score'])) <NEW_LINE> <DEDENT> print(name_list) <NEW_LINE> score_window = tk.Toplevel() <NEW_LINE> score_window.title("High Scores :: Lolo") <NEW_LINE> bestplayer = tk.Label(score_window, text="Best Player: {} with {} points!".format(highestname, highestscore)) <NEW_LINE> bestplayer.pack(side=tk.TOP) <NEW_LINE> sw = BaseLoloApp(score_window, game) <NEW_LINE> sw._grid_view.off('select', sw.activate) <NEW_LINE> leaderboard = tk.Label(score_window, text="Leaderboard") <NEW_LINE> leaderboard.pack(side=tk.TOP) <NEW_LINE> name_frame = tk.Frame(score_window) <NEW_LINE> name_frame.pack(side=tk.LEFT) <NEW_LINE> score_frame = tk.Frame(score_window) <NEW_LINE> score_frame.pack(side=tk.RIGHT) <NEW_LINE> for text in name_list: <NEW_LINE> <INDENT> tk.Label(name_frame, text=text).pack(side=tk.TOP, anchor=tk.W) <NEW_LINE> <DEDENT> for score in score_list: <NEW_LINE> <INDENT> tk.Label(score_frame, text=score).pack(side=tk.TOP, anchor=tk.E)
High Score Screen.
6259907d56ac1b37e6303a06
class GetSingleStudentTest(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.student2 = Student.objects.create( first_name='first_name3', surname='surname3', last_name='last_name3', date_of_birth=datetime.date(month=3, year=1993, day=3), grade=3 ) <NEW_LINE> self.student4 = Student.objects.create( first_name='first_name5', surname='surname5', last_name='last_name5', date_of_birth=datetime.date(month=5, year=1995, day=5), grade=5 ) <NEW_LINE> <DEDENT> def test_get_valid_single_experiment(self): <NEW_LINE> <INDENT> response = client.get( reverse('records_endpoint', kwargs={'pk': self.student2.pk})) <NEW_LINE> student2 = Student.objects.get(pk=self.student2.pk) <NEW_LINE> serializer = StudentDetailSerializer(student2) <NEW_LINE> self.assertEqual(response.data, serializer.data) <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_200_OK) <NEW_LINE> <DEDENT> def test_get_invalid_single_experiment(self): <NEW_LINE> <INDENT> response = client.get( reverse('records_endpoint', kwargs={'pk': 6969})) <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
Test case for GET single record of Student
6259907d4f6381625f19a1d1
class LoggersError(ODfuzzException): <NEW_LINE> <INDENT> pass
An error occurred while creating directories.
6259907d7cff6e4e811b7487
class StdOutPrinter(IO): <NEW_LINE> <INDENT> async def _read(self, length=1): <NEW_LINE> <INDENT> await curio.sleep(0) <NEW_LINE> return bytearray([0]) <NEW_LINE> <DEDENT> async def _write(self, data): <NEW_LINE> <INDENT> data = data.decode(self._encoding) <NEW_LINE> logger.info(f"{type(self).__name__}: {data}") <NEW_LINE> await curio.sleep(0) <NEW_LINE> return len(data)
IO-Class for StdOut
6259907d442bda511e95da7b
class DownloadStats(base.ScriptBaseWithConfig): <NEW_LINE> <INDENT> ARGS_HELP = "" <NEW_LINE> VERSION = '1.0' <NEW_LINE> FIELDS = ('is_active', 'left_bytes', 'size_bytes', 'down.rate', 'priority') <NEW_LINE> MIN_STALLED_RATE = 5 * 1024 <NEW_LINE> STALLED_PERCENT = 10 <NEW_LINE> def add_options(self): <NEW_LINE> <INDENT> super(DownloadStats, self).add_options() <NEW_LINE> <DEDENT> def mainloop(self): <NEW_LINE> <INDENT> proxy = config.engine.open() <NEW_LINE> all_items = list(config.engine.multicall("incomplete", self.FIELDS)) <NEW_LINE> pending = [d for d in all_items if not d.is_active and d.priority > 0] <NEW_LINE> print("Queued items: ", fmt.human_size(sum(d.size_bytes for d in pending)), 'in', len(pending), 'item(s)', '[{} free]'.format(fmt.human_size(disk_free(proxy.directory.default())).strip())) <NEW_LINE> items = [d for d in all_items if d.is_active] <NEW_LINE> if not items: <NEW_LINE> <INDENT> print("No active downloads!") <NEW_LINE> return <NEW_LINE> <DEDENT> good_rates = [d.down_rate for d in items if d.down_rate > self.MIN_STALLED_RATE] <NEW_LINE> stalled_rate = max( self.MIN_STALLED_RATE, self.STALLED_PERCENT / 100 * sum(good_rates) / len(good_rates) if good_rates else 0) <NEW_LINE> stalled_count = sum(d.down_rate < stalled_rate for d in items) <NEW_LINE> global_down_rate = proxy.throttle.global_down.rate() <NEW_LINE> total_size = sum(d.size_bytes for d in items) <NEW_LINE> total_left = sum(d.left_bytes for d in items) <NEW_LINE> eta_list = [0] <NEW_LINE> if stalled_count < len(items): <NEW_LINE> <INDENT> eta_list = [d.left_bytes / d.down_rate for d in items if d.down_rate >= stalled_rate] <NEW_LINE> <DEDENT> eta_max = total_left / (global_down_rate or 1) <NEW_LINE> stalled_info = ', {} stalled below {}/s'.format( stalled_count, fmt.human_size(stalled_rate).strip()) if stalled_count else '' <NEW_LINE> print("Size left to download: ", fmt.human_size(total_left), 'of', fmt.human_size(total_size).strip()) <NEW_LINE> print("Overall download speed:", fmt.human_size(global_down_rate) + '/s') <NEW_LINE> print("ETA (min → max): ", fmt_duration(min(eta_list)), '→', fmt_duration(eta_max), '…', fmt_duration(max(eta_list)), '[{} item(s){}]'.format(len(items), stalled_info), )
Show stats about currently active & pending downloads.
6259907d92d797404e389880
class DirectoryGalaxyOptionManager(object): <NEW_LINE> <INDENT> def __init__(self, app, conf_dir=None, conf_file_name=OPTIONS_FILE_NAME): <NEW_LINE> <INDENT> self.app = app <NEW_LINE> if not conf_dir: <NEW_LINE> <INDENT> conf_dir = app.ud["galaxy_conf_dir"] <NEW_LINE> <DEDENT> self.conf_dir = conf_dir <NEW_LINE> self.conf_file_name = conf_file_name <NEW_LINE> <DEDENT> def setup(self): <NEW_LINE> <INDENT> self.__initialize_galaxy_config_dir() <NEW_LINE> return self.conf_dir <NEW_LINE> <DEDENT> def __initialize_galaxy_config_dir(self): <NEW_LINE> <INDENT> conf_dir = self.conf_dir <NEW_LINE> if not exists(conf_dir): <NEW_LINE> <INDENT> makedirs(conf_dir) <NEW_LINE> defaults_destination = join(conf_dir, "010_%s" % self.conf_file_name) <NEW_LINE> galaxy_config_dir = self.app.path_resolver.galaxy_config_dir <NEW_LINE> config_file_path = join(galaxy_config_dir, self.conf_file_name) <NEW_LINE> if not exists(config_file_path): <NEW_LINE> <INDENT> sample_name = "%s.sample" % self.conf_file_name <NEW_LINE> defaults_source = join(galaxy_config_dir, sample_name) <NEW_LINE> symlink(defaults_source, defaults_destination) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> defaults_source = join(galaxy_config_dir, self.conf_file_name) <NEW_LINE> copyfile(defaults_source, defaults_destination) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def set_properties(self, properties, section="app:main", description=None, priority_offset=0): <NEW_LINE> <INDENT> if not properties: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> priority = int(self.app.ud.get("galaxy_option_priority", "400")) + priority_offset <NEW_LINE> conf_dir = self.conf_dir <NEW_LINE> if description is None: <NEW_LINE> <INDENT> description = properties.keys()[0] <NEW_LINE> <DEDENT> conf_file_name = "%s_cloudman_override_%s.ini" % (str(priority), description) <NEW_LINE> conf_file = join(conf_dir, conf_file_name) <NEW_LINE> props_str = "\n".join( ["%s=%s" % (k, v) for k, v in properties.iteritems()]) <NEW_LINE> open(conf_file, "w").write("[%s]\n%s" % (section, props_str))
When `galaxy_conf_dir` in specified in UserData this is used to manage Galaxy's options.
6259907d7b180e01f3e49d89
class Clickable: <NEW_LINE> <INDENT> def on_click(self): <NEW_LINE> <INDENT> print(self.__class__.__name__, 'clicked')
Класс объекта - обработчика нажатия мыши
6259907d56b00c62f0fb431c
class ImageUploadSerializer(UserDetailsSerializer): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = UserModel <NEW_LINE> fields = ('picture')
User Profile Image upload serializer
6259907d23849d37ff852b01
class RoleLoad(object): <NEW_LINE> <INDENT> def __init__(self, config_type): <NEW_LINE> <INDENT> self.config_type = config_type <NEW_LINE> <DEDENT> def get_method(self, path, name): <NEW_LINE> <INDENT> to_import = '%s.%s' % (path, name) <NEW_LINE> return __import__(to_import, fromlist=[name]) <NEW_LINE> <DEDENT> def validate_role(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.load_role() <NEW_LINE> <DEDENT> except genastack.CantContinue: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def _get_plugin_dir(): <NEW_LINE> <INDENT> home = os.path.join(os.getenv('HOME'), 'genastack_roles') <NEW_LINE> opt = '/opt/genastack_roles' <NEW_LINE> if os.path.isdir(home): <NEW_LINE> <INDENT> return home <NEW_LINE> <DEDENT> elif os.path.isdir(opt): <NEW_LINE> <INDENT> return opt <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise genastack.CantContinue( 'Neither %s or %s exist so you have no Roles installed.' ' Please create some roles prior to continuing.' ) <NEW_LINE> <DEDENT> <DEDENT> def load_all_roles(self, plugin_dir=None): <NEW_LINE> <INDENT> if plugin_dir is None: <NEW_LINE> <INDENT> plugin_dir = self._get_plugin_dir() <NEW_LINE> <DEDENT> modules = pkgutil.iter_modules(path=[plugin_dir]) <NEW_LINE> for loader, name, ispkg in modules: <NEW_LINE> <INDENT> if ispkg is True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> module_desc = imp.find_module(name, [plugin_dir]) <NEW_LINE> method = imp.load_module(name, *module_desc) <NEW_LINE> LOG.info('Loading Role [ %s ]' % name) <NEW_LINE> yield method.BUILD_DATA <NEW_LINE> <DEDENT> except Exception as exp: <NEW_LINE> <INDENT> msg = 'role [ %s ] failed to load, error [ %s ]' % ( name, exp ) <NEW_LINE> LOG.error(msg) <NEW_LINE> raise genastack.CantContinue(msg) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def load_role(self, plugin_dir=None): <NEW_LINE> <INDENT> if plugin_dir is None: <NEW_LINE> <INDENT> plugin_dir = self._get_plugin_dir() <NEW_LINE> <DEDENT> modules = pkgutil.iter_modules(path=[plugin_dir]) <NEW_LINE> for loader, name, ispkg in modules: <NEW_LINE> <INDENT> if ispkg is True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> module_desc = imp.find_module(name, [plugin_dir]) <NEW_LINE> method = imp.load_module(name, *module_desc) <NEW_LINE> self.config_type = self.config_type.replace('-', '_') <NEW_LINE> if self.config_type in method.BUILD_DATA: <NEW_LINE> <INDENT> LOG.info('Loading Role [ %s ]' % name) <NEW_LINE> return method.BUILD_DATA[self.config_type] <NEW_LINE> <DEDENT> <DEDENT> except Exception: <NEW_LINE> <INDENT> msg = 'role [ %s ] failed to load correctly' % name <NEW_LINE> LOG.error(msg) <NEW_LINE> raise genastack.CantContinue(msg) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> msg = 'no role [ %s ] found' % self.config_type <NEW_LINE> LOG.warn(msg) <NEW_LINE> raise genastack.CantContinue(msg)
Load a given Configuration Management role. :param config_type: ``str``
6259907d796e427e538501c3
class WebApplicationFirewallCustomRule(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'name': {'max_length': 128, 'min_length': 0}, 'etag': {'readonly': True}, 'priority': {'required': True}, 'rule_type': {'required': True}, 'match_conditions': {'required': True}, 'action': {'required': True}, } <NEW_LINE> _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'priority': {'key': 'priority', 'type': 'int'}, 'rule_type': {'key': 'ruleType', 'type': 'str'}, 'match_conditions': {'key': 'matchConditions', 'type': '[MatchCondition]'}, 'action': {'key': 'action', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(WebApplicationFirewallCustomRule, self).__init__(**kwargs) <NEW_LINE> self.name = kwargs.get('name', None) <NEW_LINE> self.etag = None <NEW_LINE> self.priority = kwargs['priority'] <NEW_LINE> self.rule_type = kwargs['rule_type'] <NEW_LINE> self.match_conditions = kwargs['match_conditions'] <NEW_LINE> self.action = kwargs['action']
Defines contents of a web application rule. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param name: The name of the resource that is unique within a policy. This name can be used to access the resource. :type name: str :ivar etag: A unique read-only string that changes whenever the resource is updated. :vartype etag: str :param priority: Required. Describes priority of the rule. Rules with a lower value will be evaluated before rules with a higher value. :type priority: int :param rule_type: Required. Describes type of rule. Possible values include: "MatchRule", "Invalid". :type rule_type: str or ~azure.mgmt.network.v2019_08_01.models.WebApplicationFirewallRuleType :param match_conditions: Required. List of match conditions. :type match_conditions: list[~azure.mgmt.network.v2019_08_01.models.MatchCondition] :param action: Required. Type of Actions. Possible values include: "Allow", "Block", "Log". :type action: str or ~azure.mgmt.network.v2019_08_01.models.WebApplicationFirewallAction
6259907d1f5feb6acb164642
@gin.configurable <NEW_LINE> class BackboneAngleTransform(Transform): <NEW_LINE> <INDENT> def single_call(self, angles): <NEW_LINE> <INDENT> sin, cos = tf.sin(angles), tf.cos(angles) <NEW_LINE> return tf.concat([sin, cos], -1)
Maps tf.Tensor<float>[len, 1] of angles to [len, 2] tensor of sin/cos.
6259907d4527f215b58eb6c5
class RestaurantImages(Base): <NEW_LINE> <INDENT> __tablename__ = 'restaurant_images' <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> restaurant_id = Column(Integer, ForeignKey('restaurant.id')) <NEW_LINE> restaurant = relationship(Restaurant) <NEW_LINE> image_id = Column(Integer, ForeignKey('image.id')) <NEW_LINE> image = relationship(Image)
Restaurant & Image pairs stored here. Many-to-many relationship.
6259907d5fdd1c0f98e5f9c9
class Battery(): <NEW_LINE> <INDENT> def __init__(self, battery_size=70): <NEW_LINE> <INDENT> self.battery_size = battery_size <NEW_LINE> <DEDENT> def describe_battery(self): <NEW_LINE> <INDENT> print("This car has a " + str(self.battery_size) + "-kWh battery.") <NEW_LINE> <DEDENT> def get_range(self): <NEW_LINE> <INDENT> if self.battery_size == 70: <NEW_LINE> <INDENT> range = 240 <NEW_LINE> <DEDENT> elif self.battery_size == 85: <NEW_LINE> <INDENT> range = 270 <NEW_LINE> <DEDENT> message = "This car can go approximately " + str(range) <NEW_LINE> message += " miles on a full charge." <NEW_LINE> print(message)
一次模拟电动汽车电瓶的简单尝试
6259907d7d43ff248742813a
class Comment(db.Model): <NEW_LINE> <INDENT> comment = db.StringProperty(required=True) <NEW_LINE> post = db.StringProperty(required=True) <NEW_LINE> @classmethod <NEW_LINE> def render(self): <NEW_LINE> <INDENT> self.render("comment.html")
This is the database which will hold the individual comments for the posts :comment = The comment that was made :post = the Post id that is commented.
6259907daad79263cf430204
class GetNotifySettings(Object): <NEW_LINE> <INDENT> ID = 0x12b3ad31 <NEW_LINE> def __init__(self, peer): <NEW_LINE> <INDENT> self.peer = peer <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def read(b: BytesIO, *args) -> "GetNotifySettings": <NEW_LINE> <INDENT> peer = Object.read(b) <NEW_LINE> return GetNotifySettings(peer) <NEW_LINE> <DEDENT> def write(self) -> bytes: <NEW_LINE> <INDENT> b = BytesIO() <NEW_LINE> b.write(Int(self.ID, False)) <NEW_LINE> b.write(self.peer.write()) <NEW_LINE> return b.getvalue()
Attributes: ID: ``0x12b3ad31`` Args: peer: Either :obj:`InputNotifyPeer <pyrogram.api.types.InputNotifyPeer>`, :obj:`InputNotifyUsers <pyrogram.api.types.InputNotifyUsers>`, :obj:`InputNotifyChats <pyrogram.api.types.InputNotifyChats>` or :obj:`InputNotifyBroadcasts <pyrogram.api.types.InputNotifyBroadcasts>` Raises: :obj:`Error <pyrogram.Error>` Returns: :obj:`PeerNotifySettings <pyrogram.api.types.PeerNotifySettings>`
6259907d91f36d47f2231bb3
class LangException(Exception): <NEW_LINE> <INDENT> pass
Base class for exceptions in this package
6259907d656771135c48ad55
class NotSubset(Negate, Subset): <NEW_LINE> <INDENT> reason = '{0} is a subset of {comparable}'
Asserts that `value` is a not a subset of `comparable`. Aliases: - ``to_not_be_subset`` - ``is_not_subset`` .. versionadded:: 0.5.0
6259907d5fcc89381b266e81
class ConferenceReference(InbookReference): <NEW_LINE> <INDENT> implements(IConferenceReference) <NEW_LINE> security = ClassSecurityInfo() <NEW_LINE> source_fields = ('booktitle', 'volume', 'number', 'series', 'pages', 'address', 'organization', 'publisher', ) <NEW_LINE> archetype_name = "Conference Reference" <NEW_LINE> schema = ConferenceSchema <NEW_LINE> security.declareProtected(View, 'Source') <NEW_LINE> def Source(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.ConferenceSource() <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> booktitle = self.getBooktitle() <NEW_LINE> volume = self.getVolume() <NEW_LINE> number = self.getNumber() <NEW_LINE> series = self.getSeries() <NEW_LINE> pages = self.getPages() <NEW_LINE> address = self.getAddress() <NEW_LINE> organization = self.getOrganization() <NEW_LINE> publisher = self.getPublisher() <NEW_LINE> source = 'In: %s' % booktitle <NEW_LINE> if volume: <NEW_LINE> <INDENT> source += ', vol. %s' % volume <NEW_LINE> if number: source += '(%s)' % number <NEW_LINE> <DEDENT> if pages: source += ', pp. %s' % pages <NEW_LINE> if address: source += ', ' + address <NEW_LINE> if organization: source += ', %s' % organization <NEW_LINE> if publisher: source += ', %s' % publisher <NEW_LINE> if series: source += '. %s' % series <NEW_LINE> return source + '.' <NEW_LINE> <DEDENT> <DEDENT> security.declareProtected(View, 'getCoinsDict') <NEW_LINE> def getCoinsDict(self): <NEW_LINE> <INDENT> coinsData = InbookReference.getCoinsDict(self) <NEW_LINE> coinsData['rft.aucorp'] = self.getOrganization() <NEW_LINE> coinsData['rft.genre'] = "conference" <NEW_LINE> return coinsData
content type to make reference to a conference volume.
6259907d283ffb24f3cf52eb
class Call(object): <NEW_LINE> <INDENT> DTMF_COMMAND_BASE = '+VTS=' <NEW_LINE> dtmfSupport = False <NEW_LINE> def __init__(self, gsmModem, callId, callType, number, callStatusUpdateCallbackFunc=None): <NEW_LINE> <INDENT> self._gsmModem = weakref.proxy(gsmModem) <NEW_LINE> self._callStatusUpdateCallbackFunc = callStatusUpdateCallbackFunc <NEW_LINE> self.id = callId <NEW_LINE> self.type = callType <NEW_LINE> self.number = number <NEW_LINE> self._answered = False <NEW_LINE> self.active = True <NEW_LINE> <DEDENT> @property <NEW_LINE> def answered(self): <NEW_LINE> <INDENT> return self._answered <NEW_LINE> <DEDENT> @answered.setter <NEW_LINE> def answered(self, answered): <NEW_LINE> <INDENT> self._answered = answered <NEW_LINE> if self._callStatusUpdateCallbackFunc: <NEW_LINE> <INDENT> self._callStatusUpdateCallbackFunc(self) <NEW_LINE> <DEDENT> <DEDENT> def sendDtmfTone(self, tones): <NEW_LINE> <INDENT> if self.answered: <NEW_LINE> <INDENT> toneLen = len(tones) <NEW_LINE> if len(tones) > 1: <NEW_LINE> <INDENT> cmd = ('AT{0}{1};{0}' + ';{0}'.join(tones[1:])).format(self.DTMF_COMMAND_BASE, tones[0]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cmd = 'AT{0}={0}'.format(self.DTMF_COMMAND_BASE, tones) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self._gsmModem.write(cmd, timeout=(5 + toneLen)) <NEW_LINE> <DEDENT> except CmeError as e: <NEW_LINE> <INDENT> if e.code == 30: <NEW_LINE> <INDENT> raise InterruptedException('No network service', e) <NEW_LINE> <DEDENT> elif e.code == 3: <NEW_LINE> <INDENT> raise InterruptedException('Operation not allowed', e) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise e <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise InvalidStateException('Call is not active (it has not yet been answered, or it has ended).') <NEW_LINE> <DEDENT> <DEDENT> def hangup(self): <NEW_LINE> <INDENT> self._gsmModem.write('ATH') <NEW_LINE> self.answered = False <NEW_LINE> self.active = False <NEW_LINE> if self.id in self._gsmModem.activeCalls: <NEW_LINE> <INDENT> del self._gsmModem.activeCalls[self.id]
A voice call
6259907d26068e7796d4e38a
class zerotime(restart_base): <NEW_LINE> <INDENT> pass
Test usage of docker 'restart' command (docker exits on SIGTERM) initialize: 1) start container with test command run_once: 2) check container output for start message 3) execute docker restart without timeout, container should not log info about SIGTERM 4) check container output for restart message 5) execute docker stop without timeout, container should not log info about SIGTERM 6) check container output for stop message postprocess: 7) analyze results
6259907d4428ac0f6e659f7b
class AMYFilterSet(django_filters.FilterSet): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> self.form.helper = bootstrap_helper_filter
This base class sets FormHelper.
6259907d55399d3f05627f60
class FlujoCreateForm(forms.ModelForm): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = Flujo <NEW_LINE> fields = ('nombre',)
Formulario para la creación de flujos.
6259907d67a9b606de5477cc
class Template(Classifier) : <NEW_LINE> <INDENT> attributes = {} <NEW_LINE> def __init__(self, arg = None, **args) : <NEW_LINE> <INDENT> Classifier.__init__(self, **args) <NEW_LINE> <DEDENT> def train(self, data, **args) : <NEW_LINE> <INDENT> Classifier.train(self, data, **args) <NEW_LINE> self.log.trainingTime = self.getTrainingTime() <NEW_LINE> <DEDENT> def decisionFunc(self, data, i) : <NEW_LINE> <INDENT> return margin <NEW_LINE> <DEDENT> def classify(self, data, i) : <NEW_LINE> <INDENT> return (margin, classification)
A template for a pyml classifier
6259907d76e4537e8c3f0fcb
class PackageURLParser(StaticURLParser): <NEW_LINE> <INDENT> def __init__(self, package_name, resource_name, root_resource=None, cache_max_age=None): <NEW_LINE> <INDENT> self.package_name = package_name <NEW_LINE> self.resource_name = os.path.normpath(resource_name) <NEW_LINE> if root_resource is None: <NEW_LINE> <INDENT> root_resource = self.resource_name <NEW_LINE> <DEDENT> self.root_resource = root_resource <NEW_LINE> self.cache_max_age = cache_max_age <NEW_LINE> <DEDENT> def __call__(self, environ, start_response): <NEW_LINE> <INDENT> path_info = environ.get('PATH_INFO', '') <NEW_LINE> if not path_info: <NEW_LINE> <INDENT> return self.add_slash(environ, start_response) <NEW_LINE> <DEDENT> if path_info == '/': <NEW_LINE> <INDENT> filename = 'index.html' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> filename = request.path_info_pop(environ) <NEW_LINE> <DEDENT> resource = os.path.normcase(os.path.normpath( self.resource_name + '/' + filename)) <NEW_LINE> if ( (self.root_resource is not None) and (not resource.startswith(self.root_resource)) ): <NEW_LINE> <INDENT> return self.not_found(environ, start_response) <NEW_LINE> <DEDENT> if not pkg_resources.resource_exists(self.package_name, resource): <NEW_LINE> <INDENT> return self.not_found(environ, start_response) <NEW_LINE> <DEDENT> if pkg_resources.resource_isdir(self.package_name, resource): <NEW_LINE> <INDENT> child_root = (self.root_resource is not None and self.root_resource or self.resource_name) <NEW_LINE> return self.__class__( self.package_name, resource, root_resource=child_root, cache_max_age=self.cache_max_age)(environ, start_response) <NEW_LINE> <DEDENT> if (environ.get('PATH_INFO') and environ.get('PATH_INFO') != '/'): <NEW_LINE> <INDENT> return self.error_extra_path(environ, start_response) <NEW_LINE> <DEDENT> full = pkg_resources.resource_filename(self.package_name, resource) <NEW_LINE> if_none_match = environ.get('HTTP_IF_NONE_MATCH') <NEW_LINE> if if_none_match: <NEW_LINE> <INDENT> mytime = os.stat(full).st_mtime <NEW_LINE> if str(mytime) == if_none_match: <NEW_LINE> <INDENT> headers = [] <NEW_LINE> ETAG.update(headers, mytime) <NEW_LINE> start_response('304 Not Modified', headers) <NEW_LINE> return [''] <NEW_LINE> <DEDENT> <DEDENT> fa = self.make_app(full) <NEW_LINE> if self.cache_max_age: <NEW_LINE> <INDENT> fa.cache_control(max_age=self.cache_max_age) <NEW_LINE> <DEDENT> return fa(environ, start_response) <NEW_LINE> <DEDENT> def not_found(self, environ, start_response, debug_message=None): <NEW_LINE> <INDENT> comment=('SCRIPT_NAME=%r; PATH_INFO=%r; looking in package %s; ' 'subdir %s ;debug: %s' % (environ.get('SCRIPT_NAME'), environ.get('PATH_INFO'), self.package_name, self.resource_name, debug_message or '(none)')) <NEW_LINE> exc = httpexceptions.HTTPNotFound( 'The resource at %s could not be found' % request.construct_url(environ), comment=comment) <NEW_LINE> return exc.wsgi_application(environ, start_response) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<%s %s:%s at %s>' % (self.__class__.__name__, self.package_name, self.root_resource, id(self))
This probably won't work with zipimported resources
6259907d283ffb24f3cf52ec
class agilent8594Q(agilent8590E): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.__dict__.setdefault('_instrument_id', '') <NEW_LINE> super(agilent8594Q, self).__init__(*args, **kwargs) <NEW_LINE> self._input_impedance = 50 <NEW_LINE> self._frequency_low = 9e3 <NEW_LINE> self._frequency_high = 2.9e9
Agilent 8594Q IVI spectrum analyzer driver
6259907d656771135c48ad56
class ToolValidator(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.params = arcpy.GetParameterInfo() <NEW_LINE> <DEDENT> def initializeParameters(self): <NEW_LINE> <INDENT> self.params[0].value = 1 <NEW_LINE> self.params[1].value = 0 <NEW_LINE> self.params[2].value = 0 <NEW_LINE> return <NEW_LINE> <DEDENT> def updateParameters(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def updateMessages(self): <NEW_LINE> <INDENT> if self.params[0].value == '0' and self.params[1].value == '0' and self.params[2].value == '0': <NEW_LINE> <INDENT> self.params[0].setErrorMessage("Please enter a valid interval of at least 1 second.") <NEW_LINE> <DEDENT> if not 0 <= int(self.params[0].value) <= 90: <NEW_LINE> <INDENT> self.params[0].setErrorMessage("Value must be between 0 and 90 degrees") <NEW_LINE> <DEDENT> if not 0 <= int(self.params[1].value) <= 59: <NEW_LINE> <INDENT> self.params[1].setErrorMessage("Value must be between 0 and 59 minutes") <NEW_LINE> <DEDENT> if not 0 <= int(self.params[2].value) <= 59: <NEW_LINE> <INDENT> self.params[2].setErrorMessage("Value must be between 0 and 59 seconds") <NEW_LINE> <DEDENT> mxd = arcpy.mapping.MapDocument('current') <NEW_LINE> if not mxd.activeDataFrame.mapUnits == 'DecimalDegrees': <NEW_LINE> <INDENT> self.params[3].setErrorMessage("Active data frame map units must be decimal degrees. E.g. WGS84") <NEW_LINE> <DEDENT> return
Class for validating a tool's parameter values and controlling the behavior of the tool's dialog.
6259907d99fddb7c1ca63afe
class Solution: <NEW_LINE> <INDENT> def climbStairs(self, n): <NEW_LINE> <INDENT> if n == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> if n == 1: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> if n == 2: <NEW_LINE> <INDENT> return 2 <NEW_LINE> <DEDENT> f = [0] * (n+1) <NEW_LINE> f[0] = 0 <NEW_LINE> f[1] = 1 <NEW_LINE> f[2] = 2 <NEW_LINE> for i in range(3,n+1): <NEW_LINE> <INDENT> f[i] = f[i-1] + f[i-2] <NEW_LINE> <DEDENT> return f[n]
@param n: An integer @return: An integer
6259907d796e427e538501c7
class GcsViolations(base_notification.BaseNotification): <NEW_LINE> <INDENT> def run(self): <NEW_LINE> <INDENT> if not self.notification_config['gcs_path'].startswith('gs://'): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> data_format = self.notification_config.get('data_format', 'csv') <NEW_LINE> if data_format not in self.supported_data_formats: <NEW_LINE> <INDENT> raise base_notification.InvalidDataFormatError( 'GCS uploader', data_format) <NEW_LINE> <DEDENT> if data_format == 'csv': <NEW_LINE> <INDENT> gcs_upload_path = '{}/{}'.format( self.notification_config['gcs_path'], self._get_output_filename( string_formats.VIOLATION_CSV_FMT)) <NEW_LINE> file_uploader.upload_csv( 'violations', self.violations, gcs_upload_path) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> gcs_upload_path = '{}/{}'.format( self.notification_config['gcs_path'], self._get_output_filename( string_formats.VIOLATION_JSON_FMT)) <NEW_LINE> file_uploader.upload_json(self.violations, gcs_upload_path)
Upload violations to GCS.
6259907d3617ad0b5ee07b9b
class SectionMatcher(object): <NEW_LINE> <INDENT> def __init__(self, store): <NEW_LINE> <INDENT> self.store = store <NEW_LINE> <DEDENT> def get_sections(self): <NEW_LINE> <INDENT> sections = self.store.get_sections() <NEW_LINE> for store, s in sections: <NEW_LINE> <INDENT> if self.match(s): <NEW_LINE> <INDENT> yield store, s <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def match(self, section): <NEW_LINE> <INDENT> raise NotImplementedError(self.match)
Select sections into a given Store. This is intended to be used to postpone getting an iterable of sections from a store.
6259907d3346ee7daa338388
class EventPaymentReminder(CronJobBase): <NEW_LINE> <INDENT> RUN_EVERY_MINS = 5 <NEW_LINE> schedule = Schedule(run_every_mins=RUN_EVERY_MINS) <NEW_LINE> code = 'bccf.event_payment_reminder' <NEW_LINE> email_title = 'Event Registration Payment Reminder' <NEW_LINE> def do(self): <NEW_LINE> <INDENT> events = Event.objects.need_reminder().all() <NEW_LINE> for event in events: <NEW_LINE> <INDENT> regs = EventRegistration.objects.filter(~Q(reminder=True), ~Q(paid=True), event=event.pk) <NEW_LINE> for reg in regs: <NEW_LINE> <INDENT> context = { 'event': event, 'reg': reg } <NEW_LINE> email.send_reminder(self.email_title, reg.user, context) <NEW_LINE> reg.reminder = True <NEW_LINE> reg.save()
CronJob for sending a payment reminder to users who have not paid their registrations. The is reminder will be sent 4 weeks before the event.
6259907d97e22403b383c94e
class OSMusicPlayer(MusicPlayer): <NEW_LINE> <INDENT> def __init__(self) -> None: <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self._want_to_play = False <NEW_LINE> self._actually_playing = False <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_valid_music_file_extensions(cls) -> List[str]: <NEW_LINE> <INDENT> return ['mp3', 'ogg', 'm4a', 'wav', 'flac', 'mid'] <NEW_LINE> <DEDENT> def on_select_entry(self, callback: Callable[[Any], None], current_entry: Any, selection_target_name: str) -> Any: <NEW_LINE> <INDENT> from bastd.ui.soundtrack.entrytypeselect import ( SoundtrackEntryTypeSelectWindow) <NEW_LINE> return SoundtrackEntryTypeSelectWindow(callback, current_entry, selection_target_name) <NEW_LINE> <DEDENT> def on_set_volume(self, volume: float) -> None: <NEW_LINE> <INDENT> _ba.music_player_set_volume(volume) <NEW_LINE> <DEDENT> def on_play(self, entry: Any) -> None: <NEW_LINE> <INDENT> music = _ba.app.music <NEW_LINE> entry_type = music.get_soundtrack_entry_type(entry) <NEW_LINE> name = music.get_soundtrack_entry_name(entry) <NEW_LINE> assert name is not None <NEW_LINE> if entry_type == 'musicFile': <NEW_LINE> <INDENT> self._want_to_play = self._actually_playing = True <NEW_LINE> _ba.music_player_play(name) <NEW_LINE> <DEDENT> elif entry_type == 'musicFolder': <NEW_LINE> <INDENT> self._want_to_play = True <NEW_LINE> self._actually_playing = False <NEW_LINE> _PickFolderSongThread(name, self.get_valid_music_file_extensions(), self._on_play_folder_cb).start() <NEW_LINE> <DEDENT> <DEDENT> def _on_play_folder_cb(self, result: Union[str, List[str]], error: Optional[str] = None) -> None: <NEW_LINE> <INDENT> from ba import _lang <NEW_LINE> if error is not None: <NEW_LINE> <INDENT> rstr = (_lang.Lstr( resource='internal.errorPlayingMusicText').evaluate()) <NEW_LINE> if isinstance(result, str): <NEW_LINE> <INDENT> err_str = (rstr.replace('${MUSIC}', os.path.basename(result)) + '; ' + str(error)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> err_str = (rstr.replace('${MUSIC}', '<multiple>') + '; ' + str(error)) <NEW_LINE> <DEDENT> _ba.screenmessage(err_str, color=(1, 0, 0)) <NEW_LINE> return <NEW_LINE> <DEDENT> if not self._want_to_play: <NEW_LINE> <INDENT> print('_on_play_folder_cb called with _want_to_play False') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._actually_playing = True <NEW_LINE> _ba.music_player_play(result) <NEW_LINE> <DEDENT> <DEDENT> def on_stop(self) -> None: <NEW_LINE> <INDENT> self._want_to_play = False <NEW_LINE> self._actually_playing = False <NEW_LINE> _ba.music_player_stop() <NEW_LINE> <DEDENT> def on_app_shutdown(self) -> None: <NEW_LINE> <INDENT> _ba.music_player_shutdown()
Music player that talks to internal C++ layer for functionality. (internal)
6259907d1b99ca400229025c
class Dotfile: <NEW_LINE> <INDENT> def __init__(self, name, gitplace, sysplace, isdir=False, place=""): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.gitplace = gitplace <NEW_LINE> self.sysplace = sysplace <NEW_LINE> self.isdir = isdir <NEW_LINE> self.place = place <NEW_LINE> dotfiles.append(self) <NEW_LINE> <DEDENT> def exists(self): <NEW_LINE> <INDENT> if self.isdir: <NEW_LINE> <INDENT> return os.path.isdir(self.sysplace) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return os.path.isfile(self.sysplace) <NEW_LINE> <DEDENT> <DEDENT> def placetest(self): <NEW_LINE> <INDENT> if self.place != "" and not os.path.isdir(self.place): <NEW_LINE> <INDENT> os.system("mkdir {0}".format(self.place)) <NEW_LINE> <DEDENT> <DEDENT> def link(self): <NEW_LINE> <INDENT> os.system("ln -s {0} {1}".format(self.gitplace, self.sysplace))
A object for each file or directory that needs to be setup.
6259907d5166f23b2e244e26
class SimulatedReferenceSet(AbstractReferenceSet): <NEW_LINE> <INDENT> def __init__(self, localId, randomSeed=0, numReferences=1): <NEW_LINE> <INDENT> super(SimulatedReferenceSet, self).__init__(localId) <NEW_LINE> self._randomSeed = randomSeed <NEW_LINE> self._randomGenerator = random.Random() <NEW_LINE> self._randomGenerator.seed(self._randomSeed) <NEW_LINE> for i in range(numReferences): <NEW_LINE> <INDENT> referenceSeed = self._randomGenerator.getrandbits(32) <NEW_LINE> referenceLocalId = "srs{}".format(i) <NEW_LINE> reference = SimulatedReference( self, referenceLocalId, referenceSeed) <NEW_LINE> self._referenceIdMap[reference.getId()] = reference <NEW_LINE> <DEDENT> self._referenceIds = sorted(self._referenceIdMap.keys())
A simulated referenceSet
6259907d4527f215b58eb6c7
class SerializationMixin: <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def _pickle_serialize(obj): <NEW_LINE> <INDENT> return pickle.dumps(obj, protocol=pickle.HIGHEST_PROTOCOL) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _pickle_deserialize(bstring): <NEW_LINE> <INDENT> return pickle.loads(bstring) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _pyarrow_serialize(obj): <NEW_LINE> <INDENT> return pyarrow.serialize(obj).to_buffer().to_pybytes() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _pyarrow_deserialize(bstring): <NEW_LINE> <INDENT> return pyarrow.deserialize(pyarrow.frombuffer(bstring)) <NEW_LINE> <DEDENT> def _singleprocess_deserialize_list(self, results): <NEW_LINE> <INDENT> return [self._deserialize(self._decompress(r)) for r in results] <NEW_LINE> <DEDENT> def _multiprocess_deserialize_list(self, results): <NEW_LINE> <INDENT> with Pool() as p: <NEW_LINE> <INDENT> return p.map(self._deserialize, p.map(self._decompress, results)) <NEW_LINE> <DEDENT> <DEDENT> def _compress(self, bstring): <NEW_LINE> <INDENT> if self.use_compression: <NEW_LINE> <INDENT> return lz4.frame.compress(bstring) <NEW_LINE> <DEDENT> return bstring <NEW_LINE> <DEDENT> def _decompress(self, bstring): <NEW_LINE> <INDENT> if self.use_compression: <NEW_LINE> <INDENT> return lz4.frame.decompress(bstring) <NEW_LINE> <DEDENT> return bstring
Mixin to do serialization for a datastore if required. Supports ability to do serialization in a separate process.
6259907d5fdd1c0f98e5f9cd
class Entry_u_boot_tpl_dtb_with_ucode(Entry_u_boot_dtb_with_ucode): <NEW_LINE> <INDENT> def __init__(self, section, etype, node): <NEW_LINE> <INDENT> Entry_u_boot_dtb_with_ucode.__init__(self, section, etype, node) <NEW_LINE> <DEDENT> def GetDefaultFilename(self): <NEW_LINE> <INDENT> return 'tpl/u-boot-tpl.dtb'
U-Boot TPL with embedded microcode pointer This is used when TPL must set up the microcode for U-Boot. See Entry_u_boot_ucode for full details of the entries involved in this process.
6259907d67a9b606de5477cd
class SimulationType(enum.IntEnum): <NEW_LINE> <INDENT> UNSPECIFIED = 0 <NEW_LINE> UNKNOWN = 1 <NEW_LINE> CPC_BID = 2 <NEW_LINE> CPV_BID = 3 <NEW_LINE> TARGET_CPA = 4 <NEW_LINE> BID_MODIFIER = 5
Enum describing the field a simulation modifies. Attributes: UNSPECIFIED (int): Not specified. UNKNOWN (int): Used for return value only. Represents value unknown in this version. CPC_BID (int): The simulation is for a cpc bid. CPV_BID (int): The simulation is for a cpv bid. TARGET_CPA (int): The simulation is for a cpa target. BID_MODIFIER (int): The simulation is for a bid modifier.
6259907ddc8b845886d55008
class FoveaPrintLogger(object): <NEW_LINE> <INDENT> def __init__(self, filestream=None, dbfilepath=None): <NEW_LINE> <INDENT> self._file = filestream or sys.stdout <NEW_LINE> self._write = self._file.write <NEW_LINE> self._flush = self._file.flush <NEW_LINE> self.event_list = [] <NEW_LINE> self.counter = counter_util() <NEW_LINE> self.event = {} <NEW_LINE> self._dbfilepath = dbfilepath <NEW_LINE> self.db = make_DB(dbfilepath) <NEW_LINE> <DEDENT> def set_DB_filepath(self, dbfilepath): <NEW_LINE> <INDENT> self._dbfilepath = dbfilepath <NEW_LINE> self.db = make_DB(dbfilepath) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<FoveaPrintLogger(file={0!r},dbfilepath={1!r})>'.format(self._file,self._dbfilepath) <NEW_LINE> <DEDENT> def msg(self, message): <NEW_LINE> <INDENT> self._write(message + '\n') <NEW_LINE> self._flush() <NEW_LINE> self.event_list.append(self.event.copy()) <NEW_LINE> id = self.counter.get_count() <NEW_LINE> db_dict = {'id': id} <NEW_LINE> db_dict.update(self.event) <NEW_LINE> self.db.insert(db_dict) <NEW_LINE> <DEDENT> err = debug = info = warning = error = critical = log = msg
(Non-thread safe version of structlog.PrintLogger) Prints events into a file AND store event structure internally as `event_list` attribute and an SQL database (accessible via get_DB method). :param filestream file: File (stream) to print to. (default: stdout) :param dbfilepath: tinydb file path or None (default) for in-memory only
6259907d3317a56b869bf26d
class ChinaDailySpider(WebsiteSpider): <NEW_LINE> <INDENT> name = 'china_daily' <NEW_LINE> allowed_domains = ['china.chinadaily.com.cn'] <NEW_LINE> start_urls = ['http://china.chinadaily.com.cn/'] <NEW_LINE> def parse_content(self, response): <NEW_LINE> <INDENT> categories = [] <NEW_LINE> try: <NEW_LINE> <INDENT> category_links = response.selector.xpath("//div[@class='da-bre']//a/text()") <NEW_LINE> categories = [link.extract() for link in category_links] <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> item = { 'categories' : categories, 'url' : str(response.url), 'text' : converter.handle(response.selector.xpath("//div[@class='container-left2']").extract()[0]) } <NEW_LINE> return [item] <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return []
This crawler fetches articles from the ChinaDaily website.
6259907d7c178a314d78e912
class ProductionConfig(BaseConfig): <NEW_LINE> <INDENT> DEBUG = False
生产环境配置
6259907d7d847024c075de2c
class Counter: <NEW_LINE> <INDENT> def __init__(self, parent): <NEW_LINE> <INDENT> self.parent = parent <NEW_LINE> self.frame = tkinter.Frame(parent) <NEW_LINE> self.frame.pack() <NEW_LINE> self.state = tkinter.IntVar() <NEW_LINE> self.state.set(0) <NEW_LINE> self.label = tkinter.Label(self.frame, textvariable=self.state) <NEW_LINE> self.label.pack() <NEW_LINE> self.up = tkinter.Button(self.frame, text='Up', command=self.up_click) <NEW_LINE> self.up.pack(side='left') <NEW_LINE> self.right = tkinter.Button(self.frame, text='Quit', command=self.quit_click) <NEW_LINE> self.right.pack(side='left') <NEW_LINE> <DEDENT> def up_click(self): <NEW_LINE> <INDENT> self.state.set(self.state.get() + 1) <NEW_LINE> <DEDENT> def quit_click(self): <NEW_LINE> <INDENT> self.parent.destroy()
A simple counter GUI using object-oriented programming.
6259907d2c8b7c6e89bd5235
class BertWrapper(torch.nn.Module): <NEW_LINE> <INDENT> def __init__( self, bert_model, output_dim, add_transformer_layer=False, layer_pulled=-1, aggregation="first", ): <NEW_LINE> <INDENT> super(BertWrapper, self).__init__() <NEW_LINE> self.layer_pulled = layer_pulled <NEW_LINE> self.aggregation = aggregation <NEW_LINE> self.add_transformer_layer = add_transformer_layer <NEW_LINE> bert_output_dim = bert_model.embeddings.word_embeddings.weight.size(1) <NEW_LINE> if add_transformer_layer: <NEW_LINE> <INDENT> config_for_one_layer = BertConfig( 0, hidden_size=bert_output_dim, num_attention_heads=int(bert_output_dim / 64), intermediate_size=3072, hidden_act='gelu', ) <NEW_LINE> self.additional_transformer_layer = BertLayer(config_for_one_layer) <NEW_LINE> <DEDENT> self.additional_linear_layer = torch.nn.Linear(bert_output_dim, output_dim) <NEW_LINE> self.bert_model = bert_model <NEW_LINE> <DEDENT> def forward(self, token_ids, segment_ids, attention_mask): <NEW_LINE> <INDENT> output_bert, output_pooler = self.bert_model( token_ids, segment_ids, attention_mask ) <NEW_LINE> layer_of_interest = output_bert[self.layer_pulled] <NEW_LINE> dtype = next(self.parameters()).dtype <NEW_LINE> if self.add_transformer_layer: <NEW_LINE> <INDENT> extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(2) <NEW_LINE> extended_attention_mask = (~extended_attention_mask).to(dtype) * neginf( dtype ) <NEW_LINE> embedding_layer = self.additional_transformer_layer( layer_of_interest, extended_attention_mask ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> embedding_layer = layer_of_interest <NEW_LINE> <DEDENT> if self.aggregation == "mean": <NEW_LINE> <INDENT> outputs_of_interest = embedding_layer[:, 1:, :] <NEW_LINE> mask = attention_mask[:, 1:].type_as(embedding_layer).unsqueeze(2) <NEW_LINE> sumed_embeddings = torch.sum(outputs_of_interest * mask, dim=1) <NEW_LINE> nb_elems = torch.sum(attention_mask[:, 1:].type(dtype), dim=1).unsqueeze(1) <NEW_LINE> embeddings = sumed_embeddings / nb_elems <NEW_LINE> <DEDENT> elif self.aggregation == "max": <NEW_LINE> <INDENT> outputs_of_interest = embedding_layer[:, 1:, :] <NEW_LINE> mask = (~attention_mask[:, 1:]).type(dtype).unsqueeze(2) * neginf(dtype) <NEW_LINE> embeddings, _ = torch.max(outputs_of_interest + mask, dim=1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> embeddings = embedding_layer[:, 0, :] <NEW_LINE> <DEDENT> result = self.additional_linear_layer(embeddings) <NEW_LINE> result += 0 * torch.sum(output_pooler) <NEW_LINE> return result
Adds a optional transformer layer and a linear layer on top of BERT.
6259907d67a9b606de5477ce
class AsignarEquipoConfirm(AsignarHistorias): <NEW_LINE> <INDENT> template_name = 'AsignarEquipoConfirm.html' <NEW_LINE> context_object_name = 'lista_sprints' <NEW_LINE> def post(self, request, *args, **kwargs): <NEW_LINE> <INDENT> diccionario={} <NEW_LINE> usuario_logueado= Usuario.objects.get(id= request.POST['login']) <NEW_LINE> diccionario['logueado']= usuario_logueado <NEW_LINE> diccionario['proyecto']= Proyecto.objects.get(id= request.POST['proyecto']) <NEW_LINE> proyecto_actual = Proyecto.objects.get(id= request.POST['proyecto']) <NEW_LINE> diccionario[self.context_object_name]= Sprint.objects.filter(activo= True, proyecto= proyecto_actual) <NEW_LINE> diccionario['historias']= Historia.objects.filter(activo= True, proyecto= proyecto_actual) <NEW_LINE> sprint_actual = Sprint.objects.get(id = request.POST['sprint']) <NEW_LINE> for i in sprint_actual.equipo.all(): <NEW_LINE> <INDENT> if i.usuario == Usuario.objects.get(id=request.POST['usuario']): <NEW_LINE> <INDENT> team= Equipo.objects.get(usuario=Usuario.objects.get(id=request.POST['usuario'])) <NEW_LINE> team.horas_sprint = request.POST['horas'] <NEW_LINE> team.save() <NEW_LINE> diccionario['sprint']=sprint_actual <NEW_LINE> return render(request, self.template_name, diccionario) <NEW_LINE> <DEDENT> <DEDENT> team = Equipo() <NEW_LINE> team.usuario = Usuario.objects.get(id=request.POST['usuario']) <NEW_LINE> team.horas_sprint = request.POST['horas'] <NEW_LINE> team.save() <NEW_LINE> sprint_actual.equipo.add(team) <NEW_LINE> sprint_actual.save() <NEW_LINE> diccionario['sprint']=sprint_actual <NEW_LINE> return render(request, self.template_name, diccionario)
Confirma la asignacion de usuario a un sprint especifico
6259907dad47b63b2c5a92a0
class stopwatch(object): <NEW_LINE> <INDENT> def __init__(self, level=logging.DEBUG): <NEW_LINE> <INDENT> self._level = level <NEW_LINE> <DEDENT> def __call__(self, method): <NEW_LINE> <INDENT> @wraps(method) <NEW_LINE> def wrapped_f(*args, **options): <NEW_LINE> <INDENT> _self = args[0] <NEW_LINE> fname = method.__name__ <NEW_LINE> class_name = _self.__class__.__name__ <NEW_LINE> name = _self.name <NEW_LINE> sw = StopWatch(start=True) <NEW_LINE> logger = logging.getLogger() <NEW_LINE> logger.log(self._level, '%s[%s].%s - start' %(class_name, name, fname)) <NEW_LINE> result = method(*args, **options) <NEW_LINE> logger.log(self._level, '%s[%s].%s - finished in %s' %(class_name, name, fname, sw.stop())) <NEW_LINE> return result <NEW_LINE> <DEDENT> return wrapped_f
Decorator class for measuring the execution time of methods.
6259907d3317a56b869bf26e
class Supply(models.Model): <NEW_LINE> <INDENT> name = models.CharField() <NEW_LINE> type = models.ForeignKey('DevTypes') <NEW_LINE> part_number = models.CharField() <NEW_LINE> manufacturer = models.ForeignKey('Manufacturer') <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return "%s %s" % (self.Manufacturer, self.Name)
Расходник: картриджи, бумага, тонер, ЗиПы, ремкомплекты и т.д.
6259907d23849d37ff852b09
class FirewallPolicyNatRule(FirewallPolicyRule): <NEW_LINE> <INDENT> _validation = { 'rule_type': {'required': True}, 'priority': {'maximum': 65000, 'minimum': 100}, } <NEW_LINE> _attribute_map = { 'rule_type': {'key': 'ruleType', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'priority': {'key': 'priority', 'type': 'int'}, 'action': {'key': 'action', 'type': 'FirewallPolicyNatRuleAction'}, 'translated_address': {'key': 'translatedAddress', 'type': 'str'}, 'translated_port': {'key': 'translatedPort', 'type': 'str'}, 'rule_condition': {'key': 'ruleCondition', 'type': 'FirewallPolicyRuleCondition'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(FirewallPolicyNatRule, self).__init__(**kwargs) <NEW_LINE> self.rule_type = 'FirewallPolicyNatRule' <NEW_LINE> self.action = kwargs.get('action', None) <NEW_LINE> self.translated_address = kwargs.get('translated_address', None) <NEW_LINE> self.translated_port = kwargs.get('translated_port', None) <NEW_LINE> self.rule_condition = kwargs.get('rule_condition', None)
Firewall Policy NAT Rule. All required parameters must be populated in order to send to Azure. :param rule_type: Required. The type of the rule.Constant filled by server. Possible values include: "FirewallPolicyNatRule", "FirewallPolicyFilterRule". :type rule_type: str or ~azure.mgmt.network.v2019_06_01.models.FirewallPolicyRuleType :param name: Name of the Rule. :type name: str :param priority: Priority of the Firewall Policy Rule resource. :type priority: int :param action: The action type of a Nat rule, SNAT or DNAT. :type action: ~azure.mgmt.network.v2019_06_01.models.FirewallPolicyNatRuleAction :param translated_address: The translated address for this NAT rule. :type translated_address: str :param translated_port: The translated port for this NAT rule. :type translated_port: str :param rule_condition: The match conditions for incoming traffic. :type rule_condition: ~azure.mgmt.network.v2019_06_01.models.FirewallPolicyRuleCondition
6259907d4f88993c371f124a
class AssemblyMapper: <NEW_LINE> <INDENT> map_cache = dict() <NEW_LINE> def __init__(self, from_assembly='GRCh37', to_assembly='GRCh38', species='human'): <NEW_LINE> <INDENT> self.client = EnsemblClient() <NEW_LINE> self.assembly_map = self._fetch_mapping(from_assembly, to_assembly, species) <NEW_LINE> <DEDENT> def _fetch_mapping(self, from_assembly, to_assembly, species): <NEW_LINE> <INDENT> map_key = from_assembly + to_assembly + species <NEW_LINE> if map_key in self.map_cache: <NEW_LINE> <INDENT> return self.map_cache[map_key] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> mapping = self._assemble_mapping(from_assembly, to_assembly, species) <NEW_LINE> self.__class__.map_cache[map_key] = mapping <NEW_LINE> return mapping <NEW_LINE> <DEDENT> <DEDENT> def _assemble_mapping(self, from_assembly, to_assembly, species): <NEW_LINE> <INDENT> client = self.client <NEW_LINE> genome_info = client.assembly_info(species=species) <NEW_LINE> chromosomes = {item['name']: item['length'] for item in genome_info['top_level_region'] if item['coord_system'] == 'chromosome'} <NEW_LINE> assembly_map = dict() <NEW_LINE> for chrom, chrom_len in chromosomes.items(): <NEW_LINE> <INDENT> region = region_str(chrom, start=1, end=chrom_len) <NEW_LINE> map_ = client.assembly_map(species=species, region=region, asm_one=from_assembly, asm_two=to_assembly) <NEW_LINE> assembly_map[chrom] = self._interval_tree(map_['mappings'], chrom_len) <NEW_LINE> <DEDENT> return assembly_map <NEW_LINE> <DEDENT> def _interval_tree(self, mappings, chrom_length): <NEW_LINE> <INDENT> interval_tree = IntervalTree() <NEW_LINE> for item in mappings: <NEW_LINE> <INDENT> from_ = item['original'] <NEW_LINE> to = item['mapped'] <NEW_LINE> from_region = from_['start'],from_['end']+1 <NEW_LINE> if to['strand'] == +1: <NEW_LINE> <INDENT> to_region = to['start'],to['end'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> to_region = (chrom_length - to['end'] + 1, chrom_length - to['start'] + 1) <NEW_LINE> <DEDENT> interval_tree.addi(*from_region, data=to_region) <NEW_LINE> <DEDENT> return interval_tree <NEW_LINE> <DEDENT> def map(self, chrom, pos): <NEW_LINE> <INDENT> chromosome_mapper = self.assembly_map[str(chrom)] <NEW_LINE> interval = chromosome_mapper[pos] <NEW_LINE> if interval: <NEW_LINE> <INDENT> interval = interval.pop() <NEW_LINE> mapped_pos = interval.data[0] + (pos - interval.begin) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> mapped_pos = None <NEW_LINE> <DEDENT> return mapped_pos
Structure that optimizes the mapping between diferent genome assemblies. Example:: >>> mapper = AssemblyMapper(from_assembly='GRCh37' ... to_assembly='GRCh38') >>> mapper.map(chrom='1', pos=1000000) 1064620
6259907da8370b77170f1e20
class ModifyCCThresholdPolicyRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.InstanceId = None <NEW_LINE> self.Ip = None <NEW_LINE> self.Domain = None <NEW_LINE> self.Protocol = None <NEW_LINE> self.Threshold = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.InstanceId = params.get("InstanceId") <NEW_LINE> self.Ip = params.get("Ip") <NEW_LINE> self.Domain = params.get("Domain") <NEW_LINE> self.Protocol = params.get("Protocol") <NEW_LINE> self.Threshold = params.get("Threshold") <NEW_LINE> memeber_set = set(params.keys()) <NEW_LINE> for name, value in vars(self).items(): <NEW_LINE> <INDENT> if name in memeber_set: <NEW_LINE> <INDENT> memeber_set.remove(name) <NEW_LINE> <DEDENT> <DEDENT> if len(memeber_set) > 0: <NEW_LINE> <INDENT> warnings.warn("%s fileds are useless." % ",".join(memeber_set))
ModifyCCThresholdPolicy请求参数结构体
6259907d32920d7e50bc7a92
class Sprite(object): <NEW_LINE> <INDENT> def __init__(self, file_path): <NEW_LINE> <INDENT> self.file_path = file_path <NEW_LINE> self.image = Image.open(file_path) <NEW_LINE> self.name = basename(file_path) <NEW_LINE> self.unrotated_source_size = self.image.size <NEW_LINE> self.position = (-1, -1) <NEW_LINE> self.rotated = False <NEW_LINE> self.scale = 1.0 <NEW_LINE> self.source_pixels_to_points = 1.0 <NEW_LINE> <DEDENT> @property <NEW_LINE> def unrotated_size(self): <NEW_LINE> <INDENT> s = (int(round(self.unrotated_source_size[0]*self.scale)), int(round(self.unrotated_source_size[1]*self.scale))) <NEW_LINE> return s <NEW_LINE> <DEDENT> @property <NEW_LINE> def source_size(self): <NEW_LINE> <INDENT> s = self.unrotated_source_size <NEW_LINE> if self.rotated: <NEW_LINE> <INDENT> return tuple(s[::-1]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return s <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def point_size(self): <NEW_LINE> <INDENT> def arr(x): <NEW_LINE> <INDENT> return int(round(x*self.source_pixels_to_points/self.scale)) <NEW_LINE> <DEDENT> s = map(arr, self.size) <NEW_LINE> return tuple(s) <NEW_LINE> <DEDENT> @property <NEW_LINE> def size(self): <NEW_LINE> <INDENT> s = (int(round(self.source_size[0]*self.scale)), int(round(self.source_size[1]*self.scale))) <NEW_LINE> return s <NEW_LINE> <DEDENT> @property <NEW_LINE> def width(self): <NEW_LINE> <INDENT> return self.size[0] <NEW_LINE> <DEDENT> @property <NEW_LINE> def height(self): <NEW_LINE> <INDENT> return self.size[1]
A reference of a sprite, with all the information needed for the packing algorithm, i.e. without any actual image data, just the size.
6259907d4f6381625f19a1d6
class TestComposedBool(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_ComposedBool(self): <NEW_LINE> <INDENT> pass
ComposedBool unit test stubs
6259907da8370b77170f1e21
class MoodiesUser: <NEW_LINE> <INDENT> def __init__(self, user_id): <NEW_LINE> <INDENT> self.user_id = user_id <NEW_LINE> self.moods_container = MoodsContainer() <NEW_LINE> self.top_mood = self.moods_container.moods['default'] <NEW_LINE> <DEDENT> def compute_top_mood(self): <NEW_LINE> <INDENT> self.top_mood = self.moods_container.compute_top_mood() <NEW_LINE> return self.top_mood
User class, store Mood per users in a MoodsContainer
6259907d71ff763f4b5e91fe
class ImageListView(OpenstackListView): <NEW_LINE> <INDENT> serializer_class = ImageSerializer <NEW_LINE> service = OpenstackService.Services.IMAGES
Image list view.
6259907d66673b3332c31e50
class ConfirmationQuestion(Question): <NEW_LINE> <INDENT> def __init__(self, question, default=True, true_answer_regex="(?i)^y"): <NEW_LINE> <INDENT> super(ConfirmationQuestion, self).__init__(question, default) <NEW_LINE> self._true_answer_regex = true_answer_regex <NEW_LINE> self._normalizer = self._get_default_normalizer <NEW_LINE> <DEDENT> def _write_prompt(self, io): <NEW_LINE> <INDENT> message = self._question <NEW_LINE> message = "<question>{} (yes/no)</> [<comment>{}</>] ".format( message, "yes" if self._default else "no" ) <NEW_LINE> io.error(message) <NEW_LINE> <DEDENT> def _get_default_normalizer(self, answer): <NEW_LINE> <INDENT> if isinstance(answer, bool): <NEW_LINE> <INDENT> return answer <NEW_LINE> <DEDENT> answer_is_true = re.match(self._true_answer_regex, answer) is not None <NEW_LINE> if self.default is False: <NEW_LINE> <INDENT> return answer and answer_is_true <NEW_LINE> <DEDENT> return not answer or answer_is_true
Represents a yes/no question.
6259907d3617ad0b5ee07b9f
class ChecklistIdentifier(ValidationTestCase): <NEW_LINE> <INDENT> def test_checklist_version(self): <NEW_LINE> <INDENT> for checklist in checklists: <NEW_LINE> <INDENT> self.assertIsInstance(checklist['identifier'], unicode, msg=checklist['source']) <NEW_LINE> <DEDENT> <DEDENT> def test_checklist_identifier(self): <NEW_LINE> <INDENT> for checklist in checklists: <NEW_LINE> <INDENT> self.assertIsInstance(checklist['identifier'], unicode, msg=checklist['source']) <NEW_LINE> <DEDENT> <DEDENT> def test_checklist_identifier_set(self): <NEW_LINE> <INDENT> for checklist in checklists: <NEW_LINE> <INDENT> self.assertTrue(checklist['identifier']) <NEW_LINE> <DEDENT> <DEDENT> def test_checklist_identifier_stripped(self): <NEW_LINE> <INDENT> for checklist in checklists: <NEW_LINE> <INDENT> self.assertStripped(checklist['identifier'], msg=checklist['source'])
Validate the checklist identifier in the downloaded checklists.
6259907d97e22403b383c952