code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
@benchmark.Disabled('xp') <NEW_LINE> class DromaeoDomCoreModify(_DromaeoBenchmark): <NEW_LINE> <INDENT> tag = 'domcoremodify' <NEW_LINE> query_param = 'dom-modify' <NEW_LINE> @classmethod <NEW_LINE> def Name(cls): <NEW_LINE> <INDENT> return 'dromaeo.domcoremodify'
Dromaeo DOMCore modify JavaScript benchmark. Tests creating and injecting DOM nodes.
62598f9cbaa26c4b54d4f058
class Team(models.Model): <NEW_LINE> <INDENT> name = models.TextField(max_length=200) <NEW_LINE> invitation_code = models.UUIDField( default=uuid.uuid4, editable=False, unique=True, null=True )
Class representing the team table in the database. Objects of this class will be used to interact with the team table in the database.
62598f9c4428ac0f6e6582d1
class TablePrinter(ResourcePrinter): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(TablePrinter, self).__init__(*args, **kwargs) <NEW_LINE> self._rows = [] <NEW_LINE> <DEDENT> def AddRow(self, row): <NEW_LINE> <INDENT> self._rows.append(row) <NEW_LINE> <DEDENT> def Print(self): <NEW_LINE> <INDENT> if not self._rows: <NEW_LINE> <INDENT> self._out.write('\n') <NEW_LINE> return <NEW_LINE> <DEDENT> rows = [[_Stringify(cell) for cell in row] for row in self._rows] <NEW_LINE> col_widths = [0] * len(rows[0]) <NEW_LINE> for row in rows: <NEW_LINE> <INDENT> for i in xrange(len(row)): <NEW_LINE> <INDENT> col_widths[i] = max(col_widths[i], len(row[i])) <NEW_LINE> <DEDENT> <DEDENT> for row in rows: <NEW_LINE> <INDENT> line = cStringIO.StringIO() <NEW_LINE> for i in xrange(len(row) - 1): <NEW_LINE> <INDENT> line.write(row[i].ljust(col_widths[i])) <NEW_LINE> line.write(' ') <NEW_LINE> <DEDENT> if row: <NEW_LINE> <INDENT> line.write(row[len(row) - 1]) <NEW_LINE> <DEDENT> self._out.write(line.getvalue().strip()) <NEW_LINE> self._out.write('\n')
A printer for printing human-readable tables.
62598f9c4e4d5625663721c9
class UserForm(forms.ModelForm): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = User <NEW_LINE> fields = ['username','email', 'password'] <NEW_LINE> exclude = ['first_name, last_name'] <NEW_LINE> widgets = { 'username':forms.TextInput(attrs={ 'class': 'form-control', 'id': 'name', 'type': 'text', 'placeholder': ' Username ', 'required': 'true', 'data-validation-required-message': 'Please enter your username' }), 'email': forms.TextInput(attrs={ 'class':'form-control', 'id':'email', 'type':'email', 'placeholder':'Email Address', 'required':'true', 'data-validation-required-message' : 'Please enter your email address.' }), 'password': forms.PasswordInput(attrs={ 'class': 'form-control', 'type': 'password', 'required': 'true', 'placeholder': 'Password', 'data-validation-required-message': 'Please enter your passoword' }), } <NEW_LINE> <DEDENT> def save(self, commit=True): <NEW_LINE> <INDENT> user = super(UserForm, self).save(commit=False) <NEW_LINE> user.set_password(self.cleaned_data['password']) <NEW_LINE> user.is_staff = True <NEW_LINE> user.is_active = True <NEW_LINE> user.save()
form for creating dashboard user
62598f9cd6c5a102081e1eea
class Strategy(Queue): <NEW_LINE> <INDENT> def __init__(self, f, order = min, sm = "u"): <NEW_LINE> <INDENT> self.A = [] <NEW_LINE> self.E = [] <NEW_LINE> self.order = order <NEW_LINE> self.f = f <NEW_LINE> self.search = sm <NEW_LINE> <DEDENT> def append(self, item, ok = False): <NEW_LINE> <INDENT> inThere = False <NEW_LINE> for e in self.E: <NEW_LINE> <INDENT> if (item.currState.getDate() == e.currState.getDate()) and (item.currState.getOrbitSet() == e.currState.getOrbitSet()): <NEW_LINE> <INDENT> inThere = True <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if inThere == False: <NEW_LINE> <INDENT> for a in self.A: <NEW_LINE> <INDENT> if (item.currState.getDate() == a.currState.getDate()) and (item.currState.getOrbitSet() == a.currState.getOrbitSet()): <NEW_LINE> <INDENT> if (item < a): <NEW_LINE> <INDENT> self.A.remove(a) <NEW_LINE> break <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> inThere = True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> if inThere == False: <NEW_LINE> <INDENT> bisect.insort(self.A, item) <NEW_LINE> <DEDENT> <DEDENT> def getSearch(self): <NEW_LINE> <INDENT> return self.search <NEW_LINE> <DEDENT> def appendOL(self, node): <NEW_LINE> <INDENT> self.E.append(node) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.A) <NEW_LINE> <DEDENT> def getNextNode(self): <NEW_LINE> <INDENT> if self.order == min: <NEW_LINE> <INDENT> x = self.A.pop(0) <NEW_LINE> return x <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.A.pop() <NEW_LINE> <DEDENT> <DEDENT> def __contains__(self, item): <NEW_LINE> <INDENT> return any(item == pair for pair in self.A) <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> for _, item in self.A: <NEW_LINE> <INDENT> if item == key: <NEW_LINE> <INDENT> return item <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __delitem__(self, key): <NEW_LINE> <INDENT> for i, (value, item) in enumerate(self.A): <NEW_LINE> <INDENT> if item == key: <NEW_LINE> <INDENT> self.A.pop(i)
Returns element based on its cost - evaluated by some function f. Order parameter determines if we return element with max/min cost value.
62598f9ce5267d203ee6b6b4
class NoMatchedServers(SpeedtestException): <NEW_LINE> <INDENT> pass
No servers matched when filtering
62598f9cf7d966606f747d8e
class Courses(db.Model): <NEW_LINE> <INDENT> __tablename__ = 'courses' <NEW_LINE> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> name = db.Column(db.String(60), unique=True) <NEW_LINE> description = db.Column(db.String(200)) <NEW_LINE> lesson_course_id = db.Column(db.Integer, db.ForeignKey('lessons.id')) <NEW_LINE> subjects = db.relationship('Subjects', backref='course_subject', lazy='dynamic') <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return '<Courses: {}>'.format(self.name)
Create a Courses table
62598f9c32920d7e50bc5dfc
class TestIntegrationAuto(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self._root = os.path.dirname(__main__.__file__) <NEW_LINE> self._name = 'vsgen-auto' <NEW_LINE> self._solution = os.path.normpath(os.path.join(self._root, self._name + '.sln')) <NEW_LINE> self.assertFalse(os.path.exists(self._solution), 'Test output solution {} already exits!'.format(self._solution)) <NEW_LINE> self._project = os.path.normpath(os.path.join(self._root, self._name + '.pyproj')) <NEW_LINE> self.assertFalse(os.path.exists(self._project), 'Test output project {} already exits!'.format(self._project)) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> if os.path.exists(self._solution): <NEW_LINE> <INDENT> os.remove(self._solution) <NEW_LINE> <DEDENT> if os.path.exists(self._project): <NEW_LINE> <INDENT> os.remove(self._project) <NEW_LINE> <DEDENT> <DEDENT> def test_auto_uccess(self): <NEW_LINE> <INDENT> result = __main__.main([__main__.__file__, 'auto', 'demo', '--root', self._root, '--name', self._name]) <NEW_LINE> self.assertEqual(result, 0)
Tests the Solution and Project Generation from a directory.
62598f9c10dbd63aa1c7095b
class FImporter(object): <NEW_LINE> <INDENT> def __init__(self, extensions=(F_EXT, F90_EXT), fbuild_dir=None): <NEW_LINE> <INDENT> self.extensions = extensions <NEW_LINE> self.fbuild_dir = fbuild_dir <NEW_LINE> <DEDENT> def find_module(self, fullname, package_path=None): <NEW_LINE> <INDENT> if fullname in sys.modules and not fargs.reload_support: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> fp, pathname, (ext,mode,ty) = imp.find_module(fullname,package_path) <NEW_LINE> if fp: fp.close() <NEW_LINE> for extension in self.extensions: <NEW_LINE> <INDENT> if pathname and pathname.endswith(extension): <NEW_LINE> <INDENT> return FLoader(fullname, pathname, fbuild_dir=self.fbuild_dir) <NEW_LINE> <DEDENT> if ty != imp.C_EXTENSION: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> fpath = os.path.splitext(pathname)[0]+extension <NEW_LINE> if os.path.isfile(fpath): <NEW_LINE> <INDENT> return FLoader(fullname, fpath, fbuild_dir=self.fbuild_dir) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except ImportError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> if '.' in fullname: <NEW_LINE> <INDENT> mod_parts = fullname.split('.') <NEW_LINE> module_name = mod_parts[-1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> module_name = fullname <NEW_LINE> <DEDENT> for extension in self.extensions: <NEW_LINE> <INDENT> f_module_name = module_name + extension <NEW_LINE> if package_path: <NEW_LINE> <INDENT> paths = package_path <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> paths = sys.path <NEW_LINE> <DEDENT> join_path = os.path.join <NEW_LINE> is_file = os.path.isfile <NEW_LINE> is_abs = os.path.isabs <NEW_LINE> abspath = os.path.abspath <NEW_LINE> sep = os.path.sep <NEW_LINE> for path in paths: <NEW_LINE> <INDENT> if not path: <NEW_LINE> <INDENT> path = os.getcwd() <NEW_LINE> <DEDENT> elif not is_abs(path): <NEW_LINE> <INDENT> path = abspath(path) <NEW_LINE> <DEDENT> if is_file(path+sep+f_module_name): <NEW_LINE> <INDENT> return FLoader(fullname, join_path(path, f_module_name), fbuild_dir=self.fbuild_dir) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> _debug("%s not found" % fullname) <NEW_LINE> return None
A meta-path importer for .f files.
62598f9c8da39b475be02f8b
class DeserializeException(Exception): <NEW_LINE> <INDENT> pass
Represents an error deserializing a value.
62598f9c3539df3088ecc05c
class LimitOffsetPagination(LimitPagination): <NEW_LINE> <INDENT> offset_arg = "offset" <NEW_LINE> def get_page(self, query, view): <NEW_LINE> <INDENT> offset = self.get_offset() <NEW_LINE> query = query.offset(offset) <NEW_LINE> return super().get_page(query, view) <NEW_LINE> <DEDENT> def get_offset(self): <NEW_LINE> <INDENT> offset = flask.request.args.get(self.offset_arg) <NEW_LINE> try: <NEW_LINE> <INDENT> return self.parse_offset(offset) <NEW_LINE> <DEDENT> except ApiError as e: <NEW_LINE> <INDENT> raise e.update({"source": {"parameter": self.offset_arg}}) <NEW_LINE> <DEDENT> <DEDENT> def parse_offset(self, offset): <NEW_LINE> <INDENT> if offset is None: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> offset = int(offset) <NEW_LINE> <DEDENT> except ValueError as e: <NEW_LINE> <INDENT> raise ApiError(400, {"code": "invalid_offset"}) from e <NEW_LINE> <DEDENT> if offset < 0: <NEW_LINE> <INDENT> raise ApiError(400, {"code": "invalid_offset"}) <NEW_LINE> <DEDENT> return offset
A pagination scheme that takes a user-specified limit and offset. This pagination scheme takes a user-specified limit and offset. It will retrieve up to the specified number of items, beginning at the specified offset.
62598f9cbe383301e025359e
class LabelConverter: <NEW_LINE> <INDENT> def __init__(self, label, name): <NEW_LINE> <INDENT> self.label = label <NEW_LINE> self.name = name <NEW_LINE> <DEDENT> def convertToXLS(self): <NEW_LINE> <INDENT> if self.label: <NEW_LINE> <INDENT> return self._convertLabel() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self._convertName() <NEW_LINE> <DEDENT> <DEDENT> def _convertLabel(self): <NEW_LINE> <INDENT> convertedLabel = html2text.html2text(self.label) <NEW_LINE> return convertedLabel <NEW_LINE> <DEDENT> def _convertName(self): <NEW_LINE> <INDENT> return self.name
Holds variable label from redcap file.
62598f9c8a43f66fc4bf1f22
class EmployeeDisplaySettingsForm(forms.ModelForm): <NEW_LINE> <INDENT> override_list_view = forms.BooleanField(label="", required=False, widget=forms.CheckboxInput()) <NEW_LINE> see_all_departments = forms.BooleanField(label="", required=False, widget=forms.CheckboxInput()) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = Employee <NEW_LINE> fields = ['override_list_view', 'see_all_departments']
Form for setting employee display settings
62598f9cd486a94d0ba2bd7c
class TestIoK8sApiCoreV1ServiceProxyOptions(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 testIoK8sApiCoreV1ServiceProxyOptions(self): <NEW_LINE> <INDENT> pass
IoK8sApiCoreV1ServiceProxyOptions unit test stubs
62598f9c0c0af96317c56129
class Plugin(BasePlugin): <NEW_LINE> <INDENT> def __call__(self): <NEW_LINE> <INDENT> params = self.ctx.params <NEW_LINE> size = self.ctx.tod_vx.shape <NEW_LINE> if params.load_noise_template: <NEW_LINE> <INDENT> mod = importlib.import_module(self.ctx.params.instrument) <NEW_LINE> freq = self.ctx.frequencies <NEW_LINE> wn_scale, cn_amp, cn_beta = mod.get_noise_params(freq) <NEW_LINE> params.white_noise_scale = wn_scale <NEW_LINE> params.color_noise_amp = cn_amp <NEW_LINE> params.color_noise_beta = cn_beta <NEW_LINE> <DEDENT> noise = get_noise(params.white_noise_scale, params.color_noise_amp, params.color_noise_beta, size) <NEW_LINE> self.ctx.tod_vx += noise <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "Add background noise"
Adds background noise to the time ordered data
62598f9c63d6d428bbee2558
class SOS1Content(Content): <NEW_LINE> <INDENT> def __init__(self, subject, operator, content_list): <NEW_LINE> <INDENT> super().__init__(subject=subject, operator=operator, children=content_list) <NEW_LINE> <DEDENT> def _get_text(self): <NEW_LINE> <INDENT> return '%s ' % self.operator + " ".join(['(%s)' % c.get_text() for c in self.children]) <NEW_LINE> <DEDENT> def get_child(self): <NEW_LINE> <INDENT> return self.children[0]
Content class in the form [subject] [operator] [sentence] NOT
62598f9c3c8af77a43b67e11
class AccountTypeRepository(metaclass=abc.ABCMeta): <NEW_LINE> <INDENT> @abc.abstractmethod <NEW_LINE> def search_account_type_by(self, ctx, limit=DEFAULT_LIMIT, offset=DEFAULT_OFFSET, account_type_id: int = None, terms: str = None) -> (List[AccountType], int): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def create_account_type(self, ctx, name=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def update_account_type(self, ctx, name=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def delete_account_type(self, ctx, name) -> None: <NEW_LINE> <INDENT> pass
Abstract interface to handle accounts.
62598f9c99cbb53fe6830c78
class iterating_colors: <NEW_LINE> <INDENT> def __init__(self, palette="matlab"): <NEW_LINE> <INDENT> if palette == "matlab": <NEW_LINE> <INDENT> self.colors = [ [0.0000, 0.4470, 0.7410], [0.8500, 0.3250, 0.0980], [0.9290, 0.6940, 0.1250], [0.4940, 0.1840, 0.5560], [0.4660, 0.6740, 0.1880], [0.3010, 0.7450, 0.9330], [0.6350, 0.0780, 0.1840]] <NEW_LINE> <DEDENT> if palette == "octave": <NEW_LINE> <INDENT> self.colors = [ [0.00000, 0.00000, 1.00000], [0.00000, 0.50000, 0.00000], [1.00000, 0.00000, 0.00000], [0.00000, 0.75000, 0.75000], [0.75000, 0.00000, 0.75000], [0.75000, 0.75000, 0.00000], [0.25000, 0.25000, 0.25000]] <NEW_LINE> <DEDENT> if palette == "long": <NEW_LINE> <INDENT> self.colors = [ [0.00, 0.00, 1.00], [0.00, 0.50, 0.00], [1.00, 0.00, 0.00], [0.00, 0.75, 0.75], [0.75, 0.00, 0.75], [0.75, 0.75, 0.00], [0.25, 0.25, 0.25], [0.75, 0.25, 0.25], [0.95, 0.95, 0.00], [0.25, 0.25, 0.75], [0.75, 0.75, 0.75], [0.00, 1.00, 0.00], [0.76, 0.57, 0.17], [0.54, 0.63, 0.22], [0.34, 0.57, 0.92], [1.00, 0.10, 0.60], [0.88, 0.75, 0.73], [0.10, 0.49, 0.47], [0.66, 0.34, 0.65], [0.99, 0.41, 0.23]] <NEW_LINE> <DEDENT> self.current_index = 0 <NEW_LINE> <DEDENT> def get_next(self): <NEW_LINE> <INDENT> m = len(self.colors) <NEW_LINE> color = self.colors[self.current_index % m] <NEW_LINE> RGB_color = [round(x*255.45) for x in color] <NEW_LINE> self.current_index += 1 <NEW_LINE> return tuple(RGB_color) <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self.current_index = 0
This class is made to mimic matlab-like color plotting behavior. Calling get_next() method returns new color in list, without hazzle. By default colorset is same as in matlab
62598f9ca17c0f6771d5bfe2
class TestIssue85(common.FunctionalTestCase): <NEW_LINE> <INDENT> def test_disabling_tenant_disables_token(self): <NEW_LINE> <INDENT> tenant = self.create_tenant().json['tenant'] <NEW_LINE> password = common.unique_str() <NEW_LINE> user = self.create_user(user_password=password, tenant_id=tenant['id']).json['user'] <NEW_LINE> user['password'] = password <NEW_LINE> user_token = self.authenticate(user['name'], user['password'], tenant['id']).json['access']['token']['id'] <NEW_LINE> tenant_id = self.get_token(user_token). json['access']['token']['tenant']['id'] <NEW_LINE> self.assertEqual(tenant_id, tenant['id']) <NEW_LINE> r = self.admin_request(method='PUT', path='/tenants/%s' % tenant['id'], as_json={ 'tenant': { 'name': tenant['name'], 'description': 'description', 'enabled': False}}) <NEW_LINE> self.assertFalse(r.json['tenant']['enabled']) <NEW_LINE> r = self.admin_request(path='/tokens/%s?belongsTo=%s' % (user_token, tenant['id']), assert_status=403) <NEW_LINE> self.assertTrue(r.json['tenantDisabled'], 'Tenant is disabled')
Illustrates github issue #85
62598f9c3539df3088ecc05d
class Taxcode(Serializable, Base): <NEW_LINE> <INDENT> __tablename__ = "taxcodes" <NEW_LINE> __serializable__ = ["id", "title", "effective_at", "expired_at", "shared", "body", "created_at", "updated_at"] <NEW_LINE> id = Column(CHAR(16), primary_key=True) <NEW_LINE> title = Column(String, nullable=False) <NEW_LINE> effective_at = Column(DateTime, nullable=False) <NEW_LINE> expired_at = Column(DateTime, nullable=False) <NEW_LINE> shared = Column(Boolean, nullable=False) <NEW_LINE> body = Column(String, nullable=False) <NEW_LINE> created_at = Column(DateTime, nullable=False, default=func.now()) <NEW_LINE> updated_at = Column(DateTime, nullable=False, default=func.now(), onupdate=func.now())
Taxcode to be executed per product purchased
62598f9c15baa72349461d2b
class ValidationError(Exception): <NEW_LINE> <INDENT> def __init__(self, message, code=None, params=None): <NEW_LINE> <INDENT> import operator <NEW_LINE> from django.utils.encoding import force_text <NEW_LINE> if isinstance(message, dict): <NEW_LINE> <INDENT> self.message_dict = message <NEW_LINE> message = reduce(operator.add, message.values()) <NEW_LINE> <DEDENT> if isinstance(message, list): <NEW_LINE> <INDENT> self.messages = [force_text(msg) for msg in message] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.code = code <NEW_LINE> self.params = params <NEW_LINE> message = force_text(message) <NEW_LINE> self.messages = [message] <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> if hasattr(self, 'message_dict'): <NEW_LINE> <INDENT> return repr(self.message_dict) <NEW_LINE> <DEDENT> return repr(self.messages) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> if hasattr(self, 'message_dict'): <NEW_LINE> <INDENT> return 'ValidationError(%s)' % repr(self.message_dict) <NEW_LINE> <DEDENT> return 'ValidationError(%s)' % repr(self.messages) <NEW_LINE> <DEDENT> def update_error_dict(self, error_dict): <NEW_LINE> <INDENT> if hasattr(self, 'message_dict'): <NEW_LINE> <INDENT> if error_dict: <NEW_LINE> <INDENT> for k, v in self.message_dict.items(): <NEW_LINE> <INDENT> error_dict.setdefault(k, []).extend(v) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> error_dict = self.message_dict <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> error_dict[NON_FIELD_ERRORS] = self.messages <NEW_LINE> <DEDENT> return error_dict
An error while validating data.
62598f9c5f7d997b871f92b2
class PageSearchForm(forms.Form): <NEW_LINE> <INDENT> title = forms.CharField(required=False, label="Title")
Search form to filter pages by *title.
62598f9c6e29344779b00403
class CSRFProtectedSchema(colander.MappingSchema): <NEW_LINE> <INDENT> csrf_token = colander.SchemaNode( colander.String(), name="csrf_token", validator=validate_csrf_token, )
A mixin class to validate csrf tokens.
62598f9cbaa26c4b54d4f05a
class MakoTemplate(TemplateBase): <NEW_LINE> <INDENT> _template = None <NEW_LINE> def __init__(self, template): <NEW_LINE> <INDENT> super(MakoTemplate, self).__init__() <NEW_LINE> self._template = template <NEW_LINE> <DEDENT> def render(self, bindings): <NEW_LINE> <INDENT> buf = StringIO() <NEW_LINE> _binding_dict = dict(bindings) <NEW_LINE> _binding_dict['template'] = self <NEW_LINE> context = ExternalMakoContext(buf, **_binding_dict) <NEW_LINE> try: <NEW_LINE> <INDENT> self._template.render_context(context) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> logger.error('Rendering failed') <NEW_LINE> raise <NEW_LINE> <DEDENT> return buf.getvalue() <NEW_LINE> <DEDENT> render.__doc__ = TemplateBase.render.__doc__
Wrapper for mako templates Members: _template -- Mako template
62598f9c498bea3a75a578c8
class TestGetDevicesPE(APITestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.response = self.client.get('/getDevicesPE/') <NEW_LINE> <DEDENT> def test_GetPE_received_200_status_code(self): <NEW_LINE> <INDENT> self.assertEqual(self.response.status_code, status.HTTP_200_OK) <NEW_LINE> <DEDENT> def test_GetPE_infoRecived(self): <NEW_LINE> <INDENT> info=self.response.content <NEW_LINE> info=info.decode() <NEW_LINE> busqueda=info.find('{"pe":') <NEW_LINE> if(busqueda<0): <NEW_LINE> <INDENT> busqueda=True <NEW_LINE> <DEDENT> self.assertEqual(busqueda,True)
Verify GET PE DEVICES LODED ON NSO via Microservices API
62598f9cd268445f26639a57
class InterpreterInterface(BaseInterpreterInterface): <NEW_LINE> <INDENT> def __init__(self, host, client_port): <NEW_LINE> <INDENT> self.client_port = client_port <NEW_LINE> self.host = host <NEW_LINE> self.interpreter = PyDevFrontEnd() <NEW_LINE> self._input_error_printed = False <NEW_LINE> <DEDENT> def doAddExec(self, line): <NEW_LINE> <INDENT> return bool(self.interpreter.addExec(line)) <NEW_LINE> <DEDENT> def getNamespace(self): <NEW_LINE> <INDENT> return self.interpreter.getNamespace() <NEW_LINE> <DEDENT> def getCompletions(self, text, act_tok): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ipython_completion = text.startswith('%') <NEW_LINE> if not ipython_completion: <NEW_LINE> <INDENT> s = re.search(r'\bcd\b', text) <NEW_LINE> if s is not None and s.start() == 0: <NEW_LINE> <INDENT> ipython_completion = True <NEW_LINE> <DEDENT> <DEDENT> if ipython_completion: <NEW_LINE> <INDENT> TYPE_LOCAL = '9' <NEW_LINE> _line, completions = self.interpreter.complete(text) <NEW_LINE> ret = [] <NEW_LINE> append = ret.append <NEW_LINE> for completion in completions: <NEW_LINE> <INDENT> append((completion, '', '', TYPE_LOCAL)) <NEW_LINE> <DEDENT> return ret <NEW_LINE> <DEDENT> from _pydev_completer import Completer <NEW_LINE> completer = Completer(self.getNamespace(), None) <NEW_LINE> return completer.complete(act_tok) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> import traceback;traceback.print_exc() <NEW_LINE> return [] <NEW_LINE> <DEDENT> <DEDENT> def close(self): <NEW_LINE> <INDENT> sys.exit(0)
The methods in this class should be registered in the xml-rpc server.
62598f9c004d5f362081eed1
class TiledElement(object): <NEW_LINE> <INDENT> allow_duplicate_names = False <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.properties = dict() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_xml_string(cls, xml_string): <NEW_LINE> <INDENT> return cls().parse_xml(ElementTree.fromstring(xml_string)) <NEW_LINE> <DEDENT> def _cast_and_set_attributes_from_node_items(self, items): <NEW_LINE> <INDENT> for key, value in items: <NEW_LINE> <INDENT> casted_value = types[key](value) <NEW_LINE> setattr(self, key, casted_value) <NEW_LINE> <DEDENT> <DEDENT> def _contains_invalid_property_name(self, items): <NEW_LINE> <INDENT> if self.allow_duplicate_names: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> for k, v in items: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _hasattr = hasattr(self, k) <NEW_LINE> <DEDENT> except UnicodeError: <NEW_LINE> <INDENT> _hasattr = hasattr(self, k.encode('utf-8')) <NEW_LINE> <DEDENT> if _hasattr: <NEW_LINE> <INDENT> msg = duplicate_name_fmt.format(k, self.__class__.__name__, self.name) <NEW_LINE> logger.error(msg) <NEW_LINE> return True <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _log_property_error_message(): <NEW_LINE> <INDENT> msg = 'Some name are reserved for {0} objects and cannot be used.' <NEW_LINE> logger.error(msg) <NEW_LINE> <DEDENT> def _set_properties(self, node): <NEW_LINE> <INDENT> self._cast_and_set_attributes_from_node_items(node.items()) <NEW_LINE> properties = parse_properties(node) <NEW_LINE> if (not self.allow_duplicate_names and self._contains_invalid_property_name(properties.items())): <NEW_LINE> <INDENT> self._log_property_error_message() <NEW_LINE> raise ValueError("Reserved names and duplicate names are not allowed. Please rename your property inside the .tmx-file") <NEW_LINE> <DEDENT> self.properties = properties <NEW_LINE> <DEDENT> def __getattr__(self, item): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.properties[item] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise AttributeError <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<{0}: "{1}">'.format(self.__class__.__name__, self.name)
Base class for all pytmx types
62598f9c8e7ae83300ee8e47
class CommonParserOptions(object): <NEW_LINE> <INDENT> def addOptions(self): <NEW_LINE> <INDENT> parser=OptionGroup(self.parser, "Parser Options", "Options that control the behaviour of the parser for the dictionary files") <NEW_LINE> self.parser.add_option_group(parser) <NEW_LINE> parser.add_option("--debug-parser", action="store_true", default=None, dest="debugParser" ,help="Debugs the parser") <NEW_LINE> parser.add_option("--no-header", action="store_true", default=False, dest="noHeader", help="Don't expect a header while parsing") <NEW_LINE> parser.add_option("--no-body", action="store_true", default=False, dest="noBody", help="Don't expect a body while parsing (only parse the header)") <NEW_LINE> parser.add_option("--boundary", action="store_true", default=False, dest="boundaryDict", help="Expect that this file is a boundary dictionary") <NEW_LINE> parser.add_option("--list-only", action="store_true", default=False, dest="listDict", help="Expect that this file only contains a list") <NEW_LINE> parser.add_option("--list-with-header", action="store_true", default=False, dest="listDictWithHeader", help="Expect that this file only contains a list with a header") <NEW_LINE> parser.add_option("--do-macro-expansion", action="store_true", default=False, dest="doMacros", help="Expand macros with $ and #") <NEW_LINE> parser.add_option("--no-preserve-comments", action="store_false", default=True, dest="preserveComments", help="Don't preserve comments when parsing")
The class that defines the options for the parser
62598f9c851cf427c66b8070
class FlagAction(argparse.Action): <NEW_LINE> <INDENT> def __init__(self, option_strings, dest, nargs=None, **kwargs): <NEW_LINE> <INDENT> options = [opt.strip("-") for opt in option_strings] <NEW_LINE> yes_options = [opt for opt in options if not opt.startswith("no-")] <NEW_LINE> no_options = [opt[3:] for opt in options if opt.startswith("no-")] <NEW_LINE> if sorted(yes_options) != sorted(no_options): <NEW_LINE> <INDENT> raise ValueError("There should be one --no option for every option value.") <NEW_LINE> <DEDENT> super().__init__(option_strings, dest, nargs=0, **kwargs) <NEW_LINE> <DEDENT> def __call__(self, parser, namespace, values, option_string=None): <NEW_LINE> <INDENT> if option_string.startswith("--no"): <NEW_LINE> <INDENT> value = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> value = True <NEW_LINE> <DEDENT> setattr(namespace, self.dest, value)
Facilitates --flag, --no-flag arguments Usage:: parser.add_argument( '--flag', '--no-flag', action=FlagAction, default=True, help='whether to enable flag' ) Which allows you to do:: $ command $ command --flag $ command --no-flag And the help works nicely, too:: $ command --help ... optional arguments: --flag, --no-flag whether to enable flag
62598f9c925a0f43d25e7de5
class MongoTrackerStore(TrackerStore): <NEW_LINE> <INDENT> def __init__( self, domain: Domain, host: Optional[Text] = "mongodb://localhost:27017", db: Optional[Text] = "rasa", username: Optional[Text] = None, password: Optional[Text] = None, auth_source: Optional[Text] = "admin", collection: Optional[Text] = "conversations", event_broker: Optional[EventBroker] = None, ): <NEW_LINE> <INDENT> from pymongo.database import Database <NEW_LINE> from pymongo import MongoClient <NEW_LINE> self.client = MongoClient( host, username=username, password=password, authSource=auth_source, connect=False, ) <NEW_LINE> self.db = Database(self.client, db) <NEW_LINE> self.collection = collection <NEW_LINE> super().__init__(domain, event_broker) <NEW_LINE> self._ensure_indices() <NEW_LINE> <DEDENT> @property <NEW_LINE> def conversations(self): <NEW_LINE> <INDENT> return self.db[self.collection] <NEW_LINE> <DEDENT> def _ensure_indices(self): <NEW_LINE> <INDENT> self.conversations.create_index("sender_id") <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _current_tracker_state_without_events(tracker: DialogueStateTracker) -> Dict: <NEW_LINE> <INDENT> state = tracker.current_state(EventVerbosity.ALL) <NEW_LINE> state.pop("events", None) <NEW_LINE> return state <NEW_LINE> <DEDENT> def save(self, tracker, timeout=None): <NEW_LINE> <INDENT> if self.event_broker: <NEW_LINE> <INDENT> self.stream_events(tracker) <NEW_LINE> <DEDENT> additional_events = self._additional_events(tracker) <NEW_LINE> self.conversations.update_one( {"sender_id": tracker.sender_id}, { "$set": self._current_tracker_state_without_events(tracker), "$push": { "events": {"$each": [e.as_dict() for e in additional_events]} }, }, upsert=True, ) <NEW_LINE> <DEDENT> def _additional_events(self, tracker: DialogueStateTracker) -> Iterator: <NEW_LINE> <INDENT> stored = self.conversations.find_one({"sender_id": tracker.sender_id}) or {} <NEW_LINE> number_events_since_last_session = len( self._events_since_last_session_start(stored) ) <NEW_LINE> return itertools.islice( tracker.events, number_events_since_last_session, len(tracker.events) ) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _events_since_last_session_start(serialised_tracker: Dict) -> List[Dict]: <NEW_LINE> <INDENT> events = [] <NEW_LINE> for event in reversed(serialised_tracker.get("events", [])): <NEW_LINE> <INDENT> events.append(event) <NEW_LINE> if event["event"] == SessionStarted.type_name: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> return list(reversed(events)) <NEW_LINE> <DEDENT> def retrieve(self, sender_id): <NEW_LINE> <INDENT> stored = self.conversations.find_one({"sender_id": sender_id}) <NEW_LINE> if stored is None and sender_id.isdigit(): <NEW_LINE> <INDENT> from pymongo import ReturnDocument <NEW_LINE> stored = self.conversations.find_one_and_update( {"sender_id": int(sender_id)}, {"$set": {"sender_id": str(sender_id)}}, return_document=ReturnDocument.AFTER, ) <NEW_LINE> <DEDENT> if stored is not None: <NEW_LINE> <INDENT> events = self._events_since_last_session_start(stored) <NEW_LINE> return DialogueStateTracker.from_dict(sender_id, events, self.domain.slots) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def keys(self) -> Iterable[Text]: <NEW_LINE> <INDENT> return [c["sender_id"] for c in self.conversations.find()]
Stores conversation history in Mongo Property methods: conversations: returns the current conversation
62598f9cac7a0e7691f722b4
class MediaRef(SecondaryObject, PrivacyBase, CitationBase, NoteBase, RefBase, AttributeBase): <NEW_LINE> <INDENT> def __init__(self, source=None): <NEW_LINE> <INDENT> PrivacyBase.__init__(self, source) <NEW_LINE> CitationBase.__init__(self, source) <NEW_LINE> NoteBase.__init__(self, source) <NEW_LINE> RefBase.__init__(self, source) <NEW_LINE> AttributeBase.__init__(self, source) <NEW_LINE> if source: <NEW_LINE> <INDENT> self.rect = source.rect <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.rect = None <NEW_LINE> <DEDENT> <DEDENT> def serialize(self): <NEW_LINE> <INDENT> return (PrivacyBase.serialize(self), CitationBase.serialize(self), NoteBase.serialize(self), AttributeBase.serialize(self), RefBase.serialize(self), self.rect) <NEW_LINE> <DEDENT> def unserialize(self, data): <NEW_LINE> <INDENT> (privacy, citation_list, note_list,attribute_list,ref,self.rect) = data <NEW_LINE> PrivacyBase.unserialize(self, privacy) <NEW_LINE> CitationBase.unserialize(self, citation_list) <NEW_LINE> NoteBase.unserialize(self, note_list) <NEW_LINE> AttributeBase.unserialize(self, attribute_list) <NEW_LINE> RefBase.unserialize(self, ref) <NEW_LINE> return self <NEW_LINE> <DEDENT> def get_text_data_child_list(self): <NEW_LINE> <INDENT> return self.attribute_list <NEW_LINE> <DEDENT> def get_citation_child_list(self): <NEW_LINE> <INDENT> return self.attribute_list <NEW_LINE> <DEDENT> def get_note_child_list(self): <NEW_LINE> <INDENT> return self.attribute_list <NEW_LINE> <DEDENT> def get_referenced_handles(self): <NEW_LINE> <INDENT> ret = self.get_referenced_note_handles() + self.get_referenced_citation_handles() <NEW_LINE> if self.ref: <NEW_LINE> <INDENT> ret += [('MediaObject', self.ref)] <NEW_LINE> <DEDENT> return ret <NEW_LINE> <DEDENT> def get_handle_referents(self): <NEW_LINE> <INDENT> return self.get_citation_child_list() <NEW_LINE> <DEDENT> def is_equivalent(self, other): <NEW_LINE> <INDENT> if self.ref != other.ref or self.rect != other.rect: <NEW_LINE> <INDENT> return DIFFERENT <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self.is_equal(other): <NEW_LINE> <INDENT> return IDENTICAL <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return EQUAL <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def merge(self, acquisition): <NEW_LINE> <INDENT> self._merge_privacy(acquisition) <NEW_LINE> self._merge_attribute_list(acquisition) <NEW_LINE> self._merge_citation_list(acquisition) <NEW_LINE> self._merge_note_list(acquisition) <NEW_LINE> <DEDENT> def set_rectangle(self, coord): <NEW_LINE> <INDENT> self.rect = coord <NEW_LINE> <DEDENT> def get_rectangle(self): <NEW_LINE> <INDENT> return self.rect
Media reference class.
62598f9c9c8ee82313040044
class MessageInputCommandTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def testRun(self): <NEW_LINE> <INDENT> c = MessageInputCommand() <NEW_LINE> c.params.partner = PartnerAuthInfo(None) <NEW_LINE> c.params.message = TransitMessage(serialized={ 'text' : u'Is this SPAM?'}) <NEW_LINE> return c.run().addCallback(lambda _: self.assertEqual('UNKNOWN', c.result.result))
Тест на L{spamfighter.api.message.input.MessageInputCommand}.
62598f9c3539df3088ecc05e
class VertexDefinedObjectFromValues(VertexDefinedObject): <NEW_LINE> <INDENT> def __init__(self,x,y,isClosed,samples_vertices_dict): <NEW_LINE> <INDENT> dummyvert=[] <NEW_LINE> for i in range(np.size(x)): <NEW_LINE> <INDENT> dummyvert.append(fzy.TrapezoidalFuzzyNumber()) <NEW_LINE> <DEDENT> VertexDefinedObject.__init__(self,x,y,dummyvert,dummyvert,isClosed) <NEW_LINE> self._realizations={key:None for key in samples_vertices_dict} <NEW_LINE> for k in self._realizations: <NEW_LINE> <INDENT> self._realizations[k]=[np.r_[val] for val in samples_vertices_dict[k]] <NEW_LINE> <DEDENT> <DEDENT> def plotFuzzyNumbers(self,n=-1,showAlphaCuts=True, showAcutRealizations=[],rlzColors=False): <NEW_LINE> <INDENT> VertexDefinedObject.plotFuzzyNumbers(self,n=n, showAlphaCuts=showAlphaCuts,rlzColors=rlzColors, showAcutRealizations=[],showMembFcn=False) <NEW_LINE> <DEDENT> def generateRealizations(self,n,alphaCuts,method): <NEW_LINE> <INDENT> raise NotImplementedError("generateRealizations isn't supported for this type of object")
A vertex-defined object, constructed from previously generated values. - *x*: A numpy array of x coordinates, length N - *y*: A numpy array of y coordinates, length N - *isClosed*: whether the object will be treated as having a closed boundary. - *samples_vertices_dict*: a dictionary holding samples of the fuzzy vertices. The first half of the array are the x vertex values and the other half the y. {<alpha-cut>:numpy array of length 2N, ...} Only 1 sample of each vertex is allowed per alpha cut.
62598f9ca79ad16197769e0c
class VMSizeProperties(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'v_cpus_available': {'key': 'vCPUsAvailable', 'type': 'int'}, 'v_cpus_per_core': {'key': 'vCPUsPerCore', 'type': 'int'}, } <NEW_LINE> def __init__( self, *, v_cpus_available: Optional[int] = None, v_cpus_per_core: Optional[int] = None, **kwargs ): <NEW_LINE> <INDENT> super(VMSizeProperties, self).__init__(**kwargs) <NEW_LINE> self.v_cpus_available = v_cpus_available <NEW_LINE> self.v_cpus_per_core = v_cpus_per_core
Specifies VM Size Property settings on the virtual machine. :ivar v_cpus_available: Specifies the number of vCPUs available for the VM. :code:`<br>`:code:`<br>` When this property is not specified in the request body the default behavior is to set it to the value of vCPUs available for that VM size exposed in api response of `List all available virtual machine sizes in a region <https://docs.microsoft.com/en-us/rest/api/compute/resource-skus/list>`_ . :vartype v_cpus_available: int :ivar v_cpus_per_core: Specifies the vCPU to physical core ratio. :code:`<br>`:code:`<br>` When this property is not specified in the request body the default behavior is set to the value of vCPUsPerCore for the VM Size exposed in api response of `List all available virtual machine sizes in a region <https://docs.microsoft.com/en-us/rest/api/compute/resource-skus/list>`_ :code:`<br>`:code:`<br>` Setting this property to 1 also means that hyper-threading is disabled. :vartype v_cpus_per_core: int
62598f9c30dc7b766599f5f5
class VolumeSnapshotToolbar(View): <NEW_LINE> <INDENT> policy = Dropdown('Policy') <NEW_LINE> download = Dropdown('Download') <NEW_LINE> view_selector = View.nested(ItemsToolBarViewSelector)
The toolbar on the Volume Snapshot page
62598f9c090684286d5935ae
class Proposal(db.Model): <NEW_LINE> <INDENT> device = db.ReferenceProperty(Device) <NEW_LINE> created = db.DateTimeProperty(auto_now_add=True)
A temporary proposal to connect forever
62598f9c0c0af96317c5612c
class BaseImage(object): <NEW_LINE> <INDENT> def __init__(self, docker_client, image_opts): <NEW_LINE> <INDENT> self._docker_client = docker_client <NEW_LINE> self._image_opts = image_opts <NEW_LINE> self._id = None <NEW_LINE> <DEDENT> def Build(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def Remove(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @property <NEW_LINE> def id(self): <NEW_LINE> <INDENT> return self._id <NEW_LINE> <DEDENT> @property <NEW_LINE> def tag(self): <NEW_LINE> <INDENT> return self._image_opts.tag <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> self.Build() <NEW_LINE> return self <NEW_LINE> <DEDENT> def __exit__(self, type, value, traceback): <NEW_LINE> <INDENT> self.Remove() <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> self.Remove()
Abstract base class for Docker images.
62598f9c656771135c48942b
class User: <NEW_LINE> <INDENT> user_list = [] <NEW_LINE> def __init__(self, username, password): <NEW_LINE> <INDENT> self.username = username <NEW_LINE> self.password = password <NEW_LINE> <DEDENT> def save_user(self): <NEW_LINE> <INDENT> User.user_list.append(self) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def display_user(cls): <NEW_LINE> <INDENT> return cls.user_list <NEW_LINE> <DEDENT> def delete_user(self): <NEW_LINE> <INDENT> User.user_list.remove(self)
Create User class that generates new instances of a user
62598f9c56ac1b37e6301f93
class Vis(models.Model): <NEW_LINE> <INDENT> project = models.ForeignKey(Project) <NEW_LINE> user = models.ForeignKey(User) <NEW_LINE> name = models.CharField(max_length=50) <NEW_LINE> personIn = models.BooleanField(default = 0) <NEW_LINE> locationIn = models.BooleanField(default = 0) <NEW_LINE> phoneIn = models.BooleanField(default = 0) <NEW_LINE> dateIn = models.BooleanField(default = 0) <NEW_LINE> orgIn = models.BooleanField(default = 0) <NEW_LINE> miscIn = models.BooleanField(default = 0) <NEW_LINE> create_time = models.DateTimeField('date published')
A Visualzaiton model
62598f9c0a50d4780f705182
class Attention(nn.Module): <NEW_LINE> <INDENT> def forward(self, query, key, value, mask=None, dropout=None): <NEW_LINE> <INDENT> scores = torch.exp(torch.matmul(query, key.transpose(-2, -1))) / math.sqrt(query.size(-1)) <NEW_LINE> if mask is not None: <NEW_LINE> <INDENT> scores = scores.masked_fill(mask == 0, -1e9) <NEW_LINE> <DEDENT> p_attn = F.softmax(scores, dim=-1) <NEW_LINE> if dropout is not None: <NEW_LINE> <INDENT> p_attn = dropout(p_attn) <NEW_LINE> <DEDENT> return torch.matmul(p_attn, value), p_attn
Compute 'Scaled Dot Product Attention
62598f9c6aa9bd52df0d4c77
class MockKey(object): <NEW_LINE> <INDENT> def __init__(self, bucket=None, name=None): <NEW_LINE> <INDENT> self.bucket = bucket <NEW_LINE> self.name = name <NEW_LINE> <DEDENT> def set_contents_from_file(self, f): <NEW_LINE> <INDENT> mock_s3_fs = self.bucket.connection.mock_s3_fs <NEW_LINE> f.seek(0) <NEW_LINE> contents = f.read() <NEW_LINE> mock_s3_fs[self.bucket.name][self.name] = contents
Mock out boto.s3.Key
62598f9c32920d7e50bc5e00
class Configurator(object): <NEW_LINE> <INDENT> _instance = None <NEW_LINE> def __call__(self): <NEW_LINE> <INDENT> if not self._instance: <NEW_LINE> <INDENT> self._instance = self() <NEW_LINE> <DEDENT> return self._instance <NEW_LINE> <DEDENT> def __init__(self): <NEW_LINE> <INDENT> self.__dict__['_config'] = {} <NEW_LINE> <DEDENT> def __getattr__(self, k): <NEW_LINE> <INDENT> if hasattr(self._config, k): <NEW_LINE> <INDENT> return getattr(self._config, k) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.__dict__[k] <NEW_LINE> <DEDENT> <DEDENT> def __setattr__(self, k, v): <NEW_LINE> <INDENT> if hasattr(self._config, k): <NEW_LINE> <INDENT> setattr(self._config, k, v) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.__dict__[k] = v <NEW_LINE> <DEDENT> <DEDENT> def __getitem__(self, k): <NEW_LINE> <INDENT> return self._config[k] <NEW_LINE> <DEDENT> def __setitem__(self, k, v): <NEW_LINE> <INDENT> self._config[k] = v
Has only one instance all the time, and provides access to twisted usage.Options @ivar _instance: Configurator instance, will be retruned that one instead of creating
62598f9c3eb6a72ae038a3ea
class FileHandler(): <NEW_LINE> <INDENT> def __init__(self, file_name): <NEW_LINE> <INDENT> self.file_name = file_name <NEW_LINE> <DEDENT> def read_file_bytes(self): <NEW_LINE> <INDENT> with open(self.file_name, "rb") as data_file: <NEW_LINE> <INDENT> data = data_file.read() <NEW_LINE> <DEDENT> return data <NEW_LINE> <DEDENT> def write_bytes_to_file(self, data): <NEW_LINE> <INDENT> if not isinstance(data, bytes): <NEW_LINE> <INDENT> raise TypeError("Data to be written must be byte string") <NEW_LINE> <DEDENT> with open(self.file_name, "wb") as data_file: <NEW_LINE> <INDENT> data_file.write(data) <NEW_LINE> <DEDENT> <DEDENT> def read_file_lines(self): <NEW_LINE> <INDENT> nop <NEW_LINE> <DEDENT> def write_lines_to_file(self, lines): <NEW_LINE> <INDENT> nop <NEW_LINE> <DEDENT> def read_file_line(self): <NEW_LINE> <INDENT> nop <NEW_LINE> <DEDENT> def write_line_to_file(self, line): <NEW_LINE> <INDENT> nop
Handles io operations for a file
62598f9cd268445f26639a58
class Solution: <NEW_LINE> <INDENT> def kDistinctCharacters(self, s, k): <NEW_LINE> <INDENT> lens = len(s) <NEW_LINE> count = 0 <NEW_LINE> sipre=-1 <NEW_LINE> si=0 <NEW_LINE> ei=0 <NEW_LINE> cache={} <NEW_LINE> while si <= ei: <NEW_LINE> <INDENT> if len(cache.keys()) < k and ei < lens: <NEW_LINE> <INDENT> if s[ei] not in cache: <NEW_LINE> <INDENT> cache[s[ei]] = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cache[s[ei]] += 1 <NEW_LINE> <DEDENT> ei+=1 <NEW_LINE> <DEDENT> elif len(cache.keys()) == k: <NEW_LINE> <INDENT> cache[s[si]]-=1 <NEW_LINE> if cache[s[si]] == 0: <NEW_LINE> <INDENT> cache.pop(s[si]) <NEW_LINE> count+=(si-sipre)*(lens-ei+1) <NEW_LINE> sipre = si <NEW_LINE> <DEDENT> si+=1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> return count
@param s: a string @param k: an integer @return: the number of substrings there are that contain at least k distinct characters
62598f9c8da39b475be02f8f
class LatticeGenotypePhenotypeMap(GenotypePhenotypeMap): <NEW_LINE> <INDENT> def __init__(self, wildtype, mutations, conformations=None, target=None, temp=1.0, phenotype_type="stability", **kwargs): <NEW_LINE> <INDENT> genotypes = mutations_to_genotypes(wildtype, mutations) <NEW_LINE> self.latticeproteins = LatticeProteins( genotypes, conformations=conformations, target=target ) <NEW_LINE> self._phenotype_type = phenotype_type <NEW_LINE> phenotypes = getattr(self.latticeproteins, phenotype_type) <NEW_LINE> super(LatticeGenotypePhenotypeMap, self).__init__( wildtype, genotypes, phenotypes, mutations=mutations ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def phenotype_type(self): <NEW_LINE> <INDENT> return self._phenotype_type <NEW_LINE> <DEDENT> @phenotype_type.setter <NEW_LINE> def phenotype_type(self, phenotype_type): <NEW_LINE> <INDENT> self._phenotype_type = phenotype_type <NEW_LINE> self.data['phenotypes'] = getattr(self.latticeproteins, phenotype_type) <NEW_LINE> <DEDENT> def print_sequences(self, sequences): <NEW_LINE> <INDENT> seq2conf = self.map("genotypes", "confs") <NEW_LINE> for s in sequences: <NEW_LINE> <INDENT> PrintConformation(s, seq2conf[s])
Construct a genotype-phenotype map from 2d protein lattice models. Genotypes are represented by Parameters ---------- wildtype : str Wildtype sequence mutant : str Mutant sequence target_conf : str (optional) String that describes the target conformation to fold each sequence to. temperature : float temperature parameter for calculating folding stability. n_conformations : int number of conformations that should be in space (raise error if more) conformations : latticeproteins.conformations.Conformations object latticeproteins.conformations object for all conformations for strings with len(wildtype) Attributes ---------- temperature : float temperature of the system target_conf : string target conformation for all sequences interaction_energies : dictionary mapping all contact pairs to their corresponding energies energies : array of floats native energies of all sequences stabilities : array of floats stabilities of native states for all sequences fitnesses : array of floats fitnesses of all sequences conformations : array of strings native conformations of all sequences partition_sum : array of float boltzmann weighted sum of all conformation/energies fold : boolean folded or not? For more attributes, see GenotypePhenotypeMap in `gpmap` package.
62598f9c1f5feb6acb1629cc
class HTMLClusterViewModel(BaseClusterViewModel, HTMLViewModel): <NEW_LINE> <INDENT> def get_css(self, **kwargs): <NEW_LINE> <INDENT> return _css_cluster_colors() <NEW_LINE> <DEDENT> def on_select(self, cluster_ids, **kwargs): <NEW_LINE> <INDENT> self.update(cluster_ids=cluster_ids) <NEW_LINE> <DEDENT> def on_cluster(self, up): <NEW_LINE> <INDENT> self.update(cluster_ids=self._cluster_ids, up=up)
HTML view model that displays per-cluster information.
62598f9cf8510a7c17d7e04d
class ParseCommas(argparse.Action): <NEW_LINE> <INDENT> def __init__(self, option_strings, dest, nargs=None, **kwargs): <NEW_LINE> <INDENT> if nargs is not None: <NEW_LINE> <INDENT> raise ValueError('nargs not allowed for ParseCommas') <NEW_LINE> <DEDENT> super(ParseCommas, self).__init__(option_strings, dest, **kwargs) <NEW_LINE> <DEDENT> def __call__(self, parser, namespace, values, option_string=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> assert type(values) is str <NEW_LINE> <DEDENT> except AssertionError: <NEW_LINE> <INDENT> raise TypeError('{0} is not a string'.format(values)) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> arguments = filter(None, values.split(',')) <NEW_LINE> <DEDENT> except AssertionError: <NEW_LINE> <INDENT> raise ValueError('{0} could not be parsed by commas' .format(values)) <NEW_LINE> <DEDENT> setattr(namespace, self.dest, arguments)
Argparse Action that parses arguments by commas Attributes: option_strings (list): list of str giving command line flags that call this action dest (str): Namespace reference to value nargs (bool): True if multiple arguments specified **kwargs (various): optional arguments to pass to super call
62598f9c63d6d428bbee255c
class BasicInfo(base.BaseUnivInfo): <NEW_LINE> <INDENT> data_filename = BASIC_DATA_FILENAME <NEW_LINE> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self.data['name'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def aliases(self): <NEW_LINE> <INDENT> return self.data['aliases'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def alias(self): <NEW_LINE> <INDENT> return self.aliases[0] <NEW_LINE> <DEDENT> @property <NEW_LINE> def address(self): <NEW_LINE> <INDENT> return self.data['address'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def postal(self): <NEW_LINE> <INDENT> return self.data['postal'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def homepage(self): <NEW_LINE> <INDENT> return self.data['homepage']
宿舍信息对象.
62598f9c55399d3f056262cd
class ThermoCentralDatabaseInterface(object): <NEW_LINE> <INDENT> def __init__(self, host, port, username, password): <NEW_LINE> <INDENT> self.host = host <NEW_LINE> self.port = port <NEW_LINE> self.username = username <NEW_LINE> self.password = password <NEW_LINE> self.client = self.connect() <NEW_LINE> <DEDENT> def connect(self): <NEW_LINE> <INDENT> import pymongo <NEW_LINE> remote_address = 'mongodb://{0}:{1}@{2}/thermoCentralDB'.format(self.username, self.password, self.host) <NEW_LINE> client = pymongo.MongoClient(remote_address, self.port, serverSelectionTimeoutMS=2000) <NEW_LINE> try: <NEW_LINE> <INDENT> client.server_info() <NEW_LINE> print("\nConnection success to Thermo Central Database!\n") <NEW_LINE> return client <NEW_LINE> <DEDENT> except (pymongo.errors.ServerSelectionTimeoutError, pymongo.errors.OperationFailure): <NEW_LINE> <INDENT> print("\nConnection failure to Thermo Central Database...") <NEW_LINE> return None
A class for interfacing with thermo central database.
62598f9c596a897236127a2b
@python_2_unicode_compatible <NEW_LINE> class BaseProduct(models.Model): <NEW_LINE> <INDENT> title = models.CharField(_('title'), max_length=255) <NEW_LINE> slug = AutoSlugField(_('slug'), max_length=255, populate_from=['title', 'id'], unique=True, db_index=True) <NEW_LINE> creation_date = models.DateTimeField(_('creation date'), default=timezone.now) <NEW_LINE> last_update = models.DateTimeField(_('last update'), auto_now=True) <NEW_LINE> categories = models.ManyToManyField(Category, blank=True, related_name='products', verbose_name=_('categories')) <NEW_LINE> objects = models.Manager() <NEW_LINE> @models.permalink <NEW_LINE> def get_absolute_url(self): <NEW_LINE> <INDENT> return 'product_catalog:product_detail', (self.slug,) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '%s' % self.title <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> abstract = True <NEW_LINE> ordering = ['-creation_date'] <NEW_LINE> get_latest_by = 'creation_date' <NEW_LINE> verbose_name = _('product') <NEW_LINE> verbose_name_plural = _('products')
Abstract base product model class providing the base fields and methods
62598f9c507cdc57c63a4b40
class DateRange: <NEW_LINE> <INDENT> def __init__(self, data): <NEW_LINE> <INDENT> self.start_date = parse_date(data['startDate']) <NEW_LINE> self.end_date = parse_date(data['endDate']) <NEW_LINE> self.frequencies = data['frequencies']
The class contains information about dataset's data range
62598f9c097d151d1a2c0dd1
class TagCppFlags(TagVector): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> TagVector.__init__(self)
tag CppFlags
62598f9c442bda511e95c20a
class MashapeProcessing(BaseWebService): <NEW_LINE> <INDENT> stage = stages.POST <NEW_LINE> baseurl = "http://text-processing.com/api/" <NEW_LINE> parameters = [ dict(name="extract", value="phrases", choices=["phrases", "sentiment"]), ] <NEW_LINE> def process(self, input): <NEW_LINE> <INDENT> http = httplib2.Http() <NEW_LINE> headers = {} <NEW_LINE> body = dict(text=input[:10000].encode("utf8", "replace")) <NEW_LINE> url = "%s/%s/" % (self.baseurl, self._params.get("extract", "phrases")) <NEW_LINE> request, content = http.request(url, "POST", headers=headers, body=urllib.urlencode(body)) <NEW_LINE> if request["status"] == "503": <NEW_LINE> <INDENT> raise WebServiceNodeError("Daily limit exceeded", self) <NEW_LINE> <DEDENT> elif request["status"] == "400": <NEW_LINE> <INDENT> raise WebServiceNodeError("No text, limit exceeded, or incorrect language", self) <NEW_LINE> <DEDENT> out = u"" <NEW_LINE> try: <NEW_LINE> <INDENT> data = json.loads(content) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return content <NEW_LINE> <DEDENT> for key in ["GPE", "VP", "LOCATION", "NP", "DATE"]: <NEW_LINE> <INDENT> keydata = data.get(key) <NEW_LINE> if keydata is not None: <NEW_LINE> <INDENT> out += "%s\n" % key <NEW_LINE> for entity in keydata: <NEW_LINE> <INDENT> out += " %s\n" % entity <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return out
Mashape entity extraction.
62598f9c3c8af77a43b67e13
class TestQuantityLinAlgFuncs: <NEW_LINE> <INDENT> @pytest.mark.xfail <NEW_LINE> def test_outer(self): <NEW_LINE> <INDENT> q1 = np.array([1, 2, 3]) * u.m <NEW_LINE> q2 = np.array([1, 2]) / u.s <NEW_LINE> o = np.outer(q1, q2) <NEW_LINE> assert np.all(o == np.array([[1, 2], [2, 4], [3, 6]]) * u.m / u.s) <NEW_LINE> <DEDENT> @pytest.mark.xfail <NEW_LINE> def test_inner(self): <NEW_LINE> <INDENT> q1 = np.array([1, 2, 3]) * u.m <NEW_LINE> q2 = np.array([4, 5, 6]) / u.s <NEW_LINE> o = np.inner(q1, q2) <NEW_LINE> assert o == 32 * u.m / u.s <NEW_LINE> <DEDENT> @pytest.mark.xfail <NEW_LINE> def test_dot(self): <NEW_LINE> <INDENT> q1 = np.array([1., 2., 3.]) * u.m <NEW_LINE> q2 = np.array([4., 5., 6.]) / u.s <NEW_LINE> o = np.dot(q1, q2) <NEW_LINE> assert o == 32. * u.m / u.s <NEW_LINE> <DEDENT> @pytest.mark.xfail <NEW_LINE> def test_matmul(self): <NEW_LINE> <INDENT> q1 = np.eye(3) * u.m <NEW_LINE> q2 = np.array([4., 5., 6.]) / u.s <NEW_LINE> o = np.matmul(q1, q2) <NEW_LINE> assert o == q2 / u.s
Test linear algebra functions
62598f9cb7558d58954633da
class AppAssertionCredentials(AssertionCredentials): <NEW_LINE> <INDENT> def __init__(self, email=None, *args, **kwargs): <NEW_LINE> <INDENT> if 'scopes' in kwargs: <NEW_LINE> <INDENT> warnings.warn(_SCOPES_WARNING) <NEW_LINE> kwargs['scopes'] = None <NEW_LINE> <DEDENT> super(AppAssertionCredentials, self).__init__(None, *args, **kwargs) <NEW_LINE> self.service_account_email = email <NEW_LINE> self.scopes = None <NEW_LINE> self.invalid = True <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_json(cls, json_data): <NEW_LINE> <INDENT> raise NotImplementedError( 'Cannot serialize credentials for GCE service accounts.') <NEW_LINE> <DEDENT> def to_json(self): <NEW_LINE> <INDENT> raise NotImplementedError( 'Cannot serialize credentials for GCE service accounts.') <NEW_LINE> <DEDENT> def retrieve_scopes(self, http): <NEW_LINE> <INDENT> self._retrieve_info(http.request) <NEW_LINE> return self.scopes <NEW_LINE> <DEDENT> def _retrieve_info(self, http_request): <NEW_LINE> <INDENT> if self.invalid: <NEW_LINE> <INDENT> info = _metadata.get_service_account_info( http_request, service_account=self.service_account_email or 'default') <NEW_LINE> self.invalid = False <NEW_LINE> self.service_account_email = info['email'] <NEW_LINE> self.scopes = info['scopes'] <NEW_LINE> <DEDENT> <DEDENT> def _refresh(self, http_request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._retrieve_info(http_request) <NEW_LINE> self.access_token, self.token_expiry = _metadata.get_token( http_request, service_account=self.service_account_email) <NEW_LINE> <DEDENT> except httplib2.HttpLib2Error as e: <NEW_LINE> <INDENT> raise HttpAccessTokenRefreshError(str(e)) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def serialization_data(self): <NEW_LINE> <INDENT> raise NotImplementedError( 'Cannot serialize credentials for GCE service accounts.') <NEW_LINE> <DEDENT> def create_scoped_required(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def sign_blob(self, blob): <NEW_LINE> <INDENT> raise NotImplementedError( 'Compute Engine service accounts cannot sign blobs')
Credentials object for Compute Engine Assertion Grants This object will allow a Compute Engine instance to identify itself to Google and other OAuth 2.0 servers that can verify assertions. It can be used for the purpose of accessing data stored under an account assigned to the Compute Engine instance itself. This credential does not require a flow to instantiate because it represents a two legged flow, and therefore has all of the required information to generate and refresh its own access tokens. Note that :attr:`service_account_email` and :attr:`scopes` will both return None until the credentials have been refreshed. To check whether credentials have previously been refreshed use :attr:`invalid`.
62598f9c5f7d997b871f92b4
class Type: <NEW_LINE> <INDENT> __tags = set() <NEW_LINE> def __init__(self, expr, tag = None): <NEW_LINE> <INDENT> self.expr = expr <NEW_LINE> if tag is None: <NEW_LINE> <INDENT> tag = ''.join([c for c in expr if c.isalnum() or c in '_']) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for c in tag: <NEW_LINE> <INDENT> assert c.isalnum() or c in '_' <NEW_LINE> <DEDENT> <DEDENT> if tag in Type.__tags: <NEW_LINE> <INDENT> suffix = 1 <NEW_LINE> while tag + str(suffix) in Type.__tags: <NEW_LINE> <INDENT> suffix += 1 <NEW_LINE> <DEDENT> tag += str(suffix) <NEW_LINE> <DEDENT> assert tag not in Type.__tags <NEW_LINE> Type.__tags.add(tag) <NEW_LINE> self.tag = tag <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.expr <NEW_LINE> <DEDENT> def visit(self, visitor, *args, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError
Base class for all types.
62598f9c21bff66bcd722a10
class InotifyEmitter(EventEmitter): <NEW_LINE> <INDENT> def __init__(self, event_queue, watch, timeout=DEFAULT_EMITTER_TIMEOUT): <NEW_LINE> <INDENT> EventEmitter.__init__(self, event_queue, watch, timeout) <NEW_LINE> self._lock = threading.Lock() <NEW_LINE> self._inotify = Inotify(watch.path, watch.is_recursive) <NEW_LINE> <DEDENT> def on_thread_exit(self): <NEW_LINE> <INDENT> self._inotify.close() <NEW_LINE> <DEDENT> def queue_events(self, timeout): <NEW_LINE> <INDENT> with self._lock: <NEW_LINE> <INDENT> inotify_events = self._inotify.read_events() <NEW_LINE> if not any([event.is_moved_from or event.is_moved_to for event in inotify_events]): <NEW_LINE> <INDENT> self._inotify.clear_move_records() <NEW_LINE> <DEDENT> for event in inotify_events: <NEW_LINE> <INDENT> if event.is_moved_to: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> src_path = self._inotify.source_for_move(event) <NEW_LINE> to_event = event <NEW_LINE> dest_path = to_event.src_path <NEW_LINE> klass = ACTION_EVENT_MAP[ (to_event.is_directory, EVENT_TYPE_MOVED)] <NEW_LINE> event = klass(src_path, dest_path) <NEW_LINE> self.queue_event(event) <NEW_LINE> if event.is_directory and self.watch.is_recursive: <NEW_LINE> <INDENT> for sub_event in event.sub_moved_events(): <NEW_LINE> <INDENT> self.queue_event(sub_event) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> elif event.is_attrib: <NEW_LINE> <INDENT> klass = ACTION_EVENT_MAP[(event.is_directory, EVENT_TYPE_MODIFIED)] <NEW_LINE> self.queue_event(klass(event.src_path)) <NEW_LINE> <DEDENT> elif event.is_close_write: <NEW_LINE> <INDENT> klass = ACTION_EVENT_MAP[(event.is_directory, EVENT_TYPE_MODIFIED)] <NEW_LINE> self.queue_event(klass(event.src_path)) <NEW_LINE> <DEDENT> elif event.is_modify: <NEW_LINE> <INDENT> klass = ACTION_EVENT_MAP[(event.is_directory, EVENT_TYPE_MODIFIED)] <NEW_LINE> self.queue_event(klass(event.src_path)) <NEW_LINE> <DEDENT> elif event.is_delete or event.is_delete_self: <NEW_LINE> <INDENT> klass = ACTION_EVENT_MAP[(event.is_directory, EVENT_TYPE_DELETED)] <NEW_LINE> self.queue_event(klass(event.src_path)) <NEW_LINE> <DEDENT> elif event.is_create: <NEW_LINE> <INDENT> klass = ACTION_EVENT_MAP[(event.is_directory, EVENT_TYPE_CREATED)] <NEW_LINE> self.queue_event(klass(event.src_path)) <NEW_LINE> <DEDENT> elif event.is_moved_from: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> src_path = self._inotify.source_for_move(event) <NEW_LINE> to_event = event <NEW_LINE> try: <NEW_LINE> <INDENT> dest_path = to_event.dest_path <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> dest_path = None <NEW_LINE> <DEDENT> klass = ACTION_EVENT_MAP[ (to_event.is_directory, EVENT_TYPE_MOVED)] <NEW_LINE> event = klass(src_path, dest_path) <NEW_LINE> self.queue_event(event) <NEW_LINE> if event.is_directory and self.watch.is_recursive: <NEW_LINE> <INDENT> for sub_event in event.sub_moved_events(): <NEW_LINE> <INDENT> self.queue_event(sub_event) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass
inotify(7)-based event emitter. :param event_queue: The event queue to fill with events. :param watch: A watch object representing the directory to monitor. :type watch: :class:`watchdog.observers.api.ObservedWatch` :param timeout: Read events blocking timeout (in seconds). :type timeout: ``float``
62598f9ca8370b77170f018f
class PrismRegular: <NEW_LINE> <INDENT> def __init__(self, param1, param2): <NEW_LINE> <INDENT> self.name = 'prism_regular' <NEW_LINE> if (isinstance(param1, PolygonRegular) and isinstance(param2, PolygonRegular)): <NEW_LINE> <INDENT> top_facet = param1 <NEW_LINE> bottom_facet = param2 <NEW_LINE> self.__init_primitive(top_facet, bottom_facet) <NEW_LINE> return <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('Error in RegularPrism.__init__:', 'incorrect argumetns') <NEW_LINE> return None <NEW_LINE> <DEDENT> <DEDENT> def __init_primitive(self, top_facet, bottom_facet): <NEW_LINE> <INDENT> self.top_facet = top_facet <NEW_LINE> self.bottom_facet = bottom_facet <NEW_LINE> dx = top_facet.center.x - bottom_facet.center.x <NEW_LINE> dy = top_facet.center.y - bottom_facet.center.y <NEW_LINE> dz = top_facet.center.z - bottom_facet.center.z <NEW_LINE> self.height = (dx**2 + dy**2 + dz**2)**0.5 <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> result = 'prism_reg{\n top[' <NEW_LINE> for vertex in self.top_facet.vertices: <NEW_LINE> <INDENT> result += '\n ' + str(vertex) <NEW_LINE> <DEDENT> result += ']\n bot:' <NEW_LINE> for vertex in self.bottom_facet.vertices: <NEW_LINE> <INDENT> result += '\n ' + str(vertex) <NEW_LINE> <DEDENT> result += ']\n}' <NEW_LINE> return result
Prism with a regular polygon as base. top_facet is parallel to bottom_facet and height is perpendicular to both of them.
62598f9c1b99ca400228f403
class TestOmer(object): <NEW_LINE> <INDENT> OMER_STRINGS = [ (1, u"היום יום אחד לעומר"), (2, u"היום שני ימים לעומר"), (3, u"היום שלושה ימים לעומר"), (7, u"היום שבעה ימים שהם שבוע אחד לעומר"), (8, u"היום שמונה ימים שהם שבוע אחד ויום אחד לעומר"), (10, u"היום עשרה ימים שהם שבוע אחד ושלושה ימים לעומר"), (13, u"היום שלושה עשר יום שהם שבוע אחד וששה ימים לעומר"), (14, u"היום ארבעה עשר יום שהם שני שבועות לעומר"), (17, u"היום שבעה עשר יום שהם שני שבועות ושלושה ימים לעומר"), (19, u"היום תשעה עשר יום שהם שני שבועות וחמשה ימים לעומר"), (28, u"היום שמונה ועשרים יום שהם ארבעה שבועות לעומר"), (30, u"היום שלושים יום שהם ארבעה שבועות ושני ימים לעומר"), (37, u"היום שבעה ושלושים יום שהם חמשה שבועות ושני ימים לעומר"), (45, u"היום חמשה וארבעים יום שהם ששה שבועות ושלושה ימים לעומר"), (49, u"היום תשעה וארבעים יום שהם שבעה שבועות לעומר"), ] <NEW_LINE> @pytest.mark.parametrize("omer_day,hebrew_string", OMER_STRINGS) <NEW_LINE> def test_get_omer_string(self, omer_day, hebrew_string): <NEW_LINE> <INDENT> assert dt.get_omer_string(omer_day) == hebrew_string <NEW_LINE> <DEDENT> def test_illegal_value(self): <NEW_LINE> <INDENT> with pytest.raises(ValueError): <NEW_LINE> <INDENT> dt.get_omer_string(random.randint(50, 100)) <NEW_LINE> <DEDENT> with pytest.raises(ValueError): <NEW_LINE> <INDENT> dt.get_omer_string(random.randint(-100, 0))
Test get_omer_string
62598f9cdd821e528d6d8ce0
class AssociateSecurityGroupsRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.SecurityGroupIds = None <NEW_LINE> self.InstanceIds = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.SecurityGroupIds = params.get("SecurityGroupIds") <NEW_LINE> self.InstanceIds = params.get("InstanceIds")
AssociateSecurityGroups请求参数结构体
62598f9cdd821e528d6d8ce1
class CONTAINS(object): <NEW_LINE> <INDENT> def __init__(self, *args): <NEW_LINE> <INDENT> self.values = args <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return all(value in other for value in self.values) <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return any(value not in other for value in self.values) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<CONTAINS {0}>'.format(self.values)
Helper object that checks for equalness by checking if the compared object contains elements passed in the constructor.
62598f9ca17c0f6771d5bfe7
class TestCity(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.my_object = City() <NEW_LINE> <DEDENT> def test_docstring(self): <NEW_LINE> <INDENT> msj = "Módulo does not has docstring" <NEW_LINE> self.assertIsNotNone(models.city.__doc__, msj) <NEW_LINE> msj = "Clase does not has docstring" <NEW_LINE> self.assertIsNotNone(City.__doc__, msj) <NEW_LINE> <DEDENT> def test_executable_file(self): <NEW_LINE> <INDENT> is_read_true = os.access('models/city.py', os.R_OK) <NEW_LINE> self.assertTrue(is_read_true) <NEW_LINE> is_write_true = os.access('models/city.py', os.W_OK) <NEW_LINE> self.assertTrue(is_write_true) <NEW_LINE> is_exec_true = os.access('models/city.py', os.X_OK) <NEW_LINE> self.assertTrue(is_exec_true) <NEW_LINE> <DEDENT> def test_is_an_instance(self): <NEW_LINE> <INDENT> self.assertIsInstance(self.my_object, City) <NEW_LINE> <DEDENT> def test_id(self): <NEW_LINE> <INDENT> instance1 = City() <NEW_LINE> instance2 = City() <NEW_LINE> self.assertNotEqual(instance1.id, instance2.id) <NEW_LINE> <DEDENT> def test_str(self): <NEW_LINE> <INDENT> _dict = self.my_object.__dict__ <NEW_LINE> string1 = "[City] ({}) {}".format(self.my_object.id, _dict) <NEW_LINE> string2 = str(self.my_object) <NEW_LINE> self.assertEqual(string1, string2) <NEW_LINE> <DEDENT> def test_save(self): <NEW_LINE> <INDENT> first_updated = self.my_object.updated_at <NEW_LINE> self.my_object.save() <NEW_LINE> second_updated = self.my_object.updated_at <NEW_LINE> self.assertNotEqual(first_updated, second_updated) <NEW_LINE> os.remove("file.json") <NEW_LINE> <DEDENT> def test_to_dict(self): <NEW_LINE> <INDENT> my_dict_model = self.my_object.to_dict() <NEW_LINE> self.assertIsInstance(my_dict_model, dict) <NEW_LINE> for key, value in my_dict_model.items(): <NEW_LINE> <INDENT> flag = 0 <NEW_LINE> if my_dict_model['__class__'] == 'City': <NEW_LINE> <INDENT> flag += 1 <NEW_LINE> <DEDENT> self.assertTrue(flag == 1) <NEW_LINE> <DEDENT> for key, value in my_dict_model.items(): <NEW_LINE> <INDENT> if key == 'created_at': <NEW_LINE> <INDENT> self.assertIsInstance(value, str) <NEW_LINE> <DEDENT> if key == 'updated_at': <NEW_LINE> <INDENT> self.assertIsInstance(value, str) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def test_kwargs(self): <NEW_LINE> <INDENT> self.my_object.name = "Holberton" <NEW_LINE> self.my_object.my_number = 89 <NEW_LINE> my_object_json = self.my_object.to_dict() <NEW_LINE> my_object_kwargs = City(**my_object_json) <NEW_LINE> self.assertNotEqual(my_object_kwargs, self.my_object) <NEW_LINE> <DEDENT> def test_des_and_serialization(self): <NEW_LINE> <INDENT> storage = FileStorage() <NEW_LINE> all_objs = storage.all() <NEW_LINE> self.assertIsInstance(all_objs, dict, "es diccionario") <NEW_LINE> self.my_object.name = "Paparoachchchch" <NEW_LINE> self.my_object.my_number = 95 <NEW_LINE> self.my_object.save() <NEW_LINE> with open("file.json", "r", encoding='utf-8') as f: <NEW_LINE> <INDENT> self.assertTrue(self.my_object.name in f.read())
start tests
62598f9c6fb2d068a7693d0a
class RebootRequiredTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def test_returns_true(self): <NEW_LINE> <INDENT> out = "You really need to restart here" <NEW_LINE> self.assertTrue(requires_reboot(out)) <NEW_LINE> <DEDENT> def test_returns_false(self): <NEW_LINE> <INDENT> out = "You really need to renppt here" <NEW_LINE> self.assertFalse(requires_reboot(out)) <NEW_LINE> <DEDENT> def test_is_boolean(self): <NEW_LINE> <INDENT> out = "You really need to restart" <NEW_LINE> self.assertIsInstance(requires_reboot(out), bool)
Tests for `powerful_python.py`'s `requires_reboot`.
62598f9cfff4ab517ebcd59a
class StaleObjectError(PersistenceError): <NEW_LINE> <INDENT> __xmlrpc_error__ = 8 <NEW_LINE> def __init__(self, message): <NEW_LINE> <INDENT> self.message = message <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return repr(self.message)
Thrown when an object the object being persisted has already been updated.
62598f9c2ae34c7f260aae8d
class CommentSerializer(ModelSerializer): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = Comment <NEW_LINE> exclude = ('review',) <NEW_LINE> read_only_fields = ('pub_date',) <NEW_LINE> <DEDENT> author = serializers.SlugRelatedField(slug_field='username', read_only=True)
Сериалайзер Комментарий.
62598f9c090684286d5935b0
class OffspringGenerator(object): <NEW_LINE> <INDENT> thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> def __init__(self, ops: 'opList', numOffspring: 'floatListFunc'=1, sexMode: 'floatListFunc'=RANDOM_SEX): <NEW_LINE> <INDENT> _simuPOP_op.OffspringGenerator_swiginit(self, _simuPOP_op.new_OffspringGenerator(ops, numOffspring, sexMode)) <NEW_LINE> <DEDENT> __swig_destroy__ = _simuPOP_op.delete_OffspringGenerator <NEW_LINE> def clone(self) -> "simuPOP::OffspringGenerator *": <NEW_LINE> <INDENT> return _simuPOP_op.OffspringGenerator_clone(self) <NEW_LINE> <DEDENT> def describe(self, format: 'bool'=True) -> "string": <NEW_LINE> <INDENT> return _simuPOP_op.OffspringGenerator_describe(self, format)
Details: An offspring generator generates offspring from parents chosen by a parent chooser. It is responsible for creating a certain number of offspring, determinning their sex, and transmitting genotypes from parents to offspring.
62598f9c656771135c48942f
class Location(db.Model): <NEW_LINE> <INDENT> __tablename__ = 'locations' <NEW_LINE> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> name = db.Column(db.String, nullable=False) <NEW_LINE> latitude = db.Column(db.Float) <NEW_LINE> longitude = db.Column(db.Float) <NEW_LINE> user_id = db.Column(db.Integer, db.ForeignKey('users.id')) <NEW_LINE> user = db.relationship('User', backref='location') <NEW_LINE> def __init__(self, name=None, latitude=None, longitude=None, user_id=None): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.latitude = latitude <NEW_LINE> self.longitude = longitude <NEW_LINE> self.user_id = user_id <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<Location %r,%r>' % (self.id,self.name) <NEW_LINE> <DEDENT> @property <NEW_LINE> def serialize(self): <NEW_LINE> <INDENT> return {'id': self.id, 'name': self.name, 'latitude': self.latitude, 'longitude': self.longitude }
Location model class
62598f9cd7e4931a7ef3be45
class Quantizer: <NEW_LINE> <INDENT> def __init__(self, start, end, bins): <NEW_LINE> <INDENT> self.start = start <NEW_LINE> self.end = end <NEW_LINE> self.bins = bins <NEW_LINE> self.moved_start = 0.0 <NEW_LINE> self.moved_end = abs(end - start) <NEW_LINE> self.step = abs(end - start) / bins <NEW_LINE> <DEDENT> def index(self, value): <NEW_LINE> <INDENT> if value < self.start or value > self.end: <NEW_LINE> <INDENT> value = self.start <NEW_LINE> <DEDENT> elif value > self.end: <NEW_LINE> <INDENT> value = self.end <NEW_LINE> <DEDENT> moved_value = abs(value - self.start) <NEW_LINE> return int(moved_value // self.step) <NEW_LINE> <DEDENT> def round(self, value): <NEW_LINE> <INDENT> if value < self.start or value > self.end: <NEW_LINE> <INDENT> random_index = random.choice(range(self.bins)) <NEW_LINE> v_random = self.start + self.step * random_index <NEW_LINE> return v_random <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> idx = self.index(value) <NEW_LINE> v1 = self.start + self.step * idx <NEW_LINE> v2 = v1 + self.step <NEW_LINE> a = abs(value - v1) <NEW_LINE> b = abs(value - v2) <NEW_LINE> if a >= b: <NEW_LINE> <INDENT> return float(v2) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return float(v1) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def value_to_index(self, value): <NEW_LINE> <INDENT> v = self.index(self.round(value)) <NEW_LINE> if v > self.bins - 1: <NEW_LINE> <INDENT> return self.bins - 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return v <NEW_LINE> <DEDENT> <DEDENT> def as_list(self): <NEW_LINE> <INDENT> lst = [] <NEW_LINE> for i in range(self.bins): <NEW_LINE> <INDENT> lst.append(self.start + self.step * i) <NEW_LINE> <DEDENT> return lst
quantize value range. if we want to quantize -2 to 2 into 4 bins, -2 to -1 | -1 to 0 | 0 to 1 | 1 to 2 each bin range should be 1. also index of 0.5 should return 2. Examples Note: some value may return incorrect result because of float imprecision >>> q = Quantizer(-2, 2, 4) >>> q.index(-1.9) 0 >>> q.round(-1.9) -2.0 >>> q.index(0.5) 2 >>> q.round(0.5) 1.0 >>> q = Quantizer(-0.5, 1, 15) >>> q.index(-0.38) 1 >>> q.round(-0.38) -0.4 >>> q.index(0.18) 6 >> q.round(0.18) This one have float imprecision problem for now
62598f9cd53ae8145f91823b
class Like(TimeStampedModel): <NEW_LINE> <INDENT> creator = models.ForeignKey(user_models.User, on_delete=models.CASCADE, null=True) <NEW_LINE> image = models.ForeignKey(Image, on_delete=models.CASCADE, null=True, related_name='likes') <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return 'User : {} - Image Cpation: {}'.format(self.creator.username, self.image.caption)
Like Model
62598f9ca79ad16197769e11
class HuntCronAction(rdf_structs.RDFProtoStruct): <NEW_LINE> <INDENT> protobuf = flows_pb2.HuntCronAction <NEW_LINE> rdf_deps = [ rdf_hunts.HuntRunnerArgs, ] <NEW_LINE> def GetFlowArgsClass(self): <NEW_LINE> <INDENT> if self.flow_name: <NEW_LINE> <INDENT> flow_cls = registry.AFF4FlowRegistry.FlowClassByName(self.flow_name) <NEW_LINE> return flow_cls.args_type
Cron Action that starts a hunt.
62598f9c38b623060ffa8e3e
class TimezoneConfigError(Exception): <NEW_LINE> <INDENT> pass
Exception class for timezone configuration related problems
62598f9c097d151d1a2c0dd4
class ExampleObject(HasStrictTraits): <NEW_LINE> <INDENT> spam = Event <NEW_LINE> eggs = Event
Test class; target for test_event_loop_until_traits_change.
62598f9c0a50d4780f705187
class TimeDependentStateSpaceModel(state_space_model.StateSpaceModel): <NEW_LINE> <INDENT> def __init__(self, static_unrolling_window_size_threshold=None): <NEW_LINE> <INDENT> super(TimeDependentStateSpaceModel, self).__init__( configuration=state_space_model.StateSpaceModelConfiguration( use_observation_noise=False, transition_covariance_initial_log_scale_bias=5., static_unrolling_window_size_threshold= static_unrolling_window_size_threshold)) <NEW_LINE> <DEDENT> def get_state_transition(self): <NEW_LINE> <INDENT> return array_ops.ones(shape=[1, 1]) <NEW_LINE> <DEDENT> def get_noise_transform(self): <NEW_LINE> <INDENT> return array_ops.ones(shape=[1, 1]) <NEW_LINE> <DEDENT> def get_observation_model(self, times): <NEW_LINE> <INDENT> return array_ops.reshape( tensor=math_ops.cast(times + 1, dtypes.float32), shape=[-1, 1, 1]) <NEW_LINE> <DEDENT> def make_priors(self): <NEW_LINE> <INDENT> return (ops.convert_to_tensor([1.]), ops.convert_to_tensor([[0.]]))
A mostly trivial model which predicts values = times + 1.
62598f9c851cf427c66b8076
class NullType(TypeEngine): <NEW_LINE> <INDENT> __visit_name__ = 'null' <NEW_LINE> def _adapt_expression(self, op, othertype): <NEW_LINE> <INDENT> if othertype is NullType or not operators.is_commutative(op): <NEW_LINE> <INDENT> return op, self <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return othertype._adapt_expression(op, self)
An unknown type. NullTypes will stand in if :class:`~sqlalchemy.Table` reflection encounters a column data type unknown to SQLAlchemy. The resulting columns are nearly fully usable: the DB-API adapter will handle all translation to and from the database data type. NullType does not have sufficient information to particpate in a ``CREATE TABLE`` statement and will raise an exception if encountered during a :meth:`~sqlalchemy.Table.create` operation.
62598f9c4e4d5625663721d2
class aadict(dict): <NEW_LINE> <INDENT> def __getattr__(self, key): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.__getitem__(key) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return object.__getattribute__(self, key) <NEW_LINE> <DEDENT> <DEDENT> def __delattr__(self, key): <NEW_LINE> <INDENT> if key in self: <NEW_LINE> <INDENT> del self[key] <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> def update(self, *args, **kw): <NEW_LINE> <INDENT> args = [e for e in args if e] <NEW_LINE> dict.update(self, *args, **kw) <NEW_LINE> return self <NEW_LINE> <DEDENT> def pick(self, *args): <NEW_LINE> <INDENT> return aadict({k: v for k, v in self.iteritems() if k in args}) <NEW_LINE> <DEDENT> def omit(self, *args): <NEW_LINE> <INDENT> return aadict({k: v for k, v in self.iteritems() if k not in args}) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def __dict2aadict__(subject, recursive=False): <NEW_LINE> <INDENT> if isinstance(subject, list): <NEW_LINE> <INDENT> if not recursive: <NEW_LINE> <INDENT> return subject <NEW_LINE> <DEDENT> return [aadict.__dict2aadict__(val, True) for val in subject] <NEW_LINE> <DEDENT> if not isinstance(subject, dict): <NEW_LINE> <INDENT> return subject <NEW_LINE> <DEDENT> ret = aadict(subject) <NEW_LINE> if not recursive: <NEW_LINE> <INDENT> return ret <NEW_LINE> <DEDENT> for key, val in ret.items(): <NEW_LINE> <INDENT> ret[key] = aadict.__dict2aadict__(val, True) <NEW_LINE> <DEDENT> return ret <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def d2ar(subject): <NEW_LINE> <INDENT> return aadict.__dict2aadict__(subject, True) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def d2a(subject): <NEW_LINE> <INDENT> return aadict.__dict2aadict__(subject, False)
A dict subclass that allows attribute access to be synonymous with item access, e.g. ``mydict.attribute == mydict['attribute']``. It also provides several other useful helper methods, such as :meth:`pick` and :meth:`omit`.
62598f9c6fb2d068a7693d0b
class Solution: <NEW_LINE> <INDENT> def minimumTotal(self, triangle): <NEW_LINE> <INDENT> for r in range(1, len(triangle)): <NEW_LINE> <INDENT> row = triangle[r] <NEW_LINE> prev = triangle[r - 1] <NEW_LINE> for i in range(len(row)): <NEW_LINE> <INDENT> add = prev[i - 1] if i else sys.maxint <NEW_LINE> if i != len(row) - 1: <NEW_LINE> <INDENT> add = min(add, prev[i]) <NEW_LINE> <DEDENT> row[i] += add <NEW_LINE> <DEDENT> <DEDENT> return min(triangle[-1])
@param: triangle: a list of lists of integers @return: An integer, minimum path sum
62598f9c8a43f66fc4bf1f2a
class Base1DMapper(AbstractMapper): <NEW_LINE> <INDENT> range = Instance(DataRange1D) <NEW_LINE> low_pos = Float(0.0) <NEW_LINE> high_pos = Float(1.0) <NEW_LINE> screen_bounds = Property <NEW_LINE> stretch_data = Bool(True) <NEW_LINE> _cache_valid = Bool(False) <NEW_LINE> _bounds_initialized = Bool(False) <NEW_LINE> def _low_pos_changed(self): <NEW_LINE> <INDENT> self._cache_valid = False <NEW_LINE> self.updated = True <NEW_LINE> return <NEW_LINE> <DEDENT> def _high_pos_changed(self): <NEW_LINE> <INDENT> self._cache_valid = False <NEW_LINE> self.updated = True <NEW_LINE> return <NEW_LINE> <DEDENT> def _range_changed(self, old, new): <NEW_LINE> <INDENT> if old is not None: <NEW_LINE> <INDENT> old.on_trait_change(self._range_change_handler, "updated", remove = True) <NEW_LINE> <DEDENT> if new is not None: <NEW_LINE> <INDENT> new.on_trait_change(self._range_change_handler, "updated") <NEW_LINE> <DEDENT> self._cache_valid = False <NEW_LINE> self.updated = new <NEW_LINE> return <NEW_LINE> <DEDENT> def _range_change_handler(self, obj, name, new): <NEW_LINE> <INDENT> self._cache_valid = False <NEW_LINE> self.updated = obj <NEW_LINE> return <NEW_LINE> <DEDENT> def _get_screen_bounds(self): <NEW_LINE> <INDENT> return (self.low_pos, self.high_pos) <NEW_LINE> <DEDENT> def _set_screen_bounds(self, new_bounds): <NEW_LINE> <INDENT> if new_bounds[0] == self.low_pos and new_bounds[1] == self.high_pos: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if not self.stretch_data and self.range is not None and self._bounds_initialized: <NEW_LINE> <INDENT> rangelow = self.range.low <NEW_LINE> rangehigh = self.range.high <NEW_LINE> d_data = rangehigh - rangelow <NEW_LINE> d_screen = self.high_pos - self.low_pos <NEW_LINE> if d_data != 0 and d_screen != 0: <NEW_LINE> <INDENT> new_data_extent = d_data / d_screen * abs(new_bounds[1] - new_bounds[0]) <NEW_LINE> self.range.set_bounds(rangelow, rangelow + new_data_extent) <NEW_LINE> <DEDENT> <DEDENT> self.set(low_pos = new_bounds[0], trait_change_notify=False) <NEW_LINE> self.set(high_pos = new_bounds[1], trait_change_notify=False) <NEW_LINE> self._cache_valid = False <NEW_LINE> self._bounds_initialized = True <NEW_LINE> self.updated = True <NEW_LINE> return
Defines an abstract mapping from a 1-D region in input space to a 1-D region in output space.
62598f9c24f1403a92685789
@StreamAlertOutput <NEW_LINE> class S3Output(AWSOutput): <NEW_LINE> <INDENT> __service__ = 'aws-s3' <NEW_LINE> @classmethod <NEW_LINE> def get_user_defined_properties(cls): <NEW_LINE> <INDENT> return OrderedDict([ ('descriptor', OutputProperty( description='a short and unique descriptor for this S3 bucket (ie: bucket name)')), ('aws_value', OutputProperty(description='the AWS S3 bucket name to use for this S3 configuration')) ]) <NEW_LINE> <DEDENT> def _dispatch(self, alert, descriptor): <NEW_LINE> <INDENT> bucket = self.config[self.__service__][descriptor] <NEW_LINE> key = 'alerts/dt={}/{}_{}_{}_{}.json'.format( datetime.now().strftime('%Y-%m-%d-%H'), alert.source_service, alert.source_entity, alert.rule_name, uuid.uuid4() ) <NEW_LINE> LOGGER.debug('Sending %s to S3 bucket %s with key %s', alert, bucket, key) <NEW_LINE> client = boto3.client('s3', region_name=self.region) <NEW_LINE> client.put_object(Body=json.dumps(alert.output_dict()), Bucket=bucket, Key=key) <NEW_LINE> return True
S3Output handles all alert dispatching for AWS S3
62598f9c596a897236127a2f
class WireframeObject: <NEW_LINE> <INDENT> def __init__(self, sla_object=False): <NEW_LINE> <INDENT> self.box = False <NEW_LINE> self.bleed = False <NEW_LINE> self.is_page = False <NEW_LINE> self.type = "undefined" <NEW_LINE> self.group_objects = [] <NEW_LINE> self.layer = -1 <NEW_LINE> self.draw_settings = { "fill": "", "outline": "", "bleed": "red" } <NEW_LINE> if sla_object: <NEW_LINE> <INDENT> self.from_object(sla_object) <NEW_LINE> <DEDENT> <DEDENT> def from_object(self, sla_object): <NEW_LINE> <INDENT> if isinstance(sla_object, pages.Page): <NEW_LINE> <INDENT> self.is_page = True <NEW_LINE> self.type = "page" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.is_page = False <NEW_LINE> type_ok = False <NEW_LINE> for class_test in [ pageobjects.LatexObject, pageobjects.RenderObject]: <NEW_LINE> <INDENT> if isinstance(sla_object, class_test): <NEW_LINE> <INDENT> self.type = "render" <NEW_LINE> type_ok = True <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if not type_ok: <NEW_LINE> <INDENT> for human, class_test in pageobjects.po_type_classes.items(): <NEW_LINE> <INDENT> if isinstance(sla_object, class_test): <NEW_LINE> <INDENT> self.type = human <NEW_LINE> type_ok = True <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> if self.type == "group": <NEW_LINE> <INDENT> self.group_objects = sla_object.group_objects <NEW_LINE> <DEDENT> if isinstance(sla_object, pageobjects.PageObject): <NEW_LINE> <INDENT> if sla_object.rotated: <NEW_LINE> <INDENT> self.box = sla_object.rotated_box <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.box = sla_object.box <NEW_LINE> <DEDENT> self.layer = sla_object.layer <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.box = sla_object.box <NEW_LINE> <DEDENT> <DEDENT> def draw_on_canvas(self, canvas, bleed=False): <NEW_LINE> <INDENT> if bleed and self.bleed: <NEW_LINE> <INDENT> tx = self.box.coords["top-left"][0].value - self.bleed["left"] <NEW_LINE> ty = self.box.coords["top-left"][1].value - self.bleed["top"] <NEW_LINE> bx = self.box.coords["bottom-right"][0].value + self.bleed["right"] <NEW_LINE> by = self.box.coords["bottom-right"][1].value + self.bleed["bottom"] <NEW_LINE> bleed_rect = ((tx, ty), (bx, by)) <NEW_LINE> canvas.rectangle(bleed_rect, outline="red") <NEW_LINE> <DEDENT> rect = ( ( self.box.coords["top-left"][0], self.box.coords["top-left"][1] ), ( self.box.coords["bottom-right"][0], self.box.coords["bottom-right"][1] ), ) <NEW_LINE> if self.draw_settings["fill"] and self.draw_settings["outline"]: <NEW_LINE> <INDENT> canvas.rectangle( rect, fill=self.draw_settings["fill"], outline=self.draw_settings["outline"] ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self.draw_settings["fill"]: <NEW_LINE> <INDENT> canvas.rectangle(rect, fill=self.draw_settings["fill"]) <NEW_LINE> <DEDENT> if self.draw_settings["outline"]: <NEW_LINE> <INDENT> canvas.rectangle(rect, outline=self.draw_settings["outline"]) <NEW_LINE> <DEDENT> <DEDENT> if self.type == "group": <NEW_LINE> <INDENT> for subpo in self.group_objects: <NEW_LINE> <INDENT> s = WireframeObject(subpo) <NEW_LINE> s.draw_on_canvas(canvas, bleed) <NEW_LINE> <DEDENT> <DEDENT> return canvas
Wireframe object : something to draw on the wireframe, like pages, page objects. :type sla_object: pyscribus.pages.Page, pyscribus.pageobjects.PageObject :param sla_object: PyScribus instance of drawnable object
62598f9c7047854f4633f191
class Dnstop(AutotoolsPackage): <NEW_LINE> <INDENT> homepage = "https://github.com/measurement-factory/dnstop" <NEW_LINE> git = "https://github.com/measurement-factory/dnstop.git" <NEW_LINE> version('master', branch='master') <NEW_LINE> depends_on('libpcap') <NEW_LINE> def install(self, spec, prefix): <NEW_LINE> <INDENT> mkdirp(prefix.bin) <NEW_LINE> mkdirp(prefix.share.man.man8) <NEW_LINE> make('BINPATH={0}'.format(prefix.bin), 'MANPATH={0}/'.format(prefix), 'install')
Stay on top of your DNS traffic.
62598f9c7d43ff24874272d9
class WAR_Dealer(WAR_Hand): <NEW_LINE> <INDENT> def flip_first_card(self): <NEW_LINE> <INDENT> first_card = self.cards[0] <NEW_LINE> first_card.flip()
A WAR Dealer.
62598f9c3d592f4c4edbac7e
class SyncMapInstance(InstanceResource): <NEW_LINE> <INDENT> def __init__(self, version, payload, service_sid, sid=None): <NEW_LINE> <INDENT> super(SyncMapInstance, self).__init__(version) <NEW_LINE> self._properties = { 'sid': payload.get('sid'), 'unique_name': payload.get('unique_name'), 'account_sid': payload.get('account_sid'), 'service_sid': payload.get('service_sid'), 'url': payload.get('url'), 'links': payload.get('links'), 'revision': payload.get('revision'), 'date_expires': deserialize.iso8601_datetime(payload.get('date_expires')), 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), 'created_by': payload.get('created_by'), } <NEW_LINE> self._context = None <NEW_LINE> self._solution = {'service_sid': service_sid, 'sid': sid or self._properties['sid'], } <NEW_LINE> <DEDENT> @property <NEW_LINE> def _proxy(self): <NEW_LINE> <INDENT> if self._context is None: <NEW_LINE> <INDENT> self._context = SyncMapContext( self._version, service_sid=self._solution['service_sid'], sid=self._solution['sid'], ) <NEW_LINE> <DEDENT> return self._context <NEW_LINE> <DEDENT> @property <NEW_LINE> def sid(self): <NEW_LINE> <INDENT> return self._properties['sid'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def unique_name(self): <NEW_LINE> <INDENT> return self._properties['unique_name'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def account_sid(self): <NEW_LINE> <INDENT> return self._properties['account_sid'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def service_sid(self): <NEW_LINE> <INDENT> return self._properties['service_sid'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def url(self): <NEW_LINE> <INDENT> return self._properties['url'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def links(self): <NEW_LINE> <INDENT> return self._properties['links'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def revision(self): <NEW_LINE> <INDENT> return self._properties['revision'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def date_expires(self): <NEW_LINE> <INDENT> return self._properties['date_expires'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def date_created(self): <NEW_LINE> <INDENT> return self._properties['date_created'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def date_updated(self): <NEW_LINE> <INDENT> return self._properties['date_updated'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def created_by(self): <NEW_LINE> <INDENT> return self._properties['created_by'] <NEW_LINE> <DEDENT> def fetch(self): <NEW_LINE> <INDENT> return self._proxy.fetch() <NEW_LINE> <DEDENT> def delete(self): <NEW_LINE> <INDENT> return self._proxy.delete() <NEW_LINE> <DEDENT> def update(self, ttl=values.unset, collection_ttl=values.unset): <NEW_LINE> <INDENT> return self._proxy.update(ttl=ttl, collection_ttl=collection_ttl, ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def sync_map_items(self): <NEW_LINE> <INDENT> return self._proxy.sync_map_items <NEW_LINE> <DEDENT> @property <NEW_LINE> def sync_map_permissions(self): <NEW_LINE> <INDENT> return self._proxy.sync_map_permissions <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) <NEW_LINE> return '<Twilio.Sync.V1.SyncMapInstance {}>'.format(context)
PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution.
62598f9cb7558d58954633de
class RedirectDataViewSet(mixins.ListModelMixin, mixins.CreateModelMixin, viewsets.GenericViewSet): <NEW_LINE> <INDENT> queryset = RedirectData.objects.all().order_by('created_at') <NEW_LINE> permission_classes = (AllowAny,) <NEW_LINE> serializer_class = RedirectUrlSerializer <NEW_LINE> filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter) <NEW_LINE> filter_fields = ['redirect_domain', 'referrer_domain', ] <NEW_LINE> search_fields = ['redirect_domain', 'referrer_domain', ] <NEW_LINE> ordering_fields = ['created_at', ] <NEW_LINE> pagination_class = StandardResultsPagination <NEW_LINE> def get_serializer_class(self): <NEW_LINE> <INDENT> if self.action == 'create': <NEW_LINE> <INDENT> return RedirectUrlSerializer <NEW_LINE> <DEDENT> elif self.action == 'top': <NEW_LINE> <INDENT> return RedirectDataTopListSerializer <NEW_LINE> <DEDENT> elif self.action == 'by_domain': <NEW_LINE> <INDENT> return RedirectDataListByDomainSerializer <NEW_LINE> <DEDENT> return RedirectDataListSerializer <NEW_LINE> <DEDENT> def create(self, request, *args, **kwargs): <NEW_LINE> <INDENT> with transaction.atomic(): <NEW_LINE> <INDENT> serializer = self.get_serializer(data=request.data) <NEW_LINE> serializer.is_valid(raise_exception=True) <NEW_LINE> redirect_to = serializer.validated_data['redirect_url'] <NEW_LINE> referrer = request.META.get('HTTP_REFERER', '') <NEW_LINE> agent = request.META.get('HTTP_USER_AGENT') <NEW_LINE> ip = request.META.get('REMOTE_ADDR') <NEW_LINE> store_redirect_data.delay(redirect_to, referrer, ip, agent) <NEW_LINE> return HttpResponseRedirect(redirect_to=redirect_to) <NEW_LINE> <DEDENT> <DEDENT> def list(self, request, *args, **kwargs): <NEW_LINE> <INDENT> queryset = self.filter_queryset(self.get_queryset()) <NEW_LINE> page = self.paginate_queryset(queryset) <NEW_LINE> if page is not None: <NEW_LINE> <INDENT> serializer = self.get_serializer(page, many=True) <NEW_LINE> return self.get_paginated_response(serializer.data) <NEW_LINE> <DEDENT> serializer = self.get_serializer(queryset, many=True) <NEW_LINE> return Response(serializer.data) <NEW_LINE> <DEDENT> @action(detail=False, methods=['get']) <NEW_LINE> def by_domain(self, request, *args, **kwargs): <NEW_LINE> <INDENT> result = RedirectData.objects .annotate(redirect_full_url=F('redirect_url')) .values('redirect_full_url') .annotate(redirects=Count('redirect_full_url'), referrers=ArrayAgg( F('referrer_domain') ), last_redirected=Max('created_at'), ) <NEW_LINE> queryset = self.filter_queryset(result) <NEW_LINE> page = self.paginate_queryset(queryset) <NEW_LINE> if page is not None: <NEW_LINE> <INDENT> serializer = self.get_serializer(page, many=True) <NEW_LINE> return self.get_paginated_response(serializer.data) <NEW_LINE> <DEDENT> serializer = self.get_serializer(queryset, many=True) <NEW_LINE> return Response(serializer.data) <NEW_LINE> <DEDENT> @action(detail=False, methods=['get']) <NEW_LINE> def top(self, request, *args, **kwargs): <NEW_LINE> <INDENT> queryset = self.filter_queryset(self.get_queryset()) <NEW_LINE> current_month = datetime.today().month <NEW_LINE> result = queryset.filter( created_at__month=current_month ).values('redirect_domain').annotate( redirects_count=Count('redirect_domain'), ).order_by( '-redirects_count' )[:10] <NEW_LINE> page = self.paginate_queryset(result) <NEW_LINE> if page is not None: <NEW_LINE> <INDENT> serializer = self.get_serializer(page, many=True) <NEW_LINE> return self.get_paginated_response(serializer.data) <NEW_LINE> <DEDENT> serializer = self.get_serializer(result, many=True) <NEW_LINE> return Response(serializer.data)
ViewSet to registering new redirects and getting redirects via lists for statistical analysis permission_classes - AllowAny
62598f9c4f6381625f199394
class Task(): <NEW_LINE> <INDENT> def __init__(self, function, scheduled_time, args=[], kwargs={}, id=None): <NEW_LINE> <INDENT> self.id = id <NEW_LINE> self.func = function <NEW_LINE> self.args = args <NEW_LINE> self.kwargs = kwargs <NEW_LINE> self.time = scheduled_time <NEW_LINE> self.created = datetime.now() <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return f"[{self.time.strftime('%Y-%m-%d %H:%M:%S')}] {self.id}:{self.func.__name__}" <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return f"[{self.time.strftime('%Y-%m-%d %H:%M:%S')}] {self.func.__name__}" <NEW_LINE> <DEDENT> def execute(self): <NEW_LINE> <INDENT> self.func(*self.args, **self.kwargs)
Data structure representing scheduled tasks with underlying functions,
62598f9c56b00c62f0fb2660
class QuasiStaticGraspQualityConfig(GraspQualityConfig): <NEW_LINE> <INDENT> REQUIRED_KEYS = ['quality_method', 'friction_coef', 'num_cone_faces', 'soft_fingers', 'quality_type', 'check_approach', 'all_contacts_required'] <NEW_LINE> def __init__(self, config): <NEW_LINE> <INDENT> GraspQualityConfig.__init__(self, config) <NEW_LINE> <DEDENT> def __copy__(self): <NEW_LINE> <INDENT> obj_copy = QuasiStaticGraspQualityConfig(self.__dict__) <NEW_LINE> return obj_copy <NEW_LINE> <DEDENT> def check_valid(self, config): <NEW_LINE> <INDENT> for key in QuasiStaticGraspQualityConfig.REQUIRED_KEYS: <NEW_LINE> <INDENT> if key not in config.keys(): <NEW_LINE> <INDENT> raise ValueError('Invalid configuration. Key %s must be specified' %(key))
Parameters for quasi-static grasp quality computation. Attributes ---------- config : :obj:`dict` dictionary mapping parameter names to parameter values Notes ----- Required configuration key-value pairs in Other Parameters. Other Parameters ---------------- quality_method : :obj:`str` string name of quasi-static quality metric friction_coef : float coefficient of friction at contact point num_cone_faces : int number of faces to use in friction cone approximation soft_fingers : bool whether to use a soft finger model quality_type : :obj:`str` string name of grasp quality type (e.g. quasi-static, robust quasi-static) check_approach : bool whether or not to check the approach direction
62598f9cd53ae8145f91823d
class DT(Enum): <NEW_LINE> <INDENT> DT_NULL = 0 <NEW_LINE> DT_NEEDED = 1 <NEW_LINE> DT_PLTRELSZ = 2 <NEW_LINE> DT_PLTGOT = 3 <NEW_LINE> DT_HASH = 4 <NEW_LINE> DT_STRTAB = 5 <NEW_LINE> DT_SYMTAB = 6 <NEW_LINE> DT_RELA = 7 <NEW_LINE> DT_RELASZ = 8 <NEW_LINE> DT_RELAENT = 9 <NEW_LINE> DT_STRSZ = 10 <NEW_LINE> DT_SYMENT = 11 <NEW_LINE> DT_INIT = 12 <NEW_LINE> DT_FINI = 13 <NEW_LINE> DT_SONAME = 14 <NEW_LINE> DT_RPATH = 15 <NEW_LINE> DT_SYMBOLIC = 16 <NEW_LINE> DT_REL = 17 <NEW_LINE> DT_RELSZ = 18 <NEW_LINE> DT_RELENT = 19 <NEW_LINE> DT_PLTREL = 20 <NEW_LINE> DT_DEBUG = 21 <NEW_LINE> DT_TEXTREL = 22 <NEW_LINE> DT_JMPREL = 23 <NEW_LINE> DT_BIND_NOW = 24 <NEW_LINE> DT_INIT_ARRAY = 25 <NEW_LINE> DT_FINI_ARRAY = 26 <NEW_LINE> DT_INIT_ARRAYSZ = 27 <NEW_LINE> DT_FINI_ARRAYSZ = 28 <NEW_LINE> DT_RUNPATH = 29 <NEW_LINE> DT_FLAGS = 30 <NEW_LINE> DT_ENCODING = 32 <NEW_LINE> DT_PREINIT_ARRAY = 32 <NEW_LINE> DT_PREINIT_ARRAYSZ = 33 <NEW_LINE> DT_LOOS = 0x6000000d <NEW_LINE> DT_HIOS = 0x6ffff000 <NEW_LINE> DT_LOPROC = 0x70000000 <NEW_LINE> DT_HIPROC = 0x7fffffff
d_tag enumeration
62598f9c56ac1b37e6301f99
class NotFound(HTTPException): <NEW_LINE> <INDENT> code = 404 <NEW_LINE> description = ( 'The requested URL was not found on the server. ' 'If you entered the URL manually please check your spelling and ' 'try again.' )
*404* `Not Found` Raise if a resource does not exist and never existed.
62598f9c76e4537e8c3ef365
class Rfid: <NEW_LINE> <INDENT> _s = serial.Serial() <NEW_LINE> _s.port = None <NEW_LINE> _s.baudrate = 9600 <NEW_LINE> _s.bytesize = 8 <NEW_LINE> _s.parity = 'N' <NEW_LINE> _s.stopbits = 1 <NEW_LINE> _s.timeout = 10 <NEW_LINE> crc = 0 <NEW_LINE> def CRC_calcCrc8(self, data): <NEW_LINE> <INDENT> dcdBitMask = 0x80 <NEW_LINE> for i in range(8): <NEW_LINE> <INDENT> xorFlag = self.crc & 0x8000 <NEW_LINE> self.crc <<= 1 <NEW_LINE> bit = ((data & dcdBitMask) == dcdBitMask) <NEW_LINE> self.crc |= bit <NEW_LINE> if xorFlag: <NEW_LINE> <INDENT> self.crc ^= 0x1021 <NEW_LINE> <DEDENT> dcdBitMask >>= 1 <NEW_LINE> <DEDENT> self.crc &= 0xffff <NEW_LINE> <DEDENT> def _tx(self, cmd): <NEW_LINE> <INDENT> self._s.flushInput() <NEW_LINE> if (cmd[0] != 255): <NEW_LINE> <INDENT> self.crc = 0xffff <NEW_LINE> cmd = (len(cmd)-1).to_bytes(1, byteorder='big') + cmd <NEW_LINE> for i in cmd: <NEW_LINE> <INDENT> self.CRC_calcCrc8(i) <NEW_LINE> <DEDENT> cmd = b'\xff' + cmd + self.crc.to_bytes(2, byteorder='big') <NEW_LINE> <DEDENT> print(cmd.hex()) <NEW_LINE> self._s.write(cmd) <NEW_LINE> <DEDENT> def _rx(self): <NEW_LINE> <INDENT> rx = self._s.read(255) <NEW_LINE> print(rx.hex()) <NEW_LINE> <DEDENT> def connect(self, device): <NEW_LINE> <INDENT> if device is None: <NEW_LINE> <INDENT> raise "A device MUST be given!" <NEW_LINE> <DEDENT> self._s.port = device <NEW_LINE> self._s.open() <NEW_LINE> <DEDENT> def disconnect(self): <NEW_LINE> <INDENT> self._s.close()
The basic class definition
62598f9c38b623060ffa8e40
class DerivedUpnpSensor(UpnpSensor): <NEW_LINE> <INDENT> def __init__(self, coordinator, device, sensor_type) -> None: <NEW_LINE> <INDENT> super().__init__(coordinator, device, sensor_type) <NEW_LINE> self._last_value = None <NEW_LINE> self._last_timestamp = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self) -> str: <NEW_LINE> <INDENT> return f"{self._device.name} {self._sensor_type['derived_name']}" <NEW_LINE> <DEDENT> @property <NEW_LINE> def unique_id(self) -> str: <NEW_LINE> <INDENT> return f"{self._device.udn}_{self._sensor_type['derived_unique_id']}" <NEW_LINE> <DEDENT> @property <NEW_LINE> def unit_of_measurement(self) -> str: <NEW_LINE> <INDENT> return self._sensor_type["derived_unit"] <NEW_LINE> <DEDENT> def _has_overflowed(self, current_value) -> bool: <NEW_LINE> <INDENT> return current_value < self._last_value <NEW_LINE> <DEDENT> @property <NEW_LINE> def state(self) -> str | None: <NEW_LINE> <INDENT> device_value_key = self._sensor_type["device_value_key"] <NEW_LINE> current_value = self.coordinator.data[device_value_key] <NEW_LINE> if current_value is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> current_timestamp = self.coordinator.data[TIMESTAMP] <NEW_LINE> if self._last_value is None or self._has_overflowed(current_value): <NEW_LINE> <INDENT> self._last_value = current_value <NEW_LINE> self._last_timestamp = current_timestamp <NEW_LINE> return None <NEW_LINE> <DEDENT> delta_value = current_value - self._last_value <NEW_LINE> if self._sensor_type["unit"] == DATA_BYTES: <NEW_LINE> <INDENT> delta_value /= KIBIBYTE <NEW_LINE> <DEDENT> delta_time = current_timestamp - self._last_timestamp <NEW_LINE> if delta_time.total_seconds() == 0: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> derived = delta_value / delta_time.total_seconds() <NEW_LINE> self._last_value = current_value <NEW_LINE> self._last_timestamp = current_timestamp <NEW_LINE> return format(derived, ".1f")
Representation of a UNIT Sent/Received per second sensor.
62598f9c3617ad0b5ee05eff
class Teleport(CustomAction): <NEW_LINE> <INDENT> def __init__(self, state_clone, action, steps, reward): <NEW_LINE> <INDENT> self.state_clone = state_clone <NEW_LINE> self.action = action <NEW_LINE> self.steps = steps <NEW_LINE> self.reward = reward <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "Teleport({}, {}, {})".format(self.action, self.steps, self.reward) <NEW_LINE> <DEDENT> __repr__ = __str__
Step reloads the provided ALEState
62598f9cadb09d7d5dc0a339
class Experiment(object): <NEW_LINE> <INDENT> pass
Experiment Handler
62598f9c85dfad0860cbf94c
class Session(BaseModel): <NEW_LINE> <INDENT> STATUS = ( ('L', 'link_sent'), ('LNS', 'link_not_sent'), ('C', 'completed'), ('P', 'in_process'), ('F', 'failure'), ) <NEW_LINE> MEDIUM = ( ('facebook', 'Facebook'), ('webchat', 'WebChat'), ('skype', 'Skype') ) <NEW_LINE> recipient_id = models.CharField(max_length=1000, blank=False) <NEW_LINE> recipient_email = models.CharField(max_length=100, blank=False, default='') <NEW_LINE> recipient_phone = models.CharField(max_length=13, blank=False, default='') <NEW_LINE> tree = models.ForeignKey(Tree, related_name='sessions', on_delete=models.SET_NULL, null=True) <NEW_LINE> start_date = models.DateTimeField(auto_now_add=True) <NEW_LINE> state = models.ForeignKey( TreeState, blank=True, null=True, help_text="None if the session is complete.") <NEW_LINE> num_tries = models.PositiveIntegerField(default=0, help_text="The number of times the user has tried to answer the " "current question.") <NEW_LINE> canceled = models.NullBooleanField(blank=True, null=True) <NEW_LINE> last_modified = models.DateTimeField(auto_now=True, null=True) <NEW_LINE> question_answer_pair = models.ManyToManyField(QuestionAnswerPair) <NEW_LINE> belongs_to = models.ForeignKey('auths.Client', related_name='sessions') <NEW_LINE> status = models.CharField(max_length=3, choices=STATUS, default='') <NEW_LINE> objects = SessionQuerySet.as_manager() <NEW_LINE> temporary_validation = models.CharField(max_length=50, blank=True) <NEW_LINE> trial = models.BooleanField(default=False) <NEW_LINE> is_active = models.BooleanField(default=True) <NEW_LINE> medium = models.CharField(max_length=10, choices=MEDIUM, default='facebook') <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.recipient_email <NEW_LINE> <DEDENT> def cancel(self): <NEW_LINE> <INDENT> return self.close(canceled=True) <NEW_LINE> <DEDENT> def close(self, canceled=False): <NEW_LINE> <INDENT> if not self.is_closed(): <NEW_LINE> <INDENT> self.state = None <NEW_LINE> self.canceled = canceled <NEW_LINE> self.save() <NEW_LINE> <DEDENT> <DEDENT> def is_closed(self): <NEW_LINE> <INDENT> return not bool(self.state_id) or self.canceled <NEW_LINE> <DEDENT> def is_open(self): <NEW_LINE> <INDENT> return bool(self.state_id) and not self.canceled
A Session represents a single person's current status traversing through a Tree. It is a way to persist information about what state they are in, how many retries they have had, etc. so that we aren't storing all of that in-memory.
62598f9c097d151d1a2c0dd6
@register_op(doc_str="") <NEW_LINE> class reverse(Operation): <NEW_LINE> <INDENT> input_spec = InputSpec( x=TensorInputType(), axes=IntTensorInputType(const=True, optional=True), ) <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(reverse, self).__init__(**kwargs) <NEW_LINE> <DEDENT> def type_inference(self): <NEW_LINE> <INDENT> return self.x.sym_type <NEW_LINE> <DEDENT> @precondition(allow=VALUE) <NEW_LINE> def value_inference(self): <NEW_LINE> <INDENT> res = self.x.val <NEW_LINE> axes = self.axes.val if self.axes is not None else range(self.x.rank) <NEW_LINE> for axis in axes: <NEW_LINE> <INDENT> res = np.flip(res, axis=axis) <NEW_LINE> <DEDENT> return res
Reverses the order of the input tensor ``x`` along specified ``axes``(dimensions). Parameters ---------- x: tensor<*?, T> (Required) * Input tensor. axes: const<D, i32> Optional * Dimension(s) to reverse. Each axis must be in the range ``[-rank(x), rank(x)]``. * Defaults to None (reverse on all dimensions). Returns ------ tensor<*?, T> - same type and shape as the input tensor. Attributes ---------- T: fp32
62598f9c7d847024c075c182
class DailyCache(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._dict = {} <NEW_LINE> self._daemon_start() <NEW_LINE> <DEDENT> def _daemon_start(self): <NEW_LINE> <INDENT> t = threading.Thread(target=self._daemon_run) <NEW_LINE> t.setName('DailyCache') <NEW_LINE> t.setDaemon(True) <NEW_LINE> t.start() <NEW_LINE> <DEDENT> def _daemon_run(self): <NEW_LINE> <INDENT> next_run_time = datetime.date.today().strftime('%Y-%m-%d') + ' ' + '00:00:01' <NEW_LINE> next_run_time = datetime.datetime.strptime(next_run_time, '%Y-%m-%d %H:%M:%S') <NEW_LINE> next_run_time = next_run_time + datetime.timedelta(days=1) <NEW_LINE> while True: <NEW_LINE> <INDENT> if datetime.datetime.now() >= next_run_time: <NEW_LINE> <INDENT> next_run_time = next_run_time + datetime.timedelta(days=1) <NEW_LINE> self.reset() <NEW_LINE> <DEDENT> time.sleep(1) <NEW_LINE> <DEDENT> <DEDENT> def reset(self): <NEW_LINE> <INDENT> log = logger.get(__name__) <NEW_LINE> log.debug('reset daily data cache.') <NEW_LINE> self._dict = {} <NEW_LINE> <DEDENT> def set(self, key, value): <NEW_LINE> <INDENT> self._dict[key] = value <NEW_LINE> <DEDENT> def get(self, key): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self._dict[key] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return None
每日零点自动重置的缓存器
62598f9c32920d7e50bc5e06
class Fragment(object): <NEW_LINE> <INDENT> __slots__ = ('children',) <NEW_LINE> def __init__(self, *args): <NEW_LINE> <INDENT> self.children = [] <NEW_LINE> for arg in args: <NEW_LINE> <INDENT> self.append(arg) <NEW_LINE> <DEDENT> <DEDENT> def __html__(self): <NEW_LINE> <INDENT> return Markup(str(self)) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return ''.join(escape(c, False) for c in self.children) <NEW_LINE> <DEDENT> def __add__(self, other): <NEW_LINE> <INDENT> return Fragment(self, other) <NEW_LINE> <DEDENT> def __call__(self, *args): <NEW_LINE> <INDENT> for arg in args: <NEW_LINE> <INDENT> self.append(arg) <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> def append(self, arg): <NEW_LINE> <INDENT> if arg: <NEW_LINE> <INDENT> if isinstance(arg, (Fragment, str, bytes, int, float)): <NEW_LINE> <INDENT> self.children.append(arg) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> for elt in arg: <NEW_LINE> <INDENT> self.append(elt) <NEW_LINE> <DEDENT> <DEDENT> except TypeError: <NEW_LINE> <INDENT> self.children.append(arg) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> elif arg == 0: <NEW_LINE> <INDENT> self.children.append('0') <NEW_LINE> <DEDENT> <DEDENT> def as_text(self): <NEW_LINE> <INDENT> return ''.join(c.as_text() if isinstance(c, Fragment) else str(c) for c in self.children)
A fragment represents a sequence of strings or elements.
62598f9c8e71fb1e983bb865
class UndefinedGeographicCoordinateReferenceSystem(SpatialReferenceSystem): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(UndefinedGeographicCoordinateReferenceSystem, self).__init__() <NEW_LINE> <DEDENT> spatial_ref_sys_name = "undefined geographic coordinate reference system" <NEW_LINE> srs_identifier = 0 <NEW_LINE> srs_organization = "NONE" <NEW_LINE> srs_organization_coordsys_id = 0 <NEW_LINE> srs_definition = "undefined" <NEW_LINE> srs_description = " " <NEW_LINE> @staticmethod <NEW_LINE> def invert_y(z, y): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def get_coord(self, z, x, y): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def truncate(coord): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def pixel_x_size(self, z): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def pixel_y_size(self, z): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @property <NEW_LINE> def tile_size(self): <NEW_LINE> <INDENT> raise NotImplementedError()
undefined geographic coordinate reference systems projection class. see: http://www.geopackage.org/spec121/#r11
62598f9c0a50d4780f705189
class ExtensionMixin(object): <NEW_LINE> <INDENT> input_exts = None <NEW_LINE> output_ext = None <NEW_LINE> def __init__(self, input_ext=None, input_exts=None, output_ext=None, *args, **kwargs): <NEW_LINE> <INDENT> super(ExtensionMixin, self).__init__(*args, **kwargs) <NEW_LINE> if input_ext: <NEW_LINE> <INDENT> self.input_ext = input_ext <NEW_LINE> <DEDENT> if input_exts: <NEW_LINE> <INDENT> self.input_exts = input_exts <NEW_LINE> <DEDENT> if output_ext: <NEW_LINE> <INDENT> self.output_ext = output_ext <NEW_LINE> <DEDENT> if not self.input_exts and self.input_ext: <NEW_LINE> <INDENT> self.input_exts = (self.input_ext,) <NEW_LINE> <DEDENT> <DEDENT> def _matches_input(self, intput_path): <NEW_LINE> <INDENT> if self.input_exts: <NEW_LINE> <INDENT> return re.search(r'\.({0})$'.format('|'.join(self.input_exts)), intput_path) <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def _matches_output(self, output_path): <NEW_LINE> <INDENT> if self.output_ext: <NEW_LINE> <INDENT> return re.search(r'\.{0}$'.format(self.output_ext), output_path) <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def _derive_input_paths(self, output_path): <NEW_LINE> <INDENT> paths = [] <NEW_LINE> if self.input_exts: <NEW_LINE> <INDENT> for ext in self.input_exts: <NEW_LINE> <INDENT> ext = '.' + ext <NEW_LINE> paths.append(output_path + ext) <NEW_LINE> paths.append(re.sub(r'\.[^\.]*$', ext, output_path)) <NEW_LINE> <DEDENT> <DEDENT> return paths <NEW_LINE> <DEDENT> def _derive_output_path(self, input_path): <NEW_LINE> <INDENT> if self.output_ext: <NEW_LINE> <INDENT> path = re.sub(r'\.{0}'.format(self.output_ext), '', input_path) <NEW_LINE> ext = '.' + self.output_ext <NEW_LINE> return re.sub(r'\.[^\.]*$', ext, path) <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def set_input_ext(self, value): <NEW_LINE> <INDENT> self.input_exts = (value,) <NEW_LINE> <DEDENT> input_ext = property(fset=set_input_ext)
A mixin for filters that take a file with a certain file extension and output another. For example, SassFilter generally takes files with the exentions ".scss" and ".sass" and output CSS files (".css"). Attributes: input_exts: A tuple of extensions (without the prefixed ".") output_ext: A single output extension (again, without the prefixed ".")
62598f9c3eb6a72ae038a3f0
class DateEncoder(json.JSONEncoder): <NEW_LINE> <INDENT> def default(self, o): <NEW_LINE> <INDENT> if isinstance(o, datetime): <NEW_LINE> <INDENT> return [o.year, o.month, o.day, o.minute, o.second, o.microsecond] <NEW_LINE> <DEDENT> elif isinstance(o, date): <NEW_LINE> <INDENT> return [o.year, o.month, o.day] <NEW_LINE> <DEDENT> return json.JSONEncoder.default(self, o)
Encode dates and datetimes as lists.
62598f9c8da39b475be02f95
class ExportSingleText(G2IO.ExportBaseclass): <NEW_LINE> <INDENT> def __init__(self,G2frame): <NEW_LINE> <INDENT> super(self.__class__,self).__init__( G2frame=G2frame, formatName = 'Text file', extension='.txt', longFormatName = 'Export reflection list as a text file' ) <NEW_LINE> self.exporttype = ['single'] <NEW_LINE> self.multiple = False <NEW_LINE> <DEDENT> def Exporter(self,event=None): <NEW_LINE> <INDENT> self.InitExport(event) <NEW_LINE> self.loadTree() <NEW_LINE> if self.ExportSelect( AskFile='default' ): return <NEW_LINE> self.OpenFile() <NEW_LINE> hist = self.histnam[0] <NEW_LINE> histblk = self.Histograms[hist] <NEW_LINE> hklfmt = "{:.0f},{:.0f},{:.0f}" <NEW_LINE> hfmt = "{:>10s} {:>8s} {:>12s} {:>12s} {:>12s} {:>7s} {:>6s}" <NEW_LINE> fmt = "{:>10s} {:8.3f} {:12.2f} {:12.4f} {:12.2f} {:7.2f} {:6.0f}" <NEW_LINE> self.Write(80*'=') <NEW_LINE> self.Write(hfmt.format("h,k,l","d-space","F_obs","sig(Fobs)","F_calc","phase","twin")) <NEW_LINE> self.Write(80*'=') <NEW_LINE> for ( h,k,l,twin,dsp,Fobs,sigFobs,Fcalc,FobsT,FcalcT,phase,Icorr ) in histblk['Data']['RefList']: <NEW_LINE> <INDENT> if twin > 0: <NEW_LINE> <INDENT> self.Write(fmt.format(hklfmt.format(h,k,l),dsp,Fobs,sigFobs,Fcalc,phase,twin)) <NEW_LINE> <DEDENT> <DEDENT> self.CloseFile() <NEW_LINE> print(str(hist)+' written to file '+str(self.fullpath))
Used to create a text file with single crystal reflection data skips user rejected & space group extinct reflections :param wx.Frame G2frame: reference to main GSAS-II frame
62598f9c6aa9bd52df0d4c7d
class DocumentClass(Macro): <NEW_LINE> <INDENT> def __init__(self, flap): <NEW_LINE> <INDENT> super().__init__(flap, "documentclass", None, None) <NEW_LINE> <DEDENT> def _capture_arguments(self, parser, invocation): <NEW_LINE> <INDENT> invocation.append_argument("options", parser.read.options()) <NEW_LINE> invocation.append_argument("class", parser.read.group()) <NEW_LINE> <DEDENT> def execute2(self, parser, invocation): <NEW_LINE> <INDENT> class_name = self.find_class_name(parser, invocation) <NEW_LINE> self._flap.relocate_dependency(class_name, invocation) <NEW_LINE> <DEDENT> def find_class_name(self, parser, invocation): <NEW_LINE> <INDENT> tokens = invocation.argument("class") <NEW_LINE> return "".join(each_token.as_text for each_token in tokens[1:-1]) <NEW_LINE> <DEDENT> def rewrite2(self, parser, invocation): <NEW_LINE> <INDENT> class_name = self.find_class_name(parser, invocation) <NEW_LINE> if class_name == "subfiles": <NEW_LINE> <INDENT> parser.read.until_text(r"\begin{document}", True) <NEW_LINE> document = parser.read.until_text(r"\end{document}", True) <NEW_LINE> logger.debug("Subfile extraction" + "".join(str(t) for t in document)) <NEW_LINE> return parser.evaluate(document[:-11], dict()) <NEW_LINE> <DEDENT> return invocation.as_tokens
Extract some specific document class, e.g., subfile
62598f9ca219f33f346c65ca