code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class Query(object): <NEW_LINE> <INDENT> Selectors = namedtuple('Selectors', ['date_search', 'number', 'filters', 'return_object']) <NEW_LINE> DateSearch = namedtuple('DateSearch', ['type', 'values']) <NEW_LINE> ReturnObjects = {'NEO': NearEarthObject, 'Path': OrbitPath} <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.date = kwargs.get('date', None) <NEW_LINE> self.end_date = kwargs.get('end_date', None) <NEW_LINE> self.filter = kwargs.get('filter', None) <NEW_LINE> self.number = kwargs.get('number', None) <NEW_LINE> self.start_date = kwargs.get('start_date', None) <NEW_LINE> self.return_object = kwargs.get('return_object', None) <NEW_LINE> <DEDENT> def build_query(self): <NEW_LINE> <INDENT> search_date = Query.DateSearch(DateSearch.equals.name, self.date) if self.date else Query.DateSearch(DateSearch.between.name, [self.start_date, self.end_date]) <NEW_LINE> object_to_return = Query.ReturnObjects.get(self.return_object) <NEW_LINE> filters=[] <NEW_LINE> if self.filter: <NEW_LINE> <INDENT> options = Filter.create_filter_options(self.filter) <NEW_LINE> for key, val in options.items(): <NEW_LINE> <INDENT> for a_filter in val: <NEW_LINE> <INDENT> option = a_filter.split(':')[0] <NEW_LINE> operation = a_filter.split(':')[1] <NEW_LINE> value = a_filter.split(':')[-1] <NEW_LINE> filters.append(Filter(option, key, operation, value)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return Query.Selectors(search_date, self.number, filters, object_to_return)
Object representing the desired search query operation to build. The Query uses the Selectors to structure the query information into a format the NEOSearcher can use for date search.
62598fac92d797404e388b39
class ProjectSupportEditAnswerView(ProjectDiscussionEditAnswerView): <NEW_LINE> <INDENT> def get_success_url(self): <NEW_LINE> <INDENT> return reverse('project_support_view', args=[self.project_translation.slug, self.current_question.id])
Edit a given project sheet support answer
62598fac4428ac0f6e6584ce
class Corpus: <NEW_LINE> <INDENT> def __init__(self, path, index=True, trie=True): <NEW_LINE> <INDENT> self._index = Index() if index else None <NEW_LINE> self._trie = Trie() if trie else None <NEW_LINE> path = pathlib.Path(path) <NEW_LINE> for i, doc in enumerate(sorted(path.rglob("*.txt"))): <NEW_LINE> <INDENT> if i % 500 == 0: <NEW_LINE> <INDENT> print(f'Building Corpus: Read {i:5} documents.') <NEW_LINE> <DEDENT> doc = Document(doc) <NEW_LINE> if index: <NEW_LINE> <INDENT> self._index.add_doc(doc) <NEW_LINE> <DEDENT> if trie: <NEW_LINE> <INDENT> self._trie.add_doc(doc) <NEW_LINE> <DEDENT> <DEDENT> print(f'Built corpus from {i} documents.') <NEW_LINE> <DEDENT> def search(self, query: str) -> [(str, float)]: <NEW_LINE> <INDENT> if self._index: <NEW_LINE> <INDENT> return self._index.query(query) <NEW_LINE> <DEDENT> <DEDENT> def complete(self, query: str) -> [(str, Location)]: <NEW_LINE> <INDENT> if self._trie: <NEW_LINE> <INDENT> return self._trie.complete(query)
A corpus of documents that supports: - search: given a query, return a list of contained documents ranked by relevance - compelte: given a query, return prefix-matched words from the corpus
62598fac5166f23b2e243383
class Relay_Logic(QThread): <NEW_LINE> <INDENT> relay02_setmaxtemp = 25.50 <NEW_LINE> relay02_setmintemp = 18.50 <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> QThread.__init__(self) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> self.relay01_logic() <NEW_LINE> <DEDENT> def relay01_deactivate(self): <NEW_LINE> <INDENT> self.btn_relay01off.setEnabled(False) <NEW_LINE> self.btn_relay01on.setEnabled(True) <NEW_LINE> print ("Relay 1 off!") <NEW_LINE> <DEDENT> def relay02_activate(self): <NEW_LINE> <INDENT> self.btn_relay02off.setEnabled(True) <NEW_LINE> self.btn_relay02on.setEnabled(False) <NEW_LINE> print ("Relay 2 on!") <NEW_LINE> <DEDENT> def relay02_deactivate(self): <NEW_LINE> <INDENT> self.btn_relay02off.setEnabled(False) <NEW_LINE> self.btn_relay02on.setEnabled(True) <NEW_LINE> print ("Relay 2 off!")
Logic that is used for automatic relay control
62598facf548e778e596b54e
@override_settings( LANGUAGES=[('en', 'English')], LANGUAGE_CODE='en', TEMPLATES=AUTH_TEMPLATES, ROOT_URLCONF='auth_tests.urls', ) <NEW_LINE> class AuthViewsTestCase(TestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setUpTestData(cls): <NEW_LINE> <INDENT> cls.u1 = User.objects.create_user(username='testclient', password='password', email='testclient@example.com') <NEW_LINE> cls.u3 = User.objects.create_user(username='staff', password='password', email='staffmember@example.com') <NEW_LINE> <DEDENT> def login(self, username='testclient', password='password', url='/login/'): <NEW_LINE> <INDENT> response = self.client.post(url, { 'username': username, 'password': password, }) <NEW_LINE> self.assertIn(SESSION_KEY, self.client.session) <NEW_LINE> return response <NEW_LINE> <DEDENT> def logout(self): <NEW_LINE> <INDENT> response = self.client.get('/admin/logout/') <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> self.assertNotIn(SESSION_KEY, self.client.session) <NEW_LINE> <DEDENT> def assertFormError(self, response, error): <NEW_LINE> <INDENT> form_errors = list(itertools.chain(*response.context['form'].errors.values())) <NEW_LINE> self.assertIn(str(error), form_errors)
Helper base class for all the follow test cases.
62598fac3cc13d1c6d465716
class GCIOrgAppEditPageTest(test_utils.GCIDjangoTestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.init() <NEW_LINE> self.url = '/gci/org/application/edit/%s' % self.gci.key().name() <NEW_LINE> self.post_params = { 'title': 'Test Title', 'short_name': 'Test Short Name', 'content': 'Test Content', 'survey_start': '2011-10-13 00:00:00', 'survey_end': '2011-10-13 00:00:00', 'schema': 'Test Scheme', } <NEW_LINE> <DEDENT> def assertTemplatesUsed(self, response): <NEW_LINE> <INDENT> self.assertGCITemplatesUsed(response) <NEW_LINE> self.assertTemplateUsed(response, 'modules/gci/org_app/edit.html') <NEW_LINE> self.assertTemplateUsed(response, 'modules/gci/_form.html') <NEW_LINE> <DEDENT> def testProgramHostAccessGranted(self): <NEW_LINE> <INDENT> user = profile_utils.seedNDBUser(host_for=[self.program]) <NEW_LINE> profile_utils.loginNDB(user) <NEW_LINE> response = self.get(self.url) <NEW_LINE> self.assertResponseOK(response) <NEW_LINE> <DEDENT> def testLoneUserAccessDenied(self): <NEW_LINE> <INDENT> user = profile_utils.seedNDBUser() <NEW_LINE> profile_utils.loginNDB(user) <NEW_LINE> response = self.get(self.url) <NEW_LINE> self.assertResponseForbidden(response) <NEW_LINE> <DEDENT> def testEditPage(self): <NEW_LINE> <INDENT> user = profile_utils.seedNDBUser(host_for=[self.program]) <NEW_LINE> profile_utils.loginNDB(user) <NEW_LINE> response = self.get(self.url) <NEW_LINE> self.assertTemplatesUsed(response) <NEW_LINE> response = self.post(self.url, self.post_params) <NEW_LINE> self.assertResponseRedirect(response, '%s?validated' % self.url) <NEW_LINE> query = org_app_survey.OrgAppSurvey.all().filter('program = ', self.gci) <NEW_LINE> self.assertEqual(query.count(), 1, ('There must be one and only one OrgAppSurvey ' 'instance for the program.')) <NEW_LINE> survey = query.get() <NEW_LINE> self.assertEqual(survey.title, self.post_params['title']) <NEW_LINE> self.assertEqual( org_app_survey.OrgAppSurvey.modified_by.get_value_for_datastore(survey), user.key.to_old_key())
Tests for organization applications edit page.
62598facd486a94d0ba2bf79
class TextAreaListField(TextAreaField): <NEW_LINE> <INDENT> def _value(self): <NEW_LINE> <INDENT> return '\n'.join(self.data) if self.data else '' <NEW_LINE> <DEDENT> def process_formdata(self, valuelist): <NEW_LINE> <INDENT> self.data = valuelist[0].splitlines() if valuelist else []
textarea transparently handling list of items
62598fac23849d37ff85105f
class OTPSlot(): <NEW_LINE> <INDENT> def __init__(self, name, key, base32_encoded, salt, digits): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.key = key <NEW_LINE> self.base32_encoded = base32_encoded <NEW_LINE> self.salt = salt <NEW_LINE> self.digits = digits
Base OTP slot representation
62598faca8370b77170f0386
class User(Model): <NEW_LINE> <INDENT> def __init__(self, form): <NEW_LINE> <INDENT> self.id = form.get('id', None) <NEW_LINE> self.username = form.get('username', '') <NEW_LINE> self.password = form.get('password', '') <NEW_LINE> <DEDENT> def salted_password(self, password, salt='$!@><?>HUI&DWQa`'): <NEW_LINE> <INDENT> import hashlib <NEW_LINE> def sha256(ascii_str): <NEW_LINE> <INDENT> return hashlib.sha256(ascii_str.encode('ascii')).hexdigest() <NEW_LINE> <DEDENT> hash1 = sha256(password) <NEW_LINE> hash2 = sha256(hash1 + salt) <NEW_LINE> return hash2 <NEW_LINE> <DEDENT> def hashed_password(self, pwd): <NEW_LINE> <INDENT> import hashlib <NEW_LINE> p = pwd.encode('ascii') <NEW_LINE> s = hashlib.sha256(p) <NEW_LINE> return s.hexdigest() <NEW_LINE> <DEDENT> def validate_register(self): <NEW_LINE> <INDENT> pwd = self.password <NEW_LINE> self.password = self.salted_password(pwd) <NEW_LINE> if User.find_by(username=self.username) is None: <NEW_LINE> <INDENT> self.save() <NEW_LINE> return self <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def validate_login(self): <NEW_LINE> <INDENT> u = User.find_by(username=self.username) <NEW_LINE> if u is not None: <NEW_LINE> <INDENT> return u.password == self.salted_password(self.password) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def todos(self): <NEW_LINE> <INDENT> ts = [] <NEW_LINE> for t in Todo.all(): <NEW_LINE> <INDENT> if t.user_id == self.id: <NEW_LINE> <INDENT> ts.append(t) <NEW_LINE> <DEDENT> <DEDENT> return ts
User 是一个保存用户数据的 model 现在只有两个属性 username 和 password
62598faccb5e8a47e493c14e
class Sprite(pygame.sprite.Sprite): <NEW_LINE> <INDENT> def __init__(self, entity, view): <NEW_LINE> <INDENT> pygame.sprite.Sprite.__init__(self) <NEW_LINE> self.entity = entity <NEW_LINE> self.view = view <NEW_LINE> self.color = self.get_color() <NEW_LINE> self.store_image() <NEW_LINE> <DEDENT> def store_image(self): <NEW_LINE> <INDENT> self.surface = pygame.Surface([self.entity.get_width() * self.view.get_cell_width(), self.entity.get_height() * self.view.get_cell_height()]) <NEW_LINE> self.surface.set_colorkey((0, 0, 0)) <NEW_LINE> self.shape = [] <NEW_LINE> for s in self.get_shape(): <NEW_LINE> <INDENT> self.shape.append([ s[0] * self.view.get_cell_width(), s[1] * self.view.get_cell_height() ]) <NEW_LINE> <DEDENT> pygame.draw.polygon( self.surface, self.color, self.shape, 0) <NEW_LINE> <DEDENT> def get_color(self): <NEW_LINE> <INDENT> color = self.entity.get_color() <NEW_LINE> if self.entity in self.view.agent_interaction: <NEW_LINE> <INDENT> interaction = self.view.agent_interaction[self.entity] <NEW_LINE> if isinstance(interaction, model.interaction.PrimitivePerceptionInteraction): <NEW_LINE> <INDENT> interaction = interaction.get_primitive_interaction() <NEW_LINE> <DEDENT> if interaction.get_name() == "Step" and interaction.get_result() == "Fail": <NEW_LINE> <INDENT> color = (255,0,0,255) <NEW_LINE> <DEDENT> elif interaction.get_name() == "Cuddle" and interaction.get_result() == "Succeed": <NEW_LINE> <INDENT> color = (0,255,0,255) <NEW_LINE> <DEDENT> <DEDENT> return color <NEW_LINE> <DEDENT> def get_surface(self): <NEW_LINE> <INDENT> color = self.get_color() <NEW_LINE> if color != self.color: <NEW_LINE> <INDENT> self.color = color <NEW_LINE> self.store_image() <NEW_LINE> <DEDENT> return self.surface <NEW_LINE> <DEDENT> def get_shape(self): <NEW_LINE> <INDENT> if isinstance(self.entity, model.agent.Agent): <NEW_LINE> <INDENT> return [[.2, .25], [.2, .75], [.85, 0.5]] <NEW_LINE> <DEDENT> elif isinstance(self.entity, model.structure.Block) or isinstance(self.entity, model.structure.Food): <NEW_LINE> <INDENT> return [ [0.35,0.35], [0.35, self.entity.get_height() - 1 + 0.65], [self.entity.get_width()- 1 + 0.65, self.entity.get_height() - 1 + 0.65], [self.entity.get_width() - 1 + 0.65, 0.35], [0.35,0.35] ] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [[0,0], [0,1], [1,1], [1,0], [0,0]] <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def rect(self): <NEW_LINE> <INDENT> return pygame.Rect( self.entity.get_position().get_x() * self.view.get_cell_width(), self.entity.get_position().get_y() * self.view.get_cell_height(), self.view.get_cell_width(), self.view.get_cell_height() ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def image(self): <NEW_LINE> <INDENT> surface = self.get_surface() <NEW_LINE> if self.entity.get_rotation() != 0: <NEW_LINE> <INDENT> surface = rot_center(surface, self.entity.get_rotation()) <NEW_LINE> return surface <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return surface
Class to represent world entities as sprites.
62598fac38b623060ffa9044
class Monitor(TimestampedModelMixin, UUIDPrimaryKeyMixin): <NEW_LINE> <INDENT> name = models.CharField(verbose_name=_("name"), max_length=80) <NEW_LINE> user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.PROTECT, verbose_name=_("user") ) <NEW_LINE> domain = models.ForeignKey( EnforcementDomain, on_delete=models.PROTECT, help_text=_("The enforcement domain user can monitor"), ) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = _("monitor") <NEW_LINE> verbose_name_plural = _("monitors") <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.name
A person who monitors through the Monitoring API.
62598fac3346ee7daa33761e
class GuessRacetrackGame(GuessingGame): <NEW_LINE> <INDENT> def __init__(self, bot): <NEW_LINE> <INDENT> excel_dict = pd.read_excel("data/Racetracks.xlsx").to_dict() <NEW_LINE> data = self._convert_pandas_dict(excel_dict) <NEW_LINE> data = [{**x, "name": x["Name"]} for x in data] <NEW_LINE> super().__init__( command="!rstart", attributes=list(excel_dict.keys()), object_pool=data, ) <NEW_LINE> self.bot = bot <NEW_LINE> self.points = 30 <NEW_LINE> <DEDENT> def _start_message(self, _): <NEW_LINE> <INDENT> return "Race track guessing started!" <NEW_LINE> <DEDENT> def _stop_message(self): <NEW_LINE> <INDENT> return "Stopped guessing race tracks." <NEW_LINE> <DEDENT> def _winner_message(self, obj, user): <NEW_LINE> <INDENT> return f"{self.bot.twitch.display_name(user)} guessed correctly! It was {obj['name']}" <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _name_hint(obj): <NEW_LINE> <INDENT> return f"Its name starts with '{obj['Name'][0]}'." <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _country_hint(obj): <NEW_LINE> <INDENT> return f"It's located in {obj['Country']}." <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _length_hint(obj): <NEW_LINE> <INDENT> return f"The race track is {obj['Length']} long." <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _corners_hint(obj): <NEW_LINE> <INDENT> return f"It has {obj['Corners']} corners." <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _cornername_hint(obj): <NEW_LINE> <INDENT> return f"A corner is called: {obj['Cornername']}"
Play the Guess The Minion Game. One Minion is randomly chosen from the list and the users have to guess which on it is. Give points to the winner.
62598fac851cf427c66b8267
class testemptypotion: <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def reset(): pass <NEW_LINE> type=0 <NEW_LINE> subtype=1 <NEW_LINE> name="empty" <NEW_LINE> hpr=0 <NEW_LINE> mpr=0
Empty potion
62598fac01c39578d7f12d2a
class MostraOcultaPontos(bpy.types.Operator): <NEW_LINE> <INDENT> bl_idname = "object.rhin_mostra_oculta_pontos" <NEW_LINE> bl_label = "Nose dists" <NEW_LINE> def execute(self, context): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if bpy.data.collections['Anatomical Points - Soft Tissue'].hide_viewport == False: <NEW_LINE> <INDENT> print("HIDE FALSE") <NEW_LINE> bpy.data.collections['Anatomical Points - Soft Tissue'].hide_viewport = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("HIDE TRUE") <NEW_LINE> bpy.data.collections['Anatomical Points - Soft Tissue'].hide_viewport = False <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> print("A coleção Anatomical Points - Soft Tissue não existe!") <NEW_LINE> <DEDENT> return {'FINISHED'}
Tooltip
62598fac97e22403b383aeb8
class PolicyViolationException(RuntimeError): <NEW_LINE> <INDENT> pass
Запускается при обнаружении нарушения политики обработки набора правил Появляется, например, когда используется политика обработки `error`, а для какого-то входного файла не находится ни одного соответствующего ему действия.
62598fac379a373c97d98fbe
class MyManager(models.Manager): <NEW_LINE> <INDENT> def get_query_set(self): <NEW_LINE> <INDENT> return self.model.QuerySet(self.model)
Custom query manager that allows for overriding the default __repr__. The purpose is to make a more user friendly output for event queries. http://stackoverflow.com/questions/2163151/custom-queryset-and-manager-without-breaking-dry https://docs.djangoproject.com/en/1.5/topics/db/managers/#custom-managers
62598fac442bda511e95c402
class IndicatorRelationship(db.Model): <NEW_LINE> <INDENT> __tablename__ = "indicatorRelationships" <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> source_id = Column(String(255), ForeignKey("indicators.id")) <NEW_LINE> source = relationship("Indicator", foreign_keys=source_id) <NEW_LINE> target_id = Column(String(255), ForeignKey("indicators.id")) <NEW_LINE> target = relationship("Indicator", foreign_keys=target_id) <NEW_LINE> type = Column(String(50)) <NEW_LINE> __mapper_args__ = { 'polymorphic_identity': 'indicatorRelationships', 'polymorphic_on': type } <NEW_LINE> def __init__(self, source=None, target=None): <NEW_LINE> <INDENT> self.source = source <NEW_LINE> self.target = target
classdocs
62598fac16aa5153ce4004ad
class custom_jvp(Generic[R]): <NEW_LINE> <INDENT> def __init__(self, fun: Callable[..., R], static_argnums: Tuple[int, ...] = ()): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> static_argnums = tuple(sorted(static_argnums)) <NEW_LINE> self.jvp = jax.custom_jvp(fun, nondiff_argnums=static_argnums) <NEW_LINE> <DEDENT> def defjvp(self, jvp: Callable[..., Tuple[R, R]]) -> None: <NEW_LINE> <INDENT> self.jvp.defjvp(jvp) <NEW_LINE> <DEDENT> def __call__(self, *args: Any) -> R: <NEW_LINE> <INDENT> return self.jvp(*args) <NEW_LINE> <DEDENT> def __get__(self, instance: Any, owner: Any = None) -> Callable[..., R]: <NEW_LINE> <INDENT> if instance is None: <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> return Partial(self, instance)
This is a shim class over jax.custom_jvp to: - allow custom_vjp to be used on methods, and - rename nondiff_argnums to static_argnums.
62598fac8da39b475be0318f
class Test_reformat(unittest.TestCase): <NEW_LINE> <INDENT> def test_abbreviate_firstname(self): <NEW_LINE> <INDENT> self.assertEqual( bib.reformat.abbreviate_firstname("de Geus, Thomas Willem Jan"), "de Geus, T. W. J.", ) <NEW_LINE> self.assertEqual( bib.reformat.abbreviate_firstname("de Geus, Thomas Willem Jan", sep=" "), "de Geus, T. W. J.", ) <NEW_LINE> self.assertEqual( bib.reformat.abbreviate_firstname("de Geus, Thomas W. J.", sep=" "), "de Geus, T. W. J.", ) <NEW_LINE> self.assertEqual( bib.reformat.abbreviate_firstname("de Geus, Thomas W.J.", sep=" "), "de Geus, T. W. J.", ) <NEW_LINE> self.assertEqual( bib.reformat.abbreviate_firstname(r"Molinari, Jean-Fran{\c c}ois", sep=" "), "Molinari, J.- F.", ) <NEW_LINE> self.assertEqual( bib.reformat.abbreviate_firstname(r"Temizer, \.{I}.", sep=" "), r"Temizer, \.{I}.", ) <NEW_LINE> self.assertEqual( bib.reformat.abbreviate_firstname(r"Temizer, \.{I}.\.{I}.", sep=" "), r"Temizer, \.{I}. \.{I}.", ) <NEW_LINE> self.assertEqual( bib.reformat.abbreviate_firstname(r"Temizer, \.{I}.\.{I}zemer", sep=" "), r"Temizer, \.{I}. \.{I}.", ) <NEW_LINE> <DEDENT> def test_protect_math(self): <NEW_LINE> <INDENT> simple = r"$\tau$" <NEW_LINE> self.assertEqual(bib.reformat.protect_math(simple), simple) <NEW_LINE> <DEDENT> def test_rm_unicode(self): <NEW_LINE> <INDENT> simple = r"$de Geus, Tom$" <NEW_LINE> self.assertEqual(bib.reformat.rm_unicode(simple), simple) <NEW_LINE> <DEDENT> def test_rm_accents(self): <NEW_LINE> <INDENT> self.assertEqual(bib.reformat.rm_accents("école"), "ecole") <NEW_LINE> self.assertEqual(bib.reformat.rm_accents("École"), "Ecole") <NEW_LINE> <DEDENT> def test_name2key(self): <NEW_LINE> <INDENT> self.assertEqual(bib.reformat.name2key("de Geus, Tom"), "DeGeus")
GooseBib.reformat
62598fac91f36d47f2230e7b
class ExportedLinuxSyscallTableEntryConverter(RekallResponseConverter): <NEW_LINE> <INDENT> input_rdf_type = "RekallResponse" <NEW_LINE> @staticmethod <NEW_LINE> def HandleTableRow(metadata, message): <NEW_LINE> <INDENT> row = message[1] <NEW_LINE> symbols = row.get("symbol", None) <NEW_LINE> if not isinstance(symbols, list): <NEW_LINE> <INDENT> symbols = [symbols] <NEW_LINE> <DEDENT> for symbol in symbols: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> result = ExportedLinuxSyscallTableEntry( metadata=metadata, table=row["table"], index=row["index"], handler_address=row["address"]["target"], symbol=symbol) <NEW_LINE> yield result <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass
Converts suitable RekallResponses to ExportedLinuxSyscallTableEntrys.
62598faca8370b77170f0387
class CreateTransfer(FormView): <NEW_LINE> <INDENT> form_class = TransferForm <NEW_LINE> template_name = 'transfer_form.html' <NEW_LINE> success_url = '/transfer/success' <NEW_LINE> @atomic <NEW_LINE> def form_valid(self, form): <NEW_LINE> <INDENT> user = form.cleaned_data['user'] <NEW_LINE> inn = form.cleaned_data['inn'] <NEW_LINE> transfer_sum = form.cleaned_data['transfer_sum'] <NEW_LINE> users_cards = UserCard.objects.filter(inn=inn) <NEW_LINE> transfer_summa = transfer_sum / users_cards.count() <NEW_LINE> for bill in BillRub.objects.filter(user_card__in=users_cards): <NEW_LINE> <INDENT> bill.total += transfer_summa <NEW_LINE> bill.save() <NEW_LINE> <DEDENT> user.billrub.total = user.billrub.total - transfer_sum <NEW_LINE> user.billrub.save() <NEW_LINE> return super(CreateTransfer, self).form_valid(form) <NEW_LINE> <DEDENT> def form_invalid(self, form): <NEW_LINE> <INDENT> messages = '\n'.join( [error.message for error in form.errors['__all__'].as_data()]) <NEW_LINE> return HttpResponse( json.dumps({ 'success': 'false', 'message': messages }), content_type='application/json')
Представление создания денежного перевода.
62598fac4a966d76dd5eee8c
class Encoder(nn.Module): <NEW_LINE> <INDENT> def __init__( self, num_types, d_model, d_inner, n_layers, n_head, d_k, d_v, dropout): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.d_model = d_model <NEW_LINE> self.position_vec = torch.tensor( [math.pow(10000.0, 2.0 * (i // 2) / d_model) for i in range(d_model)], device=torch.device('cuda')) <NEW_LINE> self.event_emb = nn.Embedding(num_types + 1, d_model, padding_idx=Constants.PAD) <NEW_LINE> self.layer_stack = nn.ModuleList([ EncoderLayer(d_model, d_inner, n_head, d_k, d_v, dropout=dropout, normalize_before=False) for _ in range(n_layers)]) <NEW_LINE> <DEDENT> def temporal_enc(self, time, non_pad_mask): <NEW_LINE> <INDENT> result = time.unsqueeze(-1) / self.position_vec <NEW_LINE> result[:, :, 0::2] = torch.sin(result[:, :, 0::2]) <NEW_LINE> result[:, :, 1::2] = torch.cos(result[:, :, 1::2]) <NEW_LINE> return result * non_pad_mask <NEW_LINE> <DEDENT> def forward(self, event_type, event_time, non_pad_mask): <NEW_LINE> <INDENT> slf_attn_mask_subseq = get_subsequent_mask(event_type) <NEW_LINE> slf_attn_mask_keypad = get_attn_key_pad_mask(seq_k=event_type, seq_q=event_type) <NEW_LINE> slf_attn_mask_keypad = slf_attn_mask_keypad.type_as(slf_attn_mask_subseq) <NEW_LINE> slf_attn_mask = (slf_attn_mask_keypad + slf_attn_mask_subseq).gt(0) <NEW_LINE> tem_enc = self.temporal_enc(event_time, non_pad_mask) <NEW_LINE> enc_output = self.event_emb(event_type) <NEW_LINE> for enc_layer in self.layer_stack: <NEW_LINE> <INDENT> enc_output += tem_enc <NEW_LINE> enc_output, _ = enc_layer( enc_output, non_pad_mask=non_pad_mask, slf_attn_mask=slf_attn_mask) <NEW_LINE> <DEDENT> return enc_output
A encoder model with self attention mechanism.
62598faccc0a2c111447afbc
class click_button_by_index_args: <NEW_LINE> <INDENT> thrift_spec = ( None, (1, TType.I32, 'index', None, None, ), ) <NEW_LINE> def __init__(self, index=None,): <NEW_LINE> <INDENT> self.index = index <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 1: <NEW_LINE> <INDENT> if ftype == TType.I32: <NEW_LINE> <INDENT> self.index = iprot.readI32(); <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('click_button_by_index_args') <NEW_LINE> if self.index is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('index', TType.I32, 1) <NEW_LINE> oprot.writeI32(self.index) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other)
Attributes: - index
62598fac32920d7e50bc6000
class IAttributeIndex(zope.interface.Interface): <NEW_LINE> <INDENT> interface = zope.schema.Choice( title=_(u"Interface"), description=_(u"Objects will be adapted to this interface"), vocabulary="Interfaces", required=False, ) <NEW_LINE> field_name = zope.schema.NativeStringLine( title=_(u"Field Name"), description=_(u"Name of the field to index"), ) <NEW_LINE> field_callable = zope.schema.Bool( title=_(u"Field Callable"), description=_(u"If true, then the field should be called to get the " u"value to be indexed"), )
I index objects by first adapting them to an interface, then retrieving a field on the adapted object.
62598fac097d151d1a2c0fd4
class BranchDirection: <NEW_LINE> <INDENT> default = _constants.CPX_BRANCH_GLOBAL <NEW_LINE> down = _constants.CPX_BRANCH_DOWN <NEW_LINE> up = _constants.CPX_BRANCH_UP <NEW_LINE> def __getitem__(self, item): <NEW_LINE> <INDENT> if item == _constants.CPX_BRANCH_GLOBAL: <NEW_LINE> <INDENT> return 'default' <NEW_LINE> <DEDENT> if item == _constants.CPX_BRANCH_DOWN: <NEW_LINE> <INDENT> return 'down' <NEW_LINE> <DEDENT> if item == _constants.CPX_BRANCH_UP : <NEW_LINE> <INDENT> return 'up'
Constants defining branch directions
62598facbe8e80087fbbf00f
class WrongConnectionState(ConnectionError): <NEW_LINE> <INDENT> pass
Not connected to the destination when has to be, disconnected when hasn't.
62598fac8e7ae83300ee904e
class TestHandleGetRpm: <NEW_LINE> <INDENT> @mock.patch('fand.communication.send') <NEW_LINE> def test_sanity(self, send, mock_shelf, mock_socket): <NEW_LINE> <INDENT> mock_shelf.rpm = 3000 <NEW_LINE> server._handle_get_rpm(mock_socket, mock_shelf.identifier) <NEW_LINE> send.assert_called_once_with(mock_socket, com.Request.SET_RPM, mock_shelf.identifier, 3000) <NEW_LINE> <DEDENT> @mock.patch('fand.communication.send') <NEW_LINE> def test_wrong_shelf(self, send, mock_socket): <NEW_LINE> <INDENT> with pytest.raises(server.ShelfNotFoundError): <NEW_LINE> <INDENT> server._handle_get_rpm(mock_socket, 'wrong_shelf') <NEW_LINE> <DEDENT> send.assert_not_called()
_handle_get_rpm() tests
62598fac236d856c2adc9413
class Record(list): <NEW_LINE> <INDENT> def __str__(self): <NEW_LINE> <INDENT> return "\n".join(str(motif) for motif in self)
Class to store the information in a position frequency matrix table. The record inherits from a list containing the individual motifs.
62598fac6aa9bd52df0d4e74
class TxInput(object): <NEW_LINE> <INDENT> def __init__(self, prev_txid, out_idx, signature, pubkey): <NEW_LINE> <INDENT> self.prev_txid = prev_txid <NEW_LINE> self.prev_tx_out_idx = out_idx <NEW_LINE> self.signature = signature <NEW_LINE> self.pubkey = pubkey <NEW_LINE> <DEDENT> def can_unlock_txoutput_with(self, address): <NEW_LINE> <INDENT> return Wallet.get_address(self.pubkey) == address <NEW_LINE> <DEDENT> def json_output(self): <NEW_LINE> <INDENT> output = { 'prev_txid': self.prev_txid, 'prev_tx_out_idx': self.prev_tx_out_idx, 'signature': util.get_hash(self.signature) if self.signature is not None else "", 'pubkey_hash': Script.sha160(str(self.pubkey)) if self.pubkey is not None else "" } <NEW_LINE> return output <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return json.dumps(self.json_output(), default=lambda obj: obj.__dict__, sort_keys=True, indent=4)
一个输入引用之前的一个输出
62598fac4e4d5625663723d2
class ReplyKeyboardRemove(PyrogramType): <NEW_LINE> <INDENT> def __init__(self, selective: bool = None): <NEW_LINE> <INDENT> super().__init__(None) <NEW_LINE> self.selective = selective <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def read(o): <NEW_LINE> <INDENT> return ReplyKeyboardRemove( selective=o.selective ) <NEW_LINE> <DEDENT> def write(self): <NEW_LINE> <INDENT> return ReplyKeyboardHide( selective=self.selective or None )
Upon receiving a message with this object, Telegram clients will remove the current custom keyboard and display the default letter-keyboard. By default, custom keyboards are displayed until a new keyboard is sent by a bot. An exception is made for one-time keyboards that are hidden immediately after the user presses a button (see ReplyKeyboardMarkup). Args: selective (``bool``, *optional*): Use this parameter if you want to remove the keyboard for specific users only. Targets: 1) users that are @mentioned in the text of the Message object; 2) if the bot's message is a reply (has reply_to_message_id), sender of the original message. Example: A user votes in a poll, bot returns confirmation message in reply to the vote and removes the keyboard for that user, while still showing the keyboard with poll options to users who haven't voted yet.
62598facf7d966606f747f91
class RateLimitError(ApiResponseError): <NEW_LINE> <INDENT> pass
Raised when the 3rd-party service's rate limit has been hit
62598fac3d592f4c4edbae78
class MainEngine: <NEW_LINE> <INDENT> def __init__(self, broker, config_path='me.json'): <NEW_LINE> <INDENT> self.user = easytrader.use(broker) <NEW_LINE> self.user.read_config(config_path) <NEW_LINE> self.user.autologin() <NEW_LINE> self.event_engine = EventEngine() <NEW_LINE> self.quotation_engine = Quotation(self.event_engine) <NEW_LINE> self.event_engine.register(EVENT_TIMER, self.test) <NEW_LINE> self.strategies = OrderedDict() <NEW_LINE> self.strategy_list = list() <NEW_LINE> print('启动主引擎') <NEW_LINE> <DEDENT> def test(self, event): <NEW_LINE> <INDENT> print('触发计时器') <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> self.event_engine.start() <NEW_LINE> self.quotation_engine.start() <NEW_LINE> <DEDENT> def load_strategy(self): <NEW_LINE> <INDENT> s_folder = 'strategies' <NEW_LINE> strategies = os.listdir(s_folder) <NEW_LINE> strategies = filter(lambda file: file.endswith('.py') and file != '__init__.py', strategies) <NEW_LINE> importlib.import_module(s_folder) <NEW_LINE> for strategy_file in strategies: <NEW_LINE> <INDENT> strategy_module_name = os.path.basename(strategy_file)[:-3] <NEW_LINE> log.info('加载策略: %s' % strategy_module_name) <NEW_LINE> strategy_module = importlib.import_module('.' + strategy_module_name, 'strategies') <NEW_LINE> self.strategy_list.append(getattr(strategy_module, 'Strategy')(self.user)) <NEW_LINE> <DEDENT> for strategy in self.strategy_list: <NEW_LINE> <INDENT> self.event_engine.register(EVENT_QUOTATION, strategy.run) <NEW_LINE> <DEDENT> log.info('加载策略完毕') <NEW_LINE> <DEDENT> def quotation_test(self, event): <NEW_LINE> <INDENT> print('触发行情') <NEW_LINE> print('检查持仓') <NEW_LINE> print(self.user.position) <NEW_LINE> print('触发策略') <NEW_LINE> print('检查 %s 价格 %s' % ('162411', event.data['162411']['now'])) <NEW_LINE> print(event.data['162411'])
主引擎,负责行情 / 事件驱动引擎 / 交易
62598fac9c8ee82313040147
class Gripper: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.activated = False <NEW_LINE> <DEDENT> def step(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def activate(self, objects): <NEW_LINE> <INDENT> del objects <NEW_LINE> return <NEW_LINE> <DEDENT> def release(self): <NEW_LINE> <INDENT> return
Base gripper class.
62598faccc0a2c111447afbd
class ThreadParallelShareDict(ParallelShareDictFw): <NEW_LINE> <INDENT> def _init(self, tag): <NEW_LINE> <INDENT> _gdict = RunTool.get_global_var('ThreadParallelShareDict' + tag) <NEW_LINE> if _gdict is None: <NEW_LINE> <INDENT> _gdict = dict() <NEW_LINE> RunTool.set_global_var('ThreadParallelShareDict' + tag, _gdict) <NEW_LINE> <DEDENT> return _gdict <NEW_LINE> <DEDENT> def _refresh(self, key): <NEW_LINE> <INDENT> self._dict = RunTool.get_global_var('ThreadParallelShareDict' + self._tag) <NEW_LINE> return self._dict[key] <NEW_LINE> <DEDENT> def _update(self, key, value): <NEW_LINE> <INDENT> self._dict = RunTool.get_global_var('ThreadParallelShareDict' + self._tag) <NEW_LINE> self._dict[key] = value <NEW_LINE> RunTool.set_global_var('ThreadParallelShareDict' + self._tag, self._dict)
线程共享字典对象(基于ParallelShareDictFw的实现)
62598fac7b25080760ed745b
class Button(Label): <NEW_LINE> <INDENT> state = OptionProperty('normal', options=('normal', 'down')) <NEW_LINE> background_normal = StringProperty('data/images/button.png') <NEW_LINE> background_down = StringProperty('data/images/button_pressed.png') <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(Button, self).__init__(**kwargs) <NEW_LINE> self.register_event_type('on_press') <NEW_LINE> self.register_event_type('on_release') <NEW_LINE> <DEDENT> def _do_press(self): <NEW_LINE> <INDENT> self.state = 'down' <NEW_LINE> <DEDENT> def _do_release(self): <NEW_LINE> <INDENT> self.state = 'normal' <NEW_LINE> <DEDENT> def on_touch_down(self, touch): <NEW_LINE> <INDENT> if not self.collide_point(touch.x, touch.y): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if self in touch.ud: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> touch.grab(self) <NEW_LINE> touch.ud[self] = True <NEW_LINE> self._do_press() <NEW_LINE> self.dispatch('on_press') <NEW_LINE> return True <NEW_LINE> <DEDENT> def on_touch_move(self, touch): <NEW_LINE> <INDENT> return self in touch.ud <NEW_LINE> <DEDENT> def on_touch_up(self, touch): <NEW_LINE> <INDENT> if touch.grab_current is not self: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> assert(self in touch.ud) <NEW_LINE> touch.ungrab(self) <NEW_LINE> self._do_release() <NEW_LINE> self.dispatch('on_release') <NEW_LINE> return True <NEW_LINE> <DEDENT> def on_press(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def on_release(self): <NEW_LINE> <INDENT> pass
Button class, see module documentation for more information. :Events: `on_press` Fired when the button is pressed. `on_release` Fired when the button is released (i.e., the touch/click that pressed the button goes away).
62598facfff4ab517ebcd791
class Level1Design(SPMCommand): <NEW_LINE> <INDENT> input_spec = Level1DesignInputSpec <NEW_LINE> output_spec = Level1DesignOutputSpec <NEW_LINE> _jobtype = 'stats' <NEW_LINE> _jobname = 'fmri_spec' <NEW_LINE> def _format_arg(self, opt, spec, val): <NEW_LINE> <INDENT> if opt in ['spm_mat_dir', 'mask_image']: <NEW_LINE> <INDENT> return np.array([str(val)], dtype=object) <NEW_LINE> <DEDENT> if opt in ['session_info']: <NEW_LINE> <INDENT> if isinstance(val, dict): <NEW_LINE> <INDENT> return [val] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return val <NEW_LINE> <DEDENT> <DEDENT> return val <NEW_LINE> <DEDENT> def _parse_inputs(self): <NEW_LINE> <INDENT> einputs = super(Level1Design, self)._parse_inputs(skip=('mask_threshold')) <NEW_LINE> if not isdefined(self.inputs.spm_mat_dir): <NEW_LINE> <INDENT> einputs[0]['dir'] = np.array([str(os.getcwd())], dtype=object) <NEW_LINE> <DEDENT> return einputs <NEW_LINE> <DEDENT> def _make_matlab_command(self, content): <NEW_LINE> <INDENT> if isdefined(self.inputs.mask_image): <NEW_LINE> <INDENT> postscript = "load SPM;\n" <NEW_LINE> postscript += "SPM.xM.VM = spm_vol('%s');\n" % list_to_filename(self.inputs.mask_image) <NEW_LINE> postscript += "SPM.xM.I = 0;\n" <NEW_LINE> postscript += "SPM.xM.T = [];\n" <NEW_LINE> postscript += "SPM.xM.TH = ones(size(SPM.xM.TH))*(%s);\n" % self.inputs.mask_threshold <NEW_LINE> postscript += "SPM.xM.xs = struct('Masking', 'explicit masking only');\n" <NEW_LINE> postscript += "save SPM SPM;\n" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> postscript = None <NEW_LINE> <DEDENT> return super(Level1Design, self)._make_matlab_command(content, postscript=postscript) <NEW_LINE> <DEDENT> def _list_outputs(self): <NEW_LINE> <INDENT> outputs = self._outputs().get() <NEW_LINE> spm = os.path.join(os.getcwd(), 'SPM.mat') <NEW_LINE> outputs['spm_mat_file'] = spm <NEW_LINE> return outputs
Generate an SPM design matrix http://www.fil.ion.ucl.ac.uk/spm/doc/manual.pdf#page=61 Examples -------- >>> level1design = Level1Design() >>> level1design.inputs.timing_units = 'secs' >>> level1design.inputs.interscan_interval = 2.5 >>> level1design.inputs.bases = {'hrf':{'derivs': [0,0]}} >>> level1design.inputs.session_info = 'session_info.npz' >>> level1design.run() # doctest: +SKIP
62598fac23849d37ff851061
class ProxyResource(Resource): <NEW_LINE> <INDENT> _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } <NEW_LINE> def __init__(self, **kwargs) -> None: <NEW_LINE> <INDENT> super(ProxyResource, self).__init__(**kwargs)
The resource model definition for a ARM proxy resource. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Fully qualified resource ID for the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str
62598fac7047854f4633f386
class Ascent(Segment): <NEW_LINE> <INDENT> def __defaults__(self): <NEW_LINE> <INDENT> self.tag = 'Ascent Segment' <NEW_LINE> <DEDENT> def initialize(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def unpack(self,x): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def dynamics(self,x_state,x_control,D,I): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def constraints(self,x_state,x_control,D,I): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def solution(self,x): <NEW_LINE> <INDENT> raise NotImplementedError
Ascent Segment: general flight with thrust control vector
62598fac7c178a314d78d449
class IcebergSetPattern(SetPattern): <NEW_LINE> <INDENT> MIN_SUP = 0 <NEW_LINE> @classmethod <NEW_LINE> def fix_desc(cls, desc): <NEW_LINE> <INDENT> if len(desc) < cls.MIN_SUP: <NEW_LINE> <INDENT> return cls.bottom() <NEW_LINE> <DEDENT> return desc <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def intersection(cls, desc1, desc2): <NEW_LINE> <INDENT> assert cls.MIN_SUP >= 0, 'MIN_SUP value should be a positive number' <NEW_LINE> new_desc = cls.fix_desc(desc1.intersection(desc2)) <NEW_LINE> return new_desc
Generalizes SetPattern to allow for a minimal cardinality representation
62598fac8a43f66fc4bf2129
class CustomJSONEncoder(JSONEncoder): <NEW_LINE> <INDENT> def default(self, obj): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if isinstance(obj, date): <NEW_LINE> <INDENT> return obj.isoformat() <NEW_LINE> <DEDENT> iterable = iter(obj) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return list(iterable) <NEW_LINE> <DEDENT> return JSONEncoder.default(self, obj)
Use ISO 8601 for dates
62598fac91f36d47f2230e7c
class ILicenseGroup(interfaces.IMetadataGroup): <NEW_LINE> <INDENT> pass
Placeholder interface for differentiating between regular groups and license-selector metadata groups.
62598fac1b99ca400228f506
class Solution: <NEW_LINE> <INDENT> def reachEndpoint(self, map): <NEW_LINE> <INDENT> n=len(map) <NEW_LINE> if n==0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> m=len(map[0]) <NEW_LINE> if m==0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> visited=[[False for _ in range(m)] for _ in range(n)] <NEW_LINE> self.ans=False <NEW_LINE> self.recur(0 , 0 , n , m , map , visited ) <NEW_LINE> return self.ans <NEW_LINE> <DEDENT> def recur(self , i , j , n , m , map , visited): <NEW_LINE> <INDENT> if self.ans==True: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if map[i][j]==9: <NEW_LINE> <INDENT> self.ans=True <NEW_LINE> return <NEW_LINE> <DEDENT> visited[i][j] = True <NEW_LINE> for x , y in [[1 , 0] , [-1 , 0] , [0 , 1] , [0 , -1]]: <NEW_LINE> <INDENT> nextI=i+x <NEW_LINE> nextJ=j+y <NEW_LINE> if 0<=nextI<n and 0<=nextJ<m and map[nextI][nextJ]!=0 and visited[nextI][nextJ]==False: <NEW_LINE> <INDENT> self.recur(nextI, nextJ, n, m , map , visited) <NEW_LINE> <DEDENT> <DEDENT> visited[i][j]=False
@param map: the map @return: can you reach the endpoint
62598fac8e71fb1e983bba60
@singleton <NEW_LINE> class IdWorker(object): <NEW_LINE> <INDENT> __instance = None <NEW_LINE> def __init__(self, datacenter_id=1, worker_id=2, sequence=0): <NEW_LINE> <INDENT> if worker_id > MAX_WORKER_ID or worker_id < 0: <NEW_LINE> <INDENT> raise ValueError('worker_id值越界') <NEW_LINE> <DEDENT> if datacenter_id > MAX_DATACENTER_ID or datacenter_id < 0: <NEW_LINE> <INDENT> raise ValueError('datacenter_id值越界') <NEW_LINE> <DEDENT> self.worker_id = worker_id <NEW_LINE> self.datacenter_id = datacenter_id <NEW_LINE> self.sequence = sequence <NEW_LINE> self.last_timestamp = -1 <NEW_LINE> <DEDENT> def _gen_timestamp(self): <NEW_LINE> <INDENT> return int(time.time() * 1000) <NEW_LINE> <DEDENT> def get_id(self): <NEW_LINE> <INDENT> timestamp = self._gen_timestamp() <NEW_LINE> if timestamp < self.last_timestamp: <NEW_LINE> <INDENT> logging.error('clock is moving backwards. Rejecting requests until {}'.format(self.last_timestamp)) <NEW_LINE> raise InvalidSystemClock <NEW_LINE> <DEDENT> if timestamp == self.last_timestamp: <NEW_LINE> <INDENT> self.sequence = (self.sequence + 1) & SEQUENCE_MASK <NEW_LINE> if self.sequence == 0: <NEW_LINE> <INDENT> timestamp = self._til_next_millis(self.last_timestamp) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.sequence = 0 <NEW_LINE> <DEDENT> self.last_timestamp = timestamp <NEW_LINE> new_id = ((timestamp - TWEPOCH) << TIMESTAMP_LEFT_SHIFT) | (self.datacenter_id << DATACENTER_ID_SHIFT) | (self.worker_id << WOKER_ID_SHIFT) | self.sequence <NEW_LINE> return new_id <NEW_LINE> <DEDENT> def _til_next_millis(self, last_timestamp): <NEW_LINE> <INDENT> timestamp = self._gen_timestamp() <NEW_LINE> while timestamp <= last_timestamp: <NEW_LINE> <INDENT> timestamp = self._gen_timestamp() <NEW_LINE> <DEDENT> return timestamp
用于生成IDs
62598fac7b180e01f3e49027
class Subscriber(PortalContent, DefaultDublinCoreImpl, PNLContentBase): <NEW_LINE> <INDENT> bounces = None <NEW_LINE> factory_type_information = { 'id': 'Subscriber', 'portal_type': 'Subscriber', 'meta_type': 'Subscriber', 'description': 'A newletter subscriber (has no sense oudside a NewsletterTheme object)', 'content_icon': 'Subscriber.gif', 'product': 'PloneGazette', 'factory': 'addSubscriber', 'immediate_view': 'Subscriber_edit', 'global_allow': 0, 'filter_content_types': 0, 'allowed_content_types': (), 'actions': ( { 'id': 'view', 'name': 'View', 'action': 'string:${object_url}/Subscriber_view', 'permissions': (View,), 'category': 'object' }, { 'id': 'edit', 'name': 'Edit', 'action': 'string:${object_url}/Subscriber_editForm', 'permissions': (ChangeSubscriber,), 'category': 'object', }, ), 'aliases' : { 'edit' : 'Subscriber_editForm', }, } <NEW_LINE> meta_type = factory_type_information['meta_type'] <NEW_LINE> manage_options = PortalContent.manage_options <NEW_LINE> security = ClassSecurityInfo() <NEW_LINE> security.declareObjectProtected(View) <NEW_LINE> security.declarePrivate('__init__') <NEW_LINE> def __init__(self, id, email=''): <NEW_LINE> <INDENT> self._internalVersion = 2 <NEW_LINE> self.id = id <NEW_LINE> self.title = '' <NEW_LINE> self.fullname = '' <NEW_LINE> self.email = email <NEW_LINE> self.format = 'HTML' <NEW_LINE> self.active = False <NEW_LINE> self.creation_date = DateTime() <NEW_LINE> self.bounces = [] <NEW_LINE> return <NEW_LINE> <DEDENT> security.declarePrivate('_post_init') <NEW_LINE> def _post_init(self): <NEW_LINE> <INDENT> self.indexObject() <NEW_LINE> return <NEW_LINE> <DEDENT> def __setstate__(self,state): <NEW_LINE> <INDENT> Subscriber.inheritedAttribute("__setstate__") (self, state) <NEW_LINE> if not hasattr(self, 'fullname'): <NEW_LINE> <INDENT> self.fullname = '' <NEW_LINE> <DEDENT> if not hasattr(self, 'email'): <NEW_LINE> <INDENT> self.email = self.title <NEW_LINE> <DEDENT> <DEDENT> security.declareProtected(ChangeSubscriber, 'edit') <NEW_LINE> def edit(self, format='', active=False, email=''): <NEW_LINE> <INDENT> self.format = format <NEW_LINE> self.active = not not active <NEW_LINE> self.email = email.strip() <NEW_LINE> self.reindexObject() <NEW_LINE> return <NEW_LINE> <DEDENT> security.declarePublic('Title') <NEW_LINE> def Title(self): <NEW_LINE> <INDENT> return self.fullname or self.email <NEW_LINE> <DEDENT> security.declarePublic('SearchableText') <NEW_LINE> def SearchableText(self): <NEW_LINE> <INDENT> return ' '.join([self.fullname, self.email]) <NEW_LINE> <DEDENT> security.declarePublic('activateOnFirstTime') <NEW_LINE> def activateOnFirstTime(self, REQUEST): <NEW_LINE> <INDENT> firsttime = REQUEST.form.get('firsttime') <NEW_LINE> if firsttime: <NEW_LINE> <INDENT> self.active = True <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> def checkMailAddress(self, mail): <NEW_LINE> <INDENT> return checkMailAddress(self,mail) <NEW_LINE> <DEDENT> security.declarePublic('is_bouncing') <NEW_LINE> def is_bouncing(self): <NEW_LINE> <INDENT> return self.bounces and (len(self.bounces) >= MAXIMUM_BOUNCES) <NEW_LINE> <DEDENT> security.declareProtected(ChangeSubscriber, 'mailingInfo') <NEW_LINE> def mailingInfo(self): <NEW_LINE> <INDENT> if self.active: <NEW_LINE> <INDENT> return self.email, self.format, self.absolute_url() + '/Subscriber_editForm' <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> def _getCatalogTool(self): <NEW_LINE> <INDENT> return getattr(self.getTheme(), PG_CATALOG, None) <NEW_LINE> <DEDENT> def reindexObjectSecurity(self, skip_self=False): <NEW_LINE> <INDENT> pass
Subscriber class
62598fac85dfad0860cbfa4a
class ProxmoxHost(): <NEW_LINE> <INDENT> def __init__(self, name, status): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.status = status <NEW_LINE> self.child_vms = [] <NEW_LINE> self.per_cpu_mhz = 0 <NEW_LINE> self.cpu_count = 0 <NEW_LINE> self.max_mhz = 0 <NEW_LINE> self.max_memory = 0 <NEW_LINE> self.allocated_memory = 0 <NEW_LINE> self.used_memory = 0 <NEW_LINE> self.used_cpu_mhz = 0 <NEW_LINE> self.running_vms = 0 <NEW_LINE> <DEDENT> def set_cpu_info(self, cpu_speed, cpu_count): <NEW_LINE> <INDENT> self.per_cpu_mhz = cpu_speed <NEW_LINE> self.cpu_count = cpu_count <NEW_LINE> self.max_mhz = cpu_count*cpu_speed <NEW_LINE> <DEDENT> def set_mem_info(self, max_memory): <NEW_LINE> <INDENT> self.max_memory = max_memory <NEW_LINE> <DEDENT> def get_usage(self): <NEW_LINE> <INDENT> self.used_memory = 0 <NEW_LINE> self.used_cpu_mhz = 0 <NEW_LINE> self.running_vms = 0 <NEW_LINE> for VM in self.get_vms(): <NEW_LINE> <INDENT> self.allocated_memory += VM.max_memory <NEW_LINE> self.used_memory += VM.used_memory <NEW_LINE> self.used_cpu_mhz += VM.cpu_usage*(VM.cpus*self.per_cpu_mhz) <NEW_LINE> if VM.state == "running": <NEW_LINE> <INDENT> self.running_vms += 1 <NEW_LINE> <DEDENT> <DEDENT> free_cpu_mhz = self.max_mhz-self.used_cpu_mhz <NEW_LINE> free_memory = self.max_memory-self.used_memory <NEW_LINE> return {"used_cpu_mhz": self.used_cpu_mhz, "used_memory": self.used_memory, "allocated_memory": self.allocated_memory, "free_cpu_mhz": free_cpu_mhz, "free_memory": free_memory, "running_vms": self.running_vms} <NEW_LINE> <DEDENT> def add_vm(self, virtual_machine): <NEW_LINE> <INDENT> vm_used_memory = virtual_machine.used_memory <NEW_LINE> vm_cpu_mhz = virtual_machine.cpu_usage * (virtual_machine.cpus*self.per_cpu_mhz) <NEW_LINE> vm_cost = {"used_memory": vm_used_memory, "vm_cpu_mhz": vm_cpu_mhz} <NEW_LINE> virtual_machine.set_cost(vm_cost) <NEW_LINE> self.child_vms.append(virtual_machine) <NEW_LINE> self.get_usage() <NEW_LINE> <DEDENT> def get_metric(self, metric): <NEW_LINE> <INDENT> if metric == "used_memory": <NEW_LINE> <INDENT> return self.used_memory <NEW_LINE> <DEDENT> if metric == "used_cpu_mhz": <NEW_LINE> <INDENT> return self.used_cpu_mhz <NEW_LINE> <DEDENT> if metric == "running_vms": <NEW_LINE> <INDENT> return self.running_vms <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def remove_vm(self, virtual_machine): <NEW_LINE> <INDENT> self.child_vms.remove(virtual_machine) <NEW_LINE> self.get_usage() <NEW_LINE> <DEDENT> def get_vms(self): <NEW_LINE> <INDENT> return self.child_vms <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.name) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return str(self.name)
Represents a Proxmox Host, we pass in the name and status and it keeps track of it's memory, cpu, running vms, etc
62598face1aae11d1e7ce7fa
class Sql(object): <NEW_LINE> <INDENT> def __init__(self, connection, _verbose=True): <NEW_LINE> <INDENT> self.connection = connection <NEW_LINE> self._verbose = _verbose
Interfaces with specific database via raw sql for manipulating database schema.
62598fac097d151d1a2c0fd6
class APIError(Exception): <NEW_LINE> <INDENT> def __init__(self, value): <NEW_LINE> <INDENT> self.value = value <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return repr(self.value)
API version compatibility error.
62598fac30dc7b766599f7fb
class SunOSVirtual(Virtual): <NEW_LINE> <INDENT> platform = 'SunOS' <NEW_LINE> def get_virtual_facts(self): <NEW_LINE> <INDENT> zonename = self.module.get_bin_path('zonename') <NEW_LINE> if zonename: <NEW_LINE> <INDENT> rc, out, err = self.module.run_command(zonename) <NEW_LINE> if rc == 0 and out.rstrip() != "global": <NEW_LINE> <INDENT> self.facts['container'] = 'zone' <NEW_LINE> <DEDENT> <DEDENT> if os.path.isdir('/.SUNWnative'): <NEW_LINE> <INDENT> self.facts['container'] = 'zone' <NEW_LINE> <DEDENT> if 'container' in self.facts and self.facts['container'] == 'zone': <NEW_LINE> <INDENT> modinfo = self.module.get_bin_path('modinfo') <NEW_LINE> if modinfo: <NEW_LINE> <INDENT> rc, out, err = self.module.run_command(modinfo) <NEW_LINE> if rc == 0: <NEW_LINE> <INDENT> for line in out.splitlines(): <NEW_LINE> <INDENT> if 'VMware' in line: <NEW_LINE> <INDENT> self.facts['virtualization_type'] = 'vmware' <NEW_LINE> self.facts['virtualization_role'] = 'guest' <NEW_LINE> <DEDENT> if 'VirtualBox' in line: <NEW_LINE> <INDENT> self.facts['virtualization_type'] = 'virtualbox' <NEW_LINE> self.facts['virtualization_role'] = 'guest' <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> if os.path.exists('/proc/vz'): <NEW_LINE> <INDENT> self.facts['virtualization_type'] = 'virtuozzo' <NEW_LINE> self.facts['virtualization_role'] = 'guest' <NEW_LINE> <DEDENT> virtinfo = self.module.get_bin_path('virtinfo') <NEW_LINE> if virtinfo: <NEW_LINE> <INDENT> rc, out, err = self.module.run_command("/usr/sbin/virtinfo -p") <NEW_LINE> if rc == 0: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> for line in out.splitlines(): <NEW_LINE> <INDENT> fields = line.split('|') <NEW_LINE> if( fields[0] == 'DOMAINROLE' and fields[1] == 'impl=LDoms' ): <NEW_LINE> <INDENT> self.facts['virtualization_type'] = 'ldom' <NEW_LINE> self.facts['virtualization_role'] = 'guest' <NEW_LINE> hostfeatures = [] <NEW_LINE> for field in fields[2:]: <NEW_LINE> <INDENT> arg = field.split('=') <NEW_LINE> if( arg[1] == 'true' ): <NEW_LINE> <INDENT> hostfeatures.append(arg[0]) <NEW_LINE> <DEDENT> <DEDENT> if( len(hostfeatures) > 0 ): <NEW_LINE> <INDENT> self.facts['virtualization_role'] = 'host (' + ','.join(hostfeatures) + ')' <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> except ValueError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> smbios = self.module.get_bin_path('smbios') <NEW_LINE> rc, out, err = self.module.run_command(smbios) <NEW_LINE> if rc == 0: <NEW_LINE> <INDENT> for line in out.splitlines(): <NEW_LINE> <INDENT> if 'VMware' in line: <NEW_LINE> <INDENT> self.facts['virtualization_type'] = 'vmware' <NEW_LINE> self.facts['virtualization_role'] = 'guest' <NEW_LINE> <DEDENT> elif 'Parallels' in line: <NEW_LINE> <INDENT> self.facts['virtualization_type'] = 'parallels' <NEW_LINE> self.facts['virtualization_role'] = 'guest' <NEW_LINE> <DEDENT> elif 'VirtualBox' in line: <NEW_LINE> <INDENT> self.facts['virtualization_type'] = 'virtualbox' <NEW_LINE> self.facts['virtualization_role'] = 'guest' <NEW_LINE> <DEDENT> elif 'HVM domU' in line: <NEW_LINE> <INDENT> self.facts['virtualization_type'] = 'xen' <NEW_LINE> self.facts['virtualization_role'] = 'guest' <NEW_LINE> <DEDENT> elif 'KVM' in line: <NEW_LINE> <INDENT> self.facts['virtualization_type'] = 'kvm' <NEW_LINE> self.facts['virtualization_role'] = 'guest'
This is a SunOS-specific subclass of Virtual. It defines - virtualization_type - virtualization_role - container
62598faca79ad1619776a013
class IPlugin(object): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def get_info(cls): <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> def __init__(self): <NEW_LINE> <INDENT> self.active = False <NEW_LINE> self.jumble = None <NEW_LINE> self.path = None <NEW_LINE> self.folder = None <NEW_LINE> <DEDENT> def activate(self): <NEW_LINE> <INDENT> if self.active: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.active = True <NEW_LINE> <DEDENT> def deactivate(self): <NEW_LINE> <INDENT> self.active = False <NEW_LINE> <DEDENT> def is_active(self): <NEW_LINE> <INDENT> return self.active
The most simple interface to be inherited when creating a plugin.
62598facd268445f26639b5a
class TestPauseMonitor(CustomClusterTestSuite): <NEW_LINE> <INDENT> @CustomClusterTestSuite.with_args("--logbuflevel=-1") <NEW_LINE> def test_jvm_pause_monitor_logs_entries(self): <NEW_LINE> <INDENT> impalad = self.cluster.get_first_impalad() <NEW_LINE> impalad.kill(signal.SIGSTOP) <NEW_LINE> time.sleep(5) <NEW_LINE> impalad.kill(signal.SIGCONT) <NEW_LINE> time.sleep(2) <NEW_LINE> self.assert_impalad_log_contains('INFO', "Detected pause in JVM or host machine") <NEW_LINE> assert impalad.service.get_metric_value("jvm.gc_num_info_threshold_exceeded") > 0 <NEW_LINE> assert impalad.service.get_metric_value("jvm.gc_total_extra_sleep_time_millis") > 0
Class for pause monitor tests.
62598fac5166f23b2e243387
class ConfigurationError(PrivateError): <NEW_LINE> <INDENT> pass
Private Error Used to indicated errors due to the current configuration of the application.
62598facb7558d58954635d7
class ContractConstructor: <NEW_LINE> <INDENT> def __init__(self, web3, abi, bytecode,vmtype, *args, **kwargs): <NEW_LINE> <INDENT> self.web3 = web3 <NEW_LINE> self.abi = abi <NEW_LINE> self.bytecode = bytecode <NEW_LINE> self.vmtype = vmtype <NEW_LINE> self.data_in_transaction = self._encode_data_in_transaction(*args, **kwargs) <NEW_LINE> <DEDENT> @combomethod <NEW_LINE> def _encode_data_in_transaction(self, *args, **kwargs): <NEW_LINE> <INDENT> constructor_abi = get_constructor_abi(self.abi) <NEW_LINE> if constructor_abi: <NEW_LINE> <INDENT> if not args: <NEW_LINE> <INDENT> args = tuple() <NEW_LINE> <DEDENT> if not kwargs: <NEW_LINE> <INDENT> kwargs = {} <NEW_LINE> <DEDENT> arguments = merge_args_and_kwargs(constructor_abi, args, kwargs) <NEW_LINE> data = add_0x_prefix( encode_abi(self.web3, constructor_abi, arguments, self.vmtype, self.bytecode, self.abi) ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> data = to_hex(self.bytecode) <NEW_LINE> <DEDENT> return data <NEW_LINE> <DEDENT> @combomethod <NEW_LINE> def estimateGas(self, transaction=None): <NEW_LINE> <INDENT> if transaction is None: <NEW_LINE> <INDENT> estimate_gas_transaction = {} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> estimate_gas_transaction = dict(**transaction) <NEW_LINE> self.check_forbidden_keys_in_transaction(estimate_gas_transaction, ["data", "to"]) <NEW_LINE> <DEDENT> if self.web3.eth.defaultAccount is not empty: <NEW_LINE> <INDENT> estimate_gas_transaction.setdefault('from', self.web3.eth.defaultAccount) <NEW_LINE> <DEDENT> estimate_gas_transaction['data'] = self.data_in_transaction <NEW_LINE> return self.web3.eth.estimateGas(estimate_gas_transaction) <NEW_LINE> <DEDENT> @combomethod <NEW_LINE> def transact(self, transaction=None): <NEW_LINE> <INDENT> if transaction is None: <NEW_LINE> <INDENT> transact_transaction = {} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> transact_transaction = dict(**transaction) <NEW_LINE> self.check_forbidden_keys_in_transaction(transact_transaction, ["data", "to"]) <NEW_LINE> <DEDENT> if self.web3.eth.defaultAccount is not empty: <NEW_LINE> <INDENT> transact_transaction.setdefault('from', self.web3.eth.defaultAccount) <NEW_LINE> <DEDENT> transact_transaction['data'] = self.data_in_transaction <NEW_LINE> return self.web3.eth.sendTransaction(transact_transaction) <NEW_LINE> <DEDENT> @combomethod <NEW_LINE> def buildTransaction(self, transaction=None): <NEW_LINE> <INDENT> if transaction is None: <NEW_LINE> <INDENT> built_transaction = {} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> built_transaction = dict(**transaction) <NEW_LINE> self.check_forbidden_keys_in_transaction(built_transaction, ["data", "to"]) <NEW_LINE> <DEDENT> if self.web3.eth.defaultAccount is not empty: <NEW_LINE> <INDENT> built_transaction.setdefault('from', self.web3.eth.defaultAccount) <NEW_LINE> <DEDENT> built_transaction['data'] = self.data_in_transaction <NEW_LINE> built_transaction['to'] = b'' <NEW_LINE> return fill_transaction_defaults(self.web3, built_transaction) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def check_forbidden_keys_in_transaction(transaction, forbidden_keys=None): <NEW_LINE> <INDENT> keys_found = set(transaction.keys()) & set(forbidden_keys) <NEW_LINE> if keys_found: <NEW_LINE> <INDENT> raise ValueError("Cannot set {} in transaction".format(', '.join(keys_found)))
Class for contract constructor API.
62598fac45492302aabfc47f
class DistanceMixin: <NEW_LINE> <INDENT> lng_name = 'lng' <NEW_LINE> lat_name = 'lat' <NEW_LINE> manager_name = 'objects' <NEW_LINE> def distance(self, meters): <NEW_LINE> <INDENT> lng = getattr(self, self.lng_name, None) <NEW_LINE> lat = getattr(self, self.lat_name, None) <NEW_LINE> manager = getattr(self.__class__, self.manager_name) <NEW_LINE> if not (lng and lat): <NEW_LINE> <INDENT> return manager.none() <NEW_LINE> <DEDENT> miles = float(meters)/1609.344 <NEW_LINE> dist_lng = miles/abs(math.cos(math.radians(lat))*69) <NEW_LINE> lng1 = lng-dist_lng <NEW_LINE> lng2 = lng+dist_lng <NEW_LINE> lat1 = lat-(miles/69) <NEW_LINE> lat2 = lat+(miles/69) <NEW_LINE> kwargs = {'%s__gte' % self.lng_name: lng1, '%s__lte' % self.lng_name: lng2, '%s__gte' % self.lat_name: lat1, '%s__lte' % self.lat_name: lat2 } <NEW_LINE> return manager.filter(**kwargs).exclude(pk=self.pk)
Search for nearby objects Example: class Supermarket(DistanceMixin, models.Model): lng = models.FloatField() lat = models.FloatField() name = models.CharField(max_length=100) # All McDonald's 200 meters from the supermarket supermarket = Supermarket.objects.get(name=u"Монетка").distance(200).filter(name="McDonald's")
62598fac6aa9bd52df0d4e76
class ExternalSubtitle(Subtitle): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def from_path(cls, path): <NEW_LINE> <INDENT> extension = '' <NEW_LINE> for e in EXTENSIONS: <NEW_LINE> <INDENT> if path.endswith(e): <NEW_LINE> <INDENT> extension = e <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if not extension: <NEW_LINE> <INDENT> raise ValueError('Not a supported subtitle extension') <NEW_LINE> <DEDENT> language = os.path.splitext(path[:len(path) - len(extension)])[1][1:] <NEW_LINE> if not language in list_languages(1): <NEW_LINE> <INDENT> language = None <NEW_LINE> <DEDENT> return cls(path, language)
Subtitle in a file next to the video file
62598fac67a9b606de545f7b
class ConfigEntry: <NEW_LINE> <INDENT> def __init__(self, key1: str, key2: str, default: str = ""): <NEW_LINE> <INDENT> self.key1 = key1 <NEW_LINE> self.key2 = key2 <NEW_LINE> self.default = default <NEW_LINE> self.env_var_name = f"SPEASY_{self.key1}_{self.key2}".upper().replace('-', '_') <NEW_LINE> <DEDENT> def get(self): <NEW_LINE> <INDENT> if self.env_var_name in os.environ: <NEW_LINE> <INDENT> return os.environ[self.env_var_name] <NEW_LINE> <DEDENT> if self.key1 in _config and self.key2 in _config[self.key1]: <NEW_LINE> <INDENT> return _config[self.key1][self.key2] <NEW_LINE> <DEDENT> return self.default <NEW_LINE> <DEDENT> def set(self, value: str): <NEW_LINE> <INDENT> if self.env_var_name in os.environ: <NEW_LINE> <INDENT> os.environ[self.env_var_name] = value <NEW_LINE> <DEDENT> if self.key1 not in _config: <NEW_LINE> <INDENT> _config.add_section(self.key1) <NEW_LINE> <DEDENT> _config[self.key1][self.key2] = value <NEW_LINE> _save_changes()
Configuration entry class. Used to set and get configuration values. Attributes ---------- key1: str Module or category name key2: str Entry name default: str Default value given by ctor env_var_name: str Environment variable name to use to set this entry Methods ------- get: Get entry current value set: Set entry value (could be env or file)
62598fac01c39578d7f12d2d
class MissingAFDOData(failures_lib.StepFailure): <NEW_LINE> <INDENT> pass
Exception thrown when necessary AFDO data is missing.
62598facd486a94d0ba2bf7c
class Player(models.Model): <NEW_LINE> <INDENT> player_id = models.AutoField(primary_key=True) <NEW_LINE> user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='players', ) <NEW_LINE> room = models.ForeignKey( Room, on_delete=models.CASCADE, related_name='players', ) <NEW_LINE> score = models.IntegerField(default=0) <NEW_LINE> correct = models.IntegerField(default=0) <NEW_LINE> negs = models.IntegerField(default=0) <NEW_LINE> locked_out = models.BooleanField(default=False) <NEW_LINE> banned = models.BooleanField(default=False) <NEW_LINE> reported_by = models.ManyToManyField('Player') <NEW_LINE> last_seen = models.FloatField(default=0) <NEW_LINE> def unban(self): <NEW_LINE> <INDENT> self.banned = False <NEW_LINE> self.reported_by.clear() <NEW_LINE> self.save() <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.user.name + ":" + self.room.label
Player in a room
62598fac627d3e7fe0e06e5c
class Cron(object): <NEW_LINE> <INDENT> __shared_state = dict( app_jobs = SortedDict(), thread = None, ) <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.__dict__ = self.__shared_state <NEW_LINE> <DEDENT> def get_job(self, app_label, job_name): <NEW_LINE> <INDENT> return self.app_jobs.get(app_label, SortedDict()).get(job_name.lower()) <NEW_LINE> <DEDENT> def register_job(self, app_label, *jobs): <NEW_LINE> <INDENT> for job in jobs: <NEW_LINE> <INDENT> job_name = job.__name__.lower() <NEW_LINE> job_dict = self.app_jobs.setdefault(app_label, SortedDict()) <NEW_LINE> if job_name in job_dict: <NEW_LINE> <INDENT> fname1 = os.path.abspath(sys.modules[job.__module__].__file__) <NEW_LINE> fname2 = os.path.abspath(sys.modules[job_dict[job_name].__module__].__file__) <NEW_LINE> if os.path.splitext(fname1)[0] == os.path.splitext(fname2)[0]: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> <DEDENT> job_dict[job_name] = job <NEW_LINE> <DEDENT> <DEDENT> def start(self): <NEW_LINE> <INDENT> if self.thread: self.thread.stop() <NEW_LINE> self.thread = CronThread(self) <NEW_LINE> self.thread.start() <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> self.thread.stopevent.set()
Stores jobs to be run at indicated times.
62598fac379a373c97d98fc2
class HashFile(ClientActionStub): <NEW_LINE> <INDENT> in_rdfvalue = rdf_client.FingerprintRequest <NEW_LINE> out_rdfvalues = [rdf_client.FingerprintResponse]
Hash an entire file using multiple algorithms.
62598facbaa26c4b54d4f261
class ActionTypeFailureMessage(TestCase, ActionTypeTestsMixin): <NEW_LINE> <INDENT> def getValidMessage(self): <NEW_LINE> <INDENT> return { "action_type": "myapp:mysystem:myaction", "action_status": "failed", "exception": "exceptions.RuntimeError", "reason": "because", } <NEW_LINE> <DEDENT> def getSerializer(self, actionType): <NEW_LINE> <INDENT> return actionType._serializers.failure <NEW_LINE> <DEDENT> def test_validateExtraField(self): <NEW_LINE> <INDENT> actionType = self.actionType() <NEW_LINE> message = self.getValidMessage() <NEW_LINE> message.update({"task_level": "/", "task_uuid": "123", "timestamp": "xxx"}) <NEW_LINE> message.update({"extra_field": "hello"}) <NEW_LINE> self.getSerializer(actionType).validate(message)
Tests for L{ActionType} validation of action failure messages.
62598fac7047854f4633f389
class ChallengesNotFoundError(IOError): <NEW_LINE> <INDENT> pass
Exception raised when Challenges are not loaded
62598fac2ae34c7f260ab091
class ProtectedItemOperationResultsOperations: <NEW_LINE> <INDENT> models = _models <NEW_LINE> def __init__(self, client, config, serializer, deserializer) -> None: <NEW_LINE> <INDENT> self._client = client <NEW_LINE> self._serialize = serializer <NEW_LINE> self._deserialize = deserializer <NEW_LINE> self._config = config <NEW_LINE> <DEDENT> @distributed_trace_async <NEW_LINE> async def get( self, vault_name: str, resource_group_name: str, fabric_name: str, container_name: str, protected_item_name: str, operation_id: str, **kwargs: Any ) -> Optional["_models.ProtectedItemResource"]: <NEW_LINE> <INDENT> cls = kwargs.pop('cls', None) <NEW_LINE> error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } <NEW_LINE> error_map.update(kwargs.pop('error_map', {})) <NEW_LINE> request = build_get_request( vault_name=vault_name, resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, fabric_name=fabric_name, container_name=container_name, protected_item_name=protected_item_name, operation_id=operation_id, template_url=self.get.metadata['url'], ) <NEW_LINE> request = _convert_request(request) <NEW_LINE> request.url = self._client.format_url(request.url) <NEW_LINE> pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) <NEW_LINE> response = pipeline_response.http_response <NEW_LINE> if response.status_code not in [200, 202, 204]: <NEW_LINE> <INDENT> map_error(status_code=response.status_code, response=response, error_map=error_map) <NEW_LINE> raise HttpResponseError(response=response, error_format=ARMErrorFormat) <NEW_LINE> <DEDENT> deserialized = None <NEW_LINE> if response.status_code == 200: <NEW_LINE> <INDENT> deserialized = self._deserialize('ProtectedItemResource', pipeline_response) <NEW_LINE> <DEDENT> if cls: <NEW_LINE> <INDENT> return cls(pipeline_response, deserialized, {}) <NEW_LINE> <DEDENT> return deserialized <NEW_LINE> <DEDENT> get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupFabrics/{fabricName}/protectionContainers/{containerName}/protectedItems/{protectedItemName}/operationResults/{operationId}'}
ProtectedItemOperationResultsOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.recoveryservicesbackup.activestamp.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer.
62598fac435de62698e9bda5
class WorkunitClientToFinish(Exception): <NEW_LINE> <INDENT> def __init__(self, explanation): <NEW_LINE> <INDENT> self.text = explanation <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.text
we received a 410 (probably while attempting to download a WU)
62598fac66673b3332c3037b
class PendingConfiguration(vas.shared.PendingConfigurations.PendingConfiguration): <NEW_LINE> <INDENT> def __init__(self, client, location): <NEW_LINE> <INDENT> super(PendingConfiguration, self).__init__(client, location, 'group-instance', Instance)
A configuration file that is pending :ivar str content: The configuration's content :ivar `vas.web_server.Instances.Instance` instance: The instance that owns the configuration :ivar str path: The configuration's path :ivar `vas.shared.Security.Security` security: The resource's security :ivar int size: The configuration's size
62598fac851cf427c66b826c
class ClientFakeSuccess: <NEW_LINE> <INDENT> def __init__(self, host="127.0.0.1", port=5037): <NEW_LINE> <INDENT> self._devices = [] <NEW_LINE> <DEDENT> def devices(self): <NEW_LINE> <INDENT> return self._devices <NEW_LINE> <DEDENT> def device(self, serial): <NEW_LINE> <INDENT> device = DeviceFake(serial) <NEW_LINE> self._devices.append(device) <NEW_LINE> return device
A fake of the `adb_messenger.client.Client` class when the connection and shell commands succeed.
62598faca79ad1619776a015
class InvalidError(ValueError): <NEW_LINE> <INDENT> pass
Raised when validator fails
62598fac4e4d5625663723d5
class DirEntry(object): <NEW_LINE> <INDENT> def __init__(self, filesystem): <NEW_LINE> <INDENT> self._filesystem = filesystem <NEW_LINE> self.name = '' <NEW_LINE> self.path = '' <NEW_LINE> self._inode = None <NEW_LINE> self._islink = False <NEW_LINE> self._isdir = False <NEW_LINE> self._statresult = None <NEW_LINE> self._statresult_symlink = None <NEW_LINE> <DEDENT> def inode(self): <NEW_LINE> <INDENT> if self._inode is None: <NEW_LINE> <INDENT> self.stat(follow_symlinks=False) <NEW_LINE> <DEDENT> return self._inode <NEW_LINE> <DEDENT> def is_dir(self, follow_symlinks=True): <NEW_LINE> <INDENT> return self._isdir and (follow_symlinks or not self._islink) <NEW_LINE> <DEDENT> def is_file(self, follow_symlinks=True): <NEW_LINE> <INDENT> return not self._isdir and (follow_symlinks or not self._islink) <NEW_LINE> <DEDENT> def is_symlink(self): <NEW_LINE> <INDENT> return self._islink <NEW_LINE> <DEDENT> def stat(self, follow_symlinks=True): <NEW_LINE> <INDENT> if follow_symlinks: <NEW_LINE> <INDENT> if self._statresult_symlink is None: <NEW_LINE> <INDENT> file_object = self._filesystem.ResolveObject(self.path) <NEW_LINE> if self._filesystem.is_windows_fs: <NEW_LINE> <INDENT> file_object.st_nlink = 0 <NEW_LINE> <DEDENT> self._statresult_symlink = file_object.stat_result.copy() <NEW_LINE> <DEDENT> return self._statresult_symlink <NEW_LINE> <DEDENT> if self._statresult is None: <NEW_LINE> <INDENT> file_object = self._filesystem.LResolveObject(self.path) <NEW_LINE> self._inode = file_object.st_ino <NEW_LINE> if self._filesystem.is_windows_fs: <NEW_LINE> <INDENT> file_object.st_nlink = 0 <NEW_LINE> <DEDENT> self._statresult = file_object.stat_result.copy() <NEW_LINE> <DEDENT> return self._statresult
Emulates os.DirEntry. Note that we did not enforce keyword only arguments.
62598fac5166f23b2e243389
class HeatRecoveryBoiler(FossilSteamSupply): <NEW_LINE> <INDENT> def __init__(self, steamSupplyRating2=0.0, CombustionTurbines=None, *args, **kw_args): <NEW_LINE> <INDENT> self.steamSupplyRating2 = steamSupplyRating2 <NEW_LINE> self._CombustionTurbines = [] <NEW_LINE> self.CombustionTurbines = [] if CombustionTurbines is None else CombustionTurbines <NEW_LINE> super(HeatRecoveryBoiler, self).__init__(*args, **kw_args) <NEW_LINE> <DEDENT> _attrs = ["steamSupplyRating2"] <NEW_LINE> _attr_types = {"steamSupplyRating2": float} <NEW_LINE> _defaults = {"steamSupplyRating2": 0.0} <NEW_LINE> _enums = {} <NEW_LINE> _refs = ["CombustionTurbines"] <NEW_LINE> _many_refs = ["CombustionTurbines"] <NEW_LINE> def getCombustionTurbines(self): <NEW_LINE> <INDENT> return self._CombustionTurbines <NEW_LINE> <DEDENT> def setCombustionTurbines(self, value): <NEW_LINE> <INDENT> for x in self._CombustionTurbines: <NEW_LINE> <INDENT> x.HeatRecoveryBoiler = None <NEW_LINE> <DEDENT> for y in value: <NEW_LINE> <INDENT> y._HeatRecoveryBoiler = self <NEW_LINE> <DEDENT> self._CombustionTurbines = value <NEW_LINE> <DEDENT> CombustionTurbines = property(getCombustionTurbines, setCombustionTurbines) <NEW_LINE> def addCombustionTurbines(self, *CombustionTurbines): <NEW_LINE> <INDENT> for obj in CombustionTurbines: <NEW_LINE> <INDENT> obj.HeatRecoveryBoiler = self <NEW_LINE> <DEDENT> <DEDENT> def removeCombustionTurbines(self, *CombustionTurbines): <NEW_LINE> <INDENT> for obj in CombustionTurbines: <NEW_LINE> <INDENT> obj.HeatRecoveryBoiler = None
The heat recovery system associated with combustion turbines in order to produce steam for combined cycle plantsThe heat recovery system associated with combustion turbines in order to produce steam for combined cycle plants
62598fac7d43ff24874273da
class snakesLadders(): <NEW_LINE> <INDENT> def __init__(self, sense): <NEW_LINE> <INDENT> self.board = [] <NEW_LINE> self.snakes = [] <NEW_LINE> self.ladders = [] <NEW_LINE> self.sense = sense <NEW_LINE> self.sense.clear() <NEW_LINE> <DEDENT> def addSnake(self,headX,headY,tailX,tailY): <NEW_LINE> <INDENT> self.snakes.append(snake(headX,headY,tailX,tailY)) <NEW_LINE> self.setBoard() <NEW_LINE> <DEDENT> def addLadder(self,headX,headY,tailX,tailY): <NEW_LINE> <INDENT> self.ladders.append(ladder(headX,headY,tailX,tailY)) <NEW_LINE> self.setBoard() <NEW_LINE> <DEDENT> def getSnakes(self): <NEW_LINE> <INDENT> return deepcopy(self.snakes) <NEW_LINE> <DEDENT> def getLadders(self): <NEW_LINE> <INDENT> return deepcopy(self.ladders) <NEW_LINE> <DEDENT> def setBoard(self): <NEW_LINE> <INDENT> newBoard = [] <NEW_LINE> for j in range(8): <NEW_LINE> <INDENT> for i in range(8): <NEW_LINE> <INDENT> snakeFound = False <NEW_LINE> ladderFound = False <NEW_LINE> for snake in self.snakes: <NEW_LINE> <INDENT> snakeHead = snake.getHead() <NEW_LINE> snakeTail = snake.getTail() <NEW_LINE> if i == snakeHead[0] and j == snakeHead[1]: <NEW_LINE> <INDENT> print('snakeHead') <NEW_LINE> newBoard.append(snake.colour) <NEW_LINE> snakeFound = True <NEW_LINE> break <NEW_LINE> <DEDENT> elif i == snakeTail[0] and j == snakeTail[1]: <NEW_LINE> <INDENT> newBoard.append(snake.colour) <NEW_LINE> snakeFound = True <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if not snakeFound: <NEW_LINE> <INDENT> for ladder in self.ladders: <NEW_LINE> <INDENT> ladderHead = ladder.getTop() <NEW_LINE> ladderTail = ladder.getFoot() <NEW_LINE> if i == ladderHead[0] and j == ladderHead[1]: <NEW_LINE> <INDENT> newBoard.append(ladder.colour) <NEW_LINE> ladderFound = True <NEW_LINE> break <NEW_LINE> <DEDENT> elif i == ladderTail[0] and j == ladderTail[1]: <NEW_LINE> <INDENT> newBoard.append(ladder.colour) <NEW_LINE> ladderFound = True <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if not ladderFound and not snakeFound: <NEW_LINE> <INDENT> newBoard.append(boardColour) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self.board = newBoard <NEW_LINE> self.sense.set_pixels(self.board)
Creates the board and holds variables that control the game.
62598facbe383301e02537a9
class LevelsActionsLinks(flourish.page.RefineLinksViewlet): <NEW_LINE> <INDENT> pass
Manager for Actions links.
62598fac3539df3088ecc262
class VUID(models.Model): <NEW_LINE> <INDENT> project = models.ForeignKey('Project') <NEW_LINE> filename = models.TextField() <NEW_LINE> upload_date = models.DateTimeField(auto_now_add=True) <NEW_LINE> file = models.FileField(upload_to=vuid_location) <NEW_LINE> upload_by = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return '{0}: {1}'.format(self.filename, self.project.name)
Represents the uploaded file used to generate VoiceSlot object
62598fac4e4d5625663723d6
class QTextDocumentFragment(): <NEW_LINE> <INDENT> def fromHtml(self, QString, QTextDocument=None): <NEW_LINE> <INDENT> return QTextDocumentFragment <NEW_LINE> <DEDENT> def fromPlainText(self, QString): <NEW_LINE> <INDENT> return QTextDocumentFragment <NEW_LINE> <DEDENT> def isEmpty(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def toHtml(self, QByteArray=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def toPlainText(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __init__(self, *__args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> __weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None)
QTextDocumentFragment() QTextDocumentFragment(QTextDocument) QTextDocumentFragment(QTextCursor) QTextDocumentFragment(QTextDocumentFragment)
62598fac4f88993c371f04e2
class Controller(common.QuantumController): <NEW_LINE> <INDENT> _attachment_ops_param_list = [{ 'param-name': 'id', 'required': True}, ] <NEW_LINE> _serialization_metadata = { "application/xml": { "attributes": { "attachment": ["id"], } }, } <NEW_LINE> def __init__(self, plugin): <NEW_LINE> <INDENT> self._resource_name = 'attachment' <NEW_LINE> super(Controller, self).__init__(plugin) <NEW_LINE> <DEDENT> def get_resource(self, request, tenant_id, network_id, id): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> att_data = self._plugin.get_port_details( tenant_id, network_id, id) <NEW_LINE> builder = attachments_view.get_view_builder(request) <NEW_LINE> result = builder.build(att_data)['attachment'] <NEW_LINE> return dict(attachment=result) <NEW_LINE> <DEDENT> except exception.NetworkNotFound as e: <NEW_LINE> <INDENT> return faults.Fault(faults.NetworkNotFound(e)) <NEW_LINE> <DEDENT> except exception.PortNotFound as e: <NEW_LINE> <INDENT> return faults.Fault(faults.PortNotFound(e)) <NEW_LINE> <DEDENT> <DEDENT> def attach_resource(self, request, tenant_id, network_id, id): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> request_params = self._parse_request_params(request, self._attachment_ops_param_list) <NEW_LINE> <DEDENT> except exc.HTTPError as e: <NEW_LINE> <INDENT> return faults.Fault(e) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> LOG.debug("PLUGGING INTERFACE:%s", request_params['id']) <NEW_LINE> self._plugin.plug_interface(tenant_id, network_id, id, request_params['id']) <NEW_LINE> return exc.HTTPNoContent() <NEW_LINE> <DEDENT> except exception.NetworkNotFound as e: <NEW_LINE> <INDENT> return faults.Fault(faults.NetworkNotFound(e)) <NEW_LINE> <DEDENT> except exception.PortNotFound as e: <NEW_LINE> <INDENT> return faults.Fault(faults.PortNotFound(e)) <NEW_LINE> <DEDENT> except exception.PortInUse as e: <NEW_LINE> <INDENT> return faults.Fault(faults.PortInUse(e)) <NEW_LINE> <DEDENT> except exception.AlreadyAttached as e: <NEW_LINE> <INDENT> return faults.Fault(faults.AlreadyAttached(e)) <NEW_LINE> <DEDENT> <DEDENT> def detach_resource(self, request, tenant_id, network_id, id): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._plugin.unplug_interface(tenant_id, network_id, id) <NEW_LINE> return exc.HTTPNoContent() <NEW_LINE> <DEDENT> except exception.NetworkNotFound as e: <NEW_LINE> <INDENT> return faults.Fault(faults.NetworkNotFound(e)) <NEW_LINE> <DEDENT> except exception.PortNotFound as e: <NEW_LINE> <INDENT> return faults.Fault(faults.PortNotFound(e))
Port API controller for Quantum API
62598facf7d966606f747f95
class MessageEventSubscriber(object): <NEW_LINE> <INDENT> def __init__(self, streaming_client): <NEW_LINE> <INDENT> self.__streaming_client = streaming_client <NEW_LINE> self.__listener = None <NEW_LINE> self.__realtime_client = None <NEW_LINE> <DEDENT> def subscribe(self, listener, auth, topic): <NEW_LINE> <INDENT> self.close() <NEW_LINE> self.__listener = listener <NEW_LINE> self.__realtime_client = RealtimeClient(self.__streaming_client, self.__local_listener, auth) <NEW_LINE> self.__realtime_client.connect(topic) <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> if not self.__realtime_client: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.__realtime_client.close() <NEW_LINE> self.__realtime_client = None <NEW_LINE> <DEDENT> def __local_listener(self, datum): <NEW_LINE> <INDENT> if not self.__listener: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> jdict = json.loads(datum) <NEW_LINE> event = MessageEvent.construct_from_jdict(jdict) <NEW_LINE> self.__listener(event) <NEW_LINE> <DEDENT> def __str__(self, *args, **kwargs): <NEW_LINE> <INDENT> return "MessageEventSubscriber:{streaming_client:%s}" % self.__streaming_client
classdocs
62598fac3d592f4c4edbae7c
class ConfigValidator: <NEW_LINE> <INDENT> def __init__(self, config_file): <NEW_LINE> <INDENT> self.config_file = config_file <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> cron = { 'check': str, 'cleanup': str, 'image-update': str, } <NEW_LINE> images = { 'name': str, 'base-image': str, 'min-ram': int, 'name-filter': str, 'diskimage': str, 'meta': dict, 'setup': str, 'username': str, 'private-key': str, 'config-drive': bool, } <NEW_LINE> old_network = { 'net-id': str, 'net-label': str, } <NEW_LINE> network = { 'name': v.Required(str), 'public': bool, } <NEW_LINE> providers = { 'name': str, 'region-name': str, 'service-type': str, 'service-name': str, 'availability-zones': [str], 'keypair': str, 'cloud': str, 'username': str, 'password': str, 'auth-url': str, 'project-id': str, 'project-name': str, 'max-servers': int, 'pool': str, 'image-type': str, 'networks': [v.Any(old_network, network)], 'ipv6-preferred': bool, 'boot-timeout': int, 'api-timeout': int, 'launch-timeout': int, 'rate': float, 'images': [images], 'template-hostname': str, 'clean-floating-ips': bool, } <NEW_LINE> labels = { 'name': str, 'image': str, 'min-ready': int, 'ready-script': str, 'subnodes': int, 'providers': [{ 'name': str, }], } <NEW_LINE> targets = { 'name': str, 'hostname': str, 'subnode-hostname': str, 'assign-via-gearman': bool, 'jenkins': { 'url': str, 'user': str, 'apikey': str, 'credentials-id': str, 'test-job': str } } <NEW_LINE> diskimages = { 'name': str, 'elements': [str], 'release': v.Any(str, int), 'env-vars': dict, } <NEW_LINE> top_level = { 'script-dir': str, 'elements-dir': str, 'images-dir': str, 'dburi': str, 'zmq-publishers': [str], 'gearman-servers': [{ 'host': str, 'port': int, }], 'zookeeper-servers': [{ 'host': str, 'port': int, 'chroot': str, }], 'cron': cron, 'providers': [providers], 'labels': [labels], 'targets': [targets], 'diskimages': [diskimages], } <NEW_LINE> log.info("validating %s" % self.config_file) <NEW_LINE> config = yaml.load(open(self.config_file)) <NEW_LINE> schema = v.Schema(top_level) <NEW_LINE> schema(config) <NEW_LINE> all_providers = [p['name'] for p in config['providers']] <NEW_LINE> for label in config['labels']: <NEW_LINE> <INDENT> for provider in label['providers']: <NEW_LINE> <INDENT> if not provider['name'] in all_providers: <NEW_LINE> <INDENT> raise AssertionError('label %s requests ' 'non-existent provider %s' % (label['name'], provider['name']))
Check the layout and certain configuration options
62598fac2c8b7c6e89bd3776
class SelectizeWidget(JinjaWidget): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(SelectizeWidget, self).__init__('forms/selectize_widget.html') <NEW_LINE> <DEDENT> def __call__(self, field, **kwargs): <NEW_LINE> <INDENT> choices = [] <NEW_LINE> if field.data is not None: <NEW_LINE> <INDENT> choices.append({'name': field.data.name, 'id': field.data.id}) <NEW_LINE> <DEDENT> options = { 'valueField': 'id', 'labelField': 'name', 'searchField': 'name', 'persist': False, 'options': choices, 'create': False, 'maxItems': 1, 'closeAfterSelect': True } <NEW_LINE> options.update(kwargs.pop('options', {})) <NEW_LINE> return super(SelectizeWidget, self).__call__(field, options=options)
Renders a selectizer-based widget
62598fac5fc7496912d4825a
class TestDNSCheckConfirm: <NEW_LINE> <INDENT> @pytest.fixture(scope="module") <NEW_LINE> def setup(self): <NEW_LINE> <INDENT> config = DnstestConfig() <NEW_LINE> config.server_test = "test" <NEW_LINE> config.server_prod = "prod" <NEW_LINE> config.default_domain = ".example.com" <NEW_LINE> config.have_reverse_dns = True <NEW_LINE> chk = DNStestChecks(config) <NEW_LINE> chk.DNS.resolve_name = self.stub_resolve_name <NEW_LINE> chk.DNS.lookup_reverse = self.stub_lookup_reverse <NEW_LINE> return chk <NEW_LINE> <DEDENT> @pytest.fixture(scope="module") <NEW_LINE> def setup_ignorettl(self): <NEW_LINE> <INDENT> config = DnstestConfig() <NEW_LINE> config.server_test = "test" <NEW_LINE> config.server_prod = "prod" <NEW_LINE> config.default_domain = ".example.com" <NEW_LINE> config.have_reverse_dns = True <NEW_LINE> config.ignore_ttl = True <NEW_LINE> chk = DNStestChecks(config) <NEW_LINE> chk.DNS.resolve_name = self.stub_resolve_name <NEW_LINE> chk.DNS.lookup_reverse = self.stub_lookup_reverse <NEW_LINE> return chk <NEW_LINE> <DEDENT> def stub_resolve_name(self, query, to_server, to_port=53): <NEW_LINE> <INDENT> if query in known_dns[to_server]['fwd'] and 'status' in known_dns[to_server]['fwd'][query]: <NEW_LINE> <INDENT> return {'status': known_dns[to_server]['fwd'][query]['status']} <NEW_LINE> <DEDENT> elif query in known_dns[to_server]['fwd']: <NEW_LINE> <INDENT> return {'answer': known_dns[to_server]['fwd'][query]} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return {'status': 'NXDOMAIN'} <NEW_LINE> <DEDENT> <DEDENT> def stub_lookup_reverse(self, name, to_server, to_port=53): <NEW_LINE> <INDENT> if name in known_dns[to_server]['rev'] and known_dns[to_server]['rev'][name] == "SERVFAIL": <NEW_LINE> <INDENT> return {'status': 'SERVFAIL'} <NEW_LINE> <DEDENT> elif name in known_dns[to_server]['rev']: <NEW_LINE> <INDENT> return {'answer': {'name': name, 'data': known_dns[to_server]['rev'][name], 'typename': 'PTR', 'classstr': 'IN', 'ttl': 360, 'type': 12, 'class': 1, 'rdlength': 33}} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return {'status': 'NXDOMAIN'} <NEW_LINE> <DEDENT> <DEDENT> def test_confirm(self): <NEW_LINE> <INDENT> s = self.setup() <NEW_LINE> for t in TESTS: <NEW_LINE> <INDENT> tst = TESTS[t] <NEW_LINE> yield "test_confirm chk TESTS[%d]" % t, self.dns_confirm, s, tst['hostname'], tst['result'] <NEW_LINE> <DEDENT> <DEDENT> def dns_confirm(self, setup, hostname, result): <NEW_LINE> <INDENT> foo = setup.confirm_name(hostname) <NEW_LINE> assert foo == result <NEW_LINE> <DEDENT> def test_ignorettl(self, setup_ignorettl): <NEW_LINE> <INDENT> r = {'message': "prod and test servers return same response for 'ignorettl.example.com'", 'result': True, 'secondary': ["response: {'class': 1, 'classstr': 'IN', 'data': '1.2.14.1', 'name': 'ignorettl.example.com', 'rdlength': 4, 'type': 1, 'typename': 'A'}"], 'warnings': []} <NEW_LINE> foo = setup_ignorettl.confirm_name("ignorettl.example.com") <NEW_LINE> assert foo == r
Test DNS checks, using stubbed name resolution methods that return static values. The code in this class checks the logic of dnstest.py's confirm_name method, which takes a record name and verifies that the results are the same from prod and test servers.
62598facfff4ab517ebcd795
class Adaptive( Agent ): <NEW_LINE> <INDENT> def __call__( self, history, state = {} ): <NEW_LINE> <INDENT> if not state.has_key('sequence'): <NEW_LINE> <INDENT> state['sequence'] = [True, True, True, True, True, True, False, False, False, False, False] <NEW_LINE> <DEDENT> if len(history[0])>1: <NEW_LINE> <INDENT> if not state.has_key('count'): state['count'] = {} <NEW_LINE> if not state.has_key('revenue'): state['revenue'] = {} <NEW_LINE> opponent = history[1][-2] <NEW_LINE> reaction = history[0][-1] <NEW_LINE> revenue = PrisonersDilemma.revenue( history[0][-1], history[1][-1] )[0] <NEW_LINE> s_key = (opponent, reaction) <NEW_LINE> for key, val in [['count', 1], ['revenue', revenue]]: <NEW_LINE> <INDENT> if state[key].has_key( s_key ): <NEW_LINE> <INDENT> state[key][s_key] += val <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> state[key][s_key] = val <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if len( state['sequence'] ) > 0: <NEW_LINE> <INDENT> result = state['sequence'][0] <NEW_LINE> del state['sequence'][0] <NEW_LINE> return result <NEW_LINE> <DEDENT> probabilistic = super(Adaptive, self).probabilistic_bahaviour( state ) <NEW_LINE> if probabilistic is not None: <NEW_LINE> <INDENT> return probabilistic <NEW_LINE> <DEDENT> opponent = history[1][-1] <NEW_LINE> if state['revenue'].has_key((opponent, False)) and state['revenue'].has_key((opponent, True)): <NEW_LINE> <INDENT> defect_expectation = state['revenue'][(opponent, False)]/float(state['count'][(opponent, False)]) if state['count'][(opponent, False)] > 0 else 0 <NEW_LINE> cooperation_expectation = state['revenue'][(opponent, True)] /float(state['count'][(opponent, True)]) if state['count'][(opponent, True)] > 0 else 0 <NEW_LINE> return cooperation_expectation >= defect_expectation <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> char = 'A' <NEW_LINE> name = 'Adaptive' <NEW_LINE> def __str__( self ): <NEW_LINE> <INDENT> return self.char
Adaptive strategy.
62598fac76e4537e8c3ef55e
class UploadFile(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=50) <NEW_LINE> file = models.FileField(upload_to='./upload') <NEW_LINE> ctime = models.DateTimeField(auto_now_add=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> db_table = 't_upload_file'
上传的文件
62598fac7c178a314d78d44d
class HubUser(TimeStampedModel): <NEW_LINE> <INDENT> user = models.ForeignKey(USER_MODEL, related_name="hub_users") <NEW_LINE> hub = models.ForeignKey(Hub, related_name="hub_users") <NEW_LINE> is_admin = models.BooleanField(default=False) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> ordering = ['hub', 'user'] <NEW_LINE> unique_together = ('user', 'hub') <NEW_LINE> verbose_name = _("hub user") <NEW_LINE> verbose_name_plural = _("hub users") <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return u"%s (%s)" % (self.name if self.user.is_active else ( self.user.email), self.hub.name) <NEW_LINE> <DEDENT> def delete(self, using=None): <NEW_LINE> <INDENT> from .exceptions import OwnershipRequired <NEW_LINE> try: <NEW_LINE> <INDENT> if self.hub.owner.hub_user.id == self.id: <NEW_LINE> <INDENT> raise OwnershipRequired(_("Cannot delete hub owner before" " hub or transferring ownership.")) <NEW_LINE> <DEDENT> <DEDENT> except HubOwner.DoesNotExist: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> super(HubUser, self).delete(using=using) <NEW_LINE> <DEDENT> @permalink <NEW_LINE> def get_absolute_url(self): <NEW_LINE> <INDENT> return ('hubs:user_detail', (), {'hub_slug': self.hub.slug, 'user_username': self.user.username}) <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> if hasattr(self.user, 'get_full_name'): <NEW_LINE> <INDENT> name = self.user.get_full_name() <NEW_LINE> if name: <NEW_LINE> <INDENT> return name <NEW_LINE> <DEDENT> <DEDENT> return "%s" % self.user
ManyToMany through field relating Users to Hub. It is possible for a User to be a member of multiple hubs, so this class relates the HubUser to the User model using a ForeignKey relationship, rather than a OneToOne relationship. Authentication and general user information is handled by the User class and the contrib.auth application.
62598facbaa26c4b54d4f263
class MsgStartup(SBP): <NEW_LINE> <INDENT> _parser = Struct("MsgStartup", ULInt32('reserved'),) <NEW_LINE> def __init__(self, sbp=None, **kwargs): <NEW_LINE> <INDENT> if sbp: <NEW_LINE> <INDENT> self.__dict__.update(sbp.__dict__) <NEW_LINE> self.from_binary(sbp.payload) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> super( MsgStartup, self).__init__() <NEW_LINE> self.msg_type = SBP_MSG_STARTUP <NEW_LINE> self.sender = kwargs.pop('sender', 0) <NEW_LINE> self.reserved = kwargs.pop('reserved') <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return fmt_repr(self) <NEW_LINE> <DEDENT> def from_binary(self, d): <NEW_LINE> <INDENT> p = MsgStartup._parser.parse(d) <NEW_LINE> self.__dict__.update(dict(p.viewitems())) <NEW_LINE> <DEDENT> def to_binary(self): <NEW_LINE> <INDENT> c = containerize(exclude_fields(self)) <NEW_LINE> self.payload = MsgStartup._parser.build(c) <NEW_LINE> return self.pack() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def from_json(s): <NEW_LINE> <INDENT> d = json.loads(s) <NEW_LINE> sbp = SBP.from_json_dict(d) <NEW_LINE> return MsgStartup(sbp) <NEW_LINE> <DEDENT> def to_json_dict(self): <NEW_LINE> <INDENT> self.to_binary() <NEW_LINE> d = super( MsgStartup, self).to_json_dict() <NEW_LINE> j = walk_json_dict(exclude_fields(self)) <NEW_LINE> d.update(j) <NEW_LINE> return d
SBP class for message MSG_STARTUP (0xFF00). You can have MSG_STARTUP inherent its fields directly from an inherited SBP object, or construct it inline using a dict of its fields. The system start-up message is sent once on system start-up. It notifies the host or other attached devices that the system has started and is now ready to respond to commands or configuration requests. Parameters ---------- sbp : SBP SBP parent object to inherit from. reserved : int Reserved sender : int Optional sender ID, defaults to 0
62598fac16aa5153ce4004b3
class load_plugin(Event): <NEW_LINE> <INDENT> pass
Call me with pl ug-in to load
62598fac8e7ae83300ee9053
class PacketListStopField(PacketListField): <NEW_LINE> <INDENT> __slots__ = ["count_from", "length_from", "stop"] <NEW_LINE> def __init__(self, name, default, cls, count_from=None, length_from=None, stop=None): <NEW_LINE> <INDENT> PacketListField.__init__(self, name, default, cls, count_from=count_from, length_from=length_from) <NEW_LINE> self.stop = stop <NEW_LINE> <DEDENT> def getfield(self, pkt, s): <NEW_LINE> <INDENT> c = l = None <NEW_LINE> if self.length_from is not None: <NEW_LINE> <INDENT> l = self.length_from(pkt) <NEW_LINE> <DEDENT> elif self.count_from is not None: <NEW_LINE> <INDENT> c = self.count_from(pkt) <NEW_LINE> <DEDENT> lst = [] <NEW_LINE> ret = "" <NEW_LINE> remain = s <NEW_LINE> if l is not None: <NEW_LINE> <INDENT> remain, ret = s[:l], s[l:] <NEW_LINE> <DEDENT> while remain: <NEW_LINE> <INDENT> if c is not None: <NEW_LINE> <INDENT> if c <= 0: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> c -= 1 <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> p = self.m2i(pkt, remain) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> if conf.debug_dissector: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> p = conf.raw_layer(load=remain) <NEW_LINE> remain = "" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if conf.padding_layer in p: <NEW_LINE> <INDENT> pad = p[conf.padding_layer] <NEW_LINE> remain = pad.load <NEW_LINE> del (pad.underlayer.payload) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> remain = "" <NEW_LINE> <DEDENT> <DEDENT> lst.append(p) <NEW_LINE> if self.stop and self.stop(p): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> return remain + ret, lst
Custom field that contains a list of packets until a 'stop' condition is met.
62598fac10dbd63aa1c70b64
class ResourceLink(common.Object): <NEW_LINE> <INDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._data['name'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def description(self): <NEW_LINE> <INDENT> return self._data['description'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def recycle(self): <NEW_LINE> <INDENT> return self._data["recycle"] <NEW_LINE> <DEDENT> @property <NEW_LINE> def links(self): <NEW_LINE> <INDENT> full_ids = self._data['links'] <NEW_LINE> resources = self.bridge.get_from_full_ids(full_ids) <NEW_LINE> return [resources[fid] for fid in full_ids]
Represents a Hue resourcelink.
62598facadb09d7d5dc0a53b
class SingletonQuery(Query): <NEW_LINE> <INDENT> def __init__(self, sense): <NEW_LINE> <INDENT> self.sense = sense <NEW_LINE> <DEDENT> def clause(self): <NEW_LINE> <INDENT> if self.sense: <NEW_LINE> <INDENT> return "album_id ISNULL", () <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "NOT album_id ISNULL", () <NEW_LINE> <DEDENT> <DEDENT> def match(self, item): <NEW_LINE> <INDENT> return (not item.album_id) == self.sense
Matches either singleton or non-singleton items.
62598fac56ac1b37e630219d
class AddVCenterRequest(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'properties': {'key': 'properties', 'type': 'AddVCenterRequestProperties'}, } <NEW_LINE> def __init__( self, *, properties: Optional["AddVCenterRequestProperties"] = None, **kwargs ): <NEW_LINE> <INDENT> super(AddVCenterRequest, self).__init__(**kwargs) <NEW_LINE> self.properties = properties
Input required to add vCenter. :param properties: The properties of an add vCenter request. :type properties: ~azure.mgmt.recoveryservicessiterecovery.models.AddVCenterRequestProperties
62598faccc0a2c111447afc2
class _better_cache: <NEW_LINE> <INDENT> def __init__(self, repositories): <NEW_LINE> <INDENT> self._items = collections.defaultdict(list) <NEW_LINE> self._scanned_cats = set() <NEW_LINE> self._repo_list = [ repo for repo in reversed(list(repositories)) if repo.location is not None ] <NEW_LINE> <DEDENT> def __getitem__(self, catpkg): <NEW_LINE> <INDENT> result = self._items.get(catpkg) <NEW_LINE> if result is not None: <NEW_LINE> <INDENT> return result <NEW_LINE> <DEDENT> cat, pkg = catsplit(catpkg) <NEW_LINE> if cat not in self._scanned_cats: <NEW_LINE> <INDENT> self._scan_cat(cat) <NEW_LINE> <DEDENT> return self._items[catpkg] <NEW_LINE> <DEDENT> def _scan_cat(self, cat): <NEW_LINE> <INDENT> for repo in self._repo_list: <NEW_LINE> <INDENT> cat_dir = repo.location + "/" + cat <NEW_LINE> try: <NEW_LINE> <INDENT> pkg_list = os.listdir(cat_dir) <NEW_LINE> <DEDENT> except OSError as e: <NEW_LINE> <INDENT> if e.errno not in (errno.ENOTDIR, errno.ENOENT, errno.ESTALE): <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> continue <NEW_LINE> <DEDENT> for p in pkg_list: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> atom = Atom("%s/%s" % (cat, p)) <NEW_LINE> <DEDENT> except InvalidAtom: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if atom != atom.cp: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> self._items[atom.cp].append(repo) <NEW_LINE> <DEDENT> <DEDENT> self._scanned_cats.add(cat)
The purpose of better_cache is to locate catpkgs in repositories using ``os.listdir()`` as much as possible, which is less expensive IO-wise than exhaustively doing a stat on each repo for a particular catpkg. better_cache stores a list of repos in which particular catpkgs appear. Various dbapi methods use better_cache to locate repositories of interest related to particular catpkg rather than performing an exhaustive scan of all repos/overlays. Better_cache.items data may look like this:: { "sys-apps/portage" : [ repo1, repo2 ] } Without better_cache, Portage will get slower and slower (due to excessive IO) as more overlays are added. Also note that it is OK if this cache has some 'false positive' catpkgs in it. We use it to search for specific catpkgs listed in ebuilds. The likelihood of a false positive catpkg in our cache causing a problem is extremely low, because the user of our cache is passing us a catpkg that came from somewhere and has already undergone some validation, and even then will further interrogate the short-list of repos we return to gather more information on the catpkg. Thus, the code below is optimized for speed rather than painstaking correctness. I have added a note to ``dbapi.getRepositories()`` to ensure that developers are aware of this just in case. The better_cache has been redesigned to perform on-demand scans -- it will only scan a category at a time, as needed. This should further optimize IO performance by not scanning category directories that are not needed by Portage.
62598face1aae11d1e7ce7fc
class VolumeController(wsgi.Controller): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.volume_api = volume.API() <NEW_LINE> super(VolumeController, self).__init__() <NEW_LINE> <DEDENT> @extensions.expected_errors(404) <NEW_LINE> def show(self, req, id): <NEW_LINE> <INDENT> context = req.environ['nova.context'] <NEW_LINE> authorize(context) <NEW_LINE> try: <NEW_LINE> <INDENT> vol = self.volume_api.get(context, id) <NEW_LINE> <DEDENT> except exception.NotFound as e: <NEW_LINE> <INDENT> raise exc.HTTPNotFound(explanation=e.format_message()) <NEW_LINE> <DEDENT> return {'volume': _translate_volume_detail_view(context, vol)} <NEW_LINE> <DEDENT> @extensions.expected_errors(404) <NEW_LINE> def delete(self, req, id): <NEW_LINE> <INDENT> context = req.environ['nova.context'] <NEW_LINE> authorize(context) <NEW_LINE> LOG.audit(_("Delete volume with id: %s"), id, context=context) <NEW_LINE> try: <NEW_LINE> <INDENT> self.volume_api.delete(context, id) <NEW_LINE> <DEDENT> except exception.NotFound as e: <NEW_LINE> <INDENT> raise exc.HTTPNotFound(explanation=e.format_message()) <NEW_LINE> <DEDENT> return webob.Response(status_int=202) <NEW_LINE> <DEDENT> @extensions.expected_errors(()) <NEW_LINE> def index(self, req): <NEW_LINE> <INDENT> return self._items(req, entity_maker=_translate_volume_summary_view) <NEW_LINE> <DEDENT> @extensions.expected_errors(()) <NEW_LINE> def detail(self, req): <NEW_LINE> <INDENT> return self._items(req, entity_maker=_translate_volume_detail_view) <NEW_LINE> <DEDENT> def _items(self, req, entity_maker): <NEW_LINE> <INDENT> context = req.environ['nova.context'] <NEW_LINE> authorize(context) <NEW_LINE> volumes = self.volume_api.get_all(context) <NEW_LINE> limited_list = common.limited(volumes, req) <NEW_LINE> res = [entity_maker(context, vol) for vol in limited_list] <NEW_LINE> return {'volumes': res} <NEW_LINE> <DEDENT> @extensions.expected_errors(400) <NEW_LINE> def create(self, req, body): <NEW_LINE> <INDENT> context = req.environ['nova.context'] <NEW_LINE> authorize(context) <NEW_LINE> if not self.is_valid_body(body, 'volume'): <NEW_LINE> <INDENT> msg = _("volume not specified") <NEW_LINE> raise exc.HTTPBadRequest(explanation=msg) <NEW_LINE> <DEDENT> vol = body['volume'] <NEW_LINE> vol_type = vol.get('volume_type') <NEW_LINE> metadata = vol.get('metadata') <NEW_LINE> snapshot_id = vol.get('snapshot_id') <NEW_LINE> if snapshot_id is not None: <NEW_LINE> <INDENT> snapshot = self.volume_api.get_snapshot(context, snapshot_id) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> snapshot = None <NEW_LINE> <DEDENT> size = vol.get('size', None) <NEW_LINE> if size is None and snapshot is not None: <NEW_LINE> <INDENT> size = snapshot['volume_size'] <NEW_LINE> <DEDENT> LOG.audit(_("Create volume of %s GB"), size, context=context) <NEW_LINE> availability_zone = vol.get('availability_zone') <NEW_LINE> try: <NEW_LINE> <INDENT> new_volume = self.volume_api.create( context, size, vol.get('display_name'), vol.get('display_description'), snapshot=snapshot, volume_type=vol_type, metadata=metadata, availability_zone=availability_zone ) <NEW_LINE> <DEDENT> except exception.InvalidInput as err: <NEW_LINE> <INDENT> raise exc.HTTPBadRequest(explanation=err.format_message()) <NEW_LINE> <DEDENT> retval = _translate_volume_detail_view(context, dict(new_volume)) <NEW_LINE> result = {'volume': retval} <NEW_LINE> location = '%s/%s' % (req.url, new_volume['id']) <NEW_LINE> return wsgi.ResponseObject(result, headers=dict(location=location))
The Volumes API controller for the OpenStack API.
62598fac99cbb53fe6830e89
class EventUpdate(EventBase): <NEW_LINE> <INDENT> event = models.ForeignKey(Event) <NEW_LINE> status = models.SmallIntegerField(choices=STATUS_CHOICES) <NEW_LINE> message = models.TextField(null=True, blank=True) <NEW_LINE> date_created = models.DateTimeField(auto_now_add=True, editable=False) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return unicode(self.date_created) <NEW_LINE> <DEDENT> def get_services(self): <NEW_LINE> <INDENT> return self.event.services.values_list('slug', 'name')
An ``EventUpdate`` contains a single update to an ``Event``. The latest update will always be reflected within the event, carrying over it's ``status`` and ``message``.
62598face5267d203ee6b8bb
class TestArchRootPyPIInstall(TestCase): <NEW_LINE> <INDENT> _shell = None <NEW_LINE> _PROMPT = r'\[root@.* /\]# ' <NEW_LINE> @classmethod <NEW_LINE> def setUpClass(cls): <NEW_LINE> <INDENT> cls._shell = pexpect.spawn('docker run --rm -it base/archlinux', timeout=90) <NEW_LINE> <DEDENT> def test_install(self): <NEW_LINE> <INDENT> self._install_pip() <NEW_LINE> self._shell.sendline('pip install kytos') <NEW_LINE> i = self._shell.expect(['Successfully installed .*kytos', self._PROMPT], timeout=90) <NEW_LINE> self.assertEqual(0, i, "Couldn't install kytos:\n" + self._shell.before.decode('utf-8')) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _install_pip(cls): <NEW_LINE> <INDENT> cls._shell.expect(cls._PROMPT) <NEW_LINE> cls._shell.sendline('pacman -Sy --noconfirm python-pip') <NEW_LINE> cls._shell.expect(cls._PROMPT, timeout=120) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def tearDownClass(cls): <NEW_LINE> <INDENT> if cls._shell: <NEW_LINE> <INDENT> cls._shell.sendline('exit')
As root, install Kytos from PyPI using pip in Archlinux. This test reproduces kytos#465.
62598facd268445f26639b5c
class GSBFrame(VLBIFrameBase): <NEW_LINE> <INDENT> _header_class = GSBHeader <NEW_LINE> _payload_class = GSBPayload <NEW_LINE> @classmethod <NEW_LINE> def fromfile(cls, fh_ts, fh_raw, payloadsize=1 << 24, nchan=1, bps=4, complex_data=False, valid=True, verify=True): <NEW_LINE> <INDENT> header = cls._header_class.fromfile(fh_ts, verify=verify) <NEW_LINE> payload = cls._payload_class.fromfile(fh_raw, payloadsize=payloadsize, nchan=nchan, bps=bps, complex_data=complex_data) <NEW_LINE> return cls(header, payload, valid=valid, verify=verify) <NEW_LINE> <DEDENT> def tofile(self, fh_ts, fh_raw): <NEW_LINE> <INDENT> self.header.tofile(fh_ts) <NEW_LINE> self.payload.tofile(fh_raw) <NEW_LINE> <DEDENT> @property <NEW_LINE> def size(self): <NEW_LINE> <INDENT> return self.payload.size
Frame encapsulating GSB Rawdump or Phased data. For Rawdump data, lines in the timestamp file are associated with single blocks of raw data. For Phased data, the lines are associated with one or two polarisations, each consisting of two blocks of raw data. Hence, the raw data come from two or four files. Parameters ---------- header : `~baseband.gsb.GSBHeader` Based on line from Rawdump or Phased timestamp file. payload : `~baseband.gsb.GSBPayload` or `~baseband.gsb.GSBPhasedPayload` Based on a single block of rawdump data, or the combined blocks for phased data. valid : bool Whether the frame contains valid data (default: `True`). verify : bool Whether to verify consistency of the frame parts (default: `True`).
62598fac3539df3088ecc264
class PlanningProblem: <NEW_LINE> <INDENT> def getStartState(self): <NEW_LINE> <INDENT> util.raiseNotDefined() <NEW_LINE> <DEDENT> def getGhostStartStates(self): <NEW_LINE> <INDENT> util.raiseNotDefined() <NEW_LINE> <DEDENT> def getGoalState(self): <NEW_LINE> <INDENT> util.raiseNotDefined()
This class outlines the structure of a planning problem, but doesn't implement any of the methods (in object-oriented terminology: an abstract class). You do not need to change anything in this class, ever.
62598fac45492302aabfc483
class InputLine(BrowsableObject): <NEW_LINE> <INDENT> def sum(self, code, from_date, to_date=None): <NEW_LINE> <INDENT> if to_date is None: <NEW_LINE> <INDENT> to_date = datetime.now().strftime('%Y-%m-%d') <NEW_LINE> <DEDENT> self.cr.execute( "SELECT sum(amount) as sum" "FROM hr_payslip as hp, hr_payslip_input as pi " "WHERE hp.employee_id = %s AND hp.state = 'done' " "AND hp.date_from >= %s AND hp.date_to <= %s " "AND hp.id = pi.payslip_id AND pi.code = %s", (self.employee_id, from_date, to_date, code)) <NEW_LINE> res = self.cr.fetchone()[0] <NEW_LINE> return res or 0.0
a class that will be used into the python code, mainly for usability purposes
62598faca17c0f6771d5c1e7
class _FromGrouping(FromClause): <NEW_LINE> <INDENT> __visit_name__ = 'grouping' <NEW_LINE> def __init__(self, element): <NEW_LINE> <INDENT> self.element = element <NEW_LINE> <DEDENT> @property <NEW_LINE> def columns(self): <NEW_LINE> <INDENT> return self.element.columns <NEW_LINE> <DEDENT> @property <NEW_LINE> def _hide_froms(self): <NEW_LINE> <INDENT> return self.element._hide_froms <NEW_LINE> <DEDENT> def get_children(self, **kwargs): <NEW_LINE> <INDENT> return self.element, <NEW_LINE> <DEDENT> def _copy_internals(self, clone=_clone): <NEW_LINE> <INDENT> self.element = clone(self.element) <NEW_LINE> <DEDENT> @property <NEW_LINE> def _from_objects(self): <NEW_LINE> <INDENT> return self.element._from_objects <NEW_LINE> <DEDENT> def __getattr__(self, attr): <NEW_LINE> <INDENT> return getattr(self.element, attr) <NEW_LINE> <DEDENT> def __getstate__(self): <NEW_LINE> <INDENT> return {'element':self.element} <NEW_LINE> <DEDENT> def __setstate__(self, state): <NEW_LINE> <INDENT> self.element = state['element']
Represent a grouping of a FROM clause
62598fac67a9b606de545f7f
class URLRequestStats(object): <NEW_LINE> <INDENT> def __init__(self, statsproto): <NEW_LINE> <INDENT> self.rpcstatslist = [] <NEW_LINE> self.timestamp = statsproto.start_timestamp_milliseconds() * 0.001 <NEW_LINE> self.totalresponsetime = int(statsproto.duration_milliseconds()) <NEW_LINE> for t in statsproto.individual_stats_list(): <NEW_LINE> <INDENT> self.AddRPCStats(t) <NEW_LINE> <DEDENT> self.totalrpctime = self.TotalRPCTime() <NEW_LINE> <DEDENT> def TotalRPCTime(self): <NEW_LINE> <INDENT> totalrpctime = 0 <NEW_LINE> for rpc in self.rpcstatslist: <NEW_LINE> <INDENT> totalrpctime += rpc.time <NEW_LINE> <DEDENT> return totalrpctime <NEW_LINE> <DEDENT> def AddRPCStats(self, rpcstatsproto): <NEW_LINE> <INDENT> for rpc in self.rpcstatslist: <NEW_LINE> <INDENT> if rpc.Match(rpcstatsproto): <NEW_LINE> <INDENT> rpc.Incr(rpcstatsproto) <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> rpcstats = RPCStats(rpcstatsproto) <NEW_LINE> self.rpcstatslist.append(rpcstats) <NEW_LINE> <DEDENT> def _IncrementCount(self, key_list, group_flag, freq, action): <NEW_LINE> <INDENT> for key in key_list: <NEW_LINE> <INDENT> if group_flag: <NEW_LINE> <INDENT> name = entity.EntityGroupName(key) <NEW_LINE> kind = entity.EntityGroupKind(key) <NEW_LINE> kind_name = '%s,%s' %(kind, name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> name = entity.EntityFullName(key) <NEW_LINE> kind = entity.EntityKind(key) <NEW_LINE> kind_name = '%s,%s' %(kind, name) <NEW_LINE> <DEDENT> if not kind_name in freq: <NEW_LINE> <INDENT> freq[kind_name] = {'read': 0, 'write': 0, 'miss': 0} <NEW_LINE> <DEDENT> freq[kind_name][action] += 1 <NEW_LINE> <DEDENT> <DEDENT> def EntityGroupCount(self): <NEW_LINE> <INDENT> freq = {} <NEW_LINE> for rpcstats in self.rpcstatslist: <NEW_LINE> <INDENT> self._IncrementCount(rpcstats.keys_read, True, freq, 'read') <NEW_LINE> self._IncrementCount(rpcstats.keys_written, True, freq, 'write') <NEW_LINE> self._IncrementCount(rpcstats.keys_failed_get, True, freq, 'miss') <NEW_LINE> <DEDENT> return freq <NEW_LINE> <DEDENT> def EntityCount(self): <NEW_LINE> <INDENT> freq = {} <NEW_LINE> for rpcstats in self.rpcstatslist: <NEW_LINE> <INDENT> self._IncrementCount(rpcstats.keys_read, False, freq, 'read') <NEW_LINE> self._IncrementCount(rpcstats.keys_written, False, freq, 'write') <NEW_LINE> self._IncrementCount(rpcstats.keys_failed_get, False, freq, 'miss') <NEW_LINE> <DEDENT> return freq
Statistics associated with each URL request. For each URL request, keep track of list of RPCs, statistics associated with each RPC, and total response time for that URL request.
62598fac2c8b7c6e89bd3778
class AFGHEncrypter(CommonEncrypter): <NEW_LINE> <INDENT> name = "afgh1-aes" <NEW_LINE> attributes = ("passphrase", "key") <NEW_LINE> iv_size = 16 <NEW_LINE> aes_key_size = 32 <NEW_LINE> hash_size = 32 <NEW_LINE> aes_mode = CryptoAES.MODE_CFB <NEW_LINE> afgh_key_size = 32 <NEW_LINE> afgh_decrypt_method = "decrypt_my" <NEW_LINE> def _init_encryption(self, passphrase=None, key=None): <NEW_LINE> <INDENT> if passphrase is not None: <NEW_LINE> <INDENT> assert key is None <NEW_LINE> self.afgh_key = crypto.Key.from_passphrase(passphrase) <NEW_LINE> <DEDENT> elif key is not None: <NEW_LINE> <INDENT> assert len(key) == self.afgh_key_size <NEW_LINE> self.afgh_key = crypto.Key.load_priv(key) <NEW_LINE> <DEDENT> self._decrypt_method = getattr(self.afgh_key, self.afgh_decrypt_method) <NEW_LINE> self._rand = Random.new() <NEW_LINE> <DEDENT> def _encrypt(self, data): <NEW_LINE> <INDENT> iv = self._rand.read(self.iv_size) <NEW_LINE> aes_key = self._rand.read(self.aes_key_size) <NEW_LINE> aes_cipher = CryptoAES.new(aes_key, self.aes_mode, iv) <NEW_LINE> h = sha256(data).digest() <NEW_LINE> edata = aes_cipher.encrypt(data + h) + iv <NEW_LINE> kdata = self.afgh_key.encrypt(aes_key) <NEW_LINE> len_kdata = struct.pack("H", len(kdata)) <NEW_LINE> return len_kdata + kdata + edata <NEW_LINE> <DEDENT> def _decrypt(self, edata): <NEW_LINE> <INDENT> len_kdata, = struct.unpack("H", edata[:2]) <NEW_LINE> kdata = edata[2:len_kdata + 2] <NEW_LINE> adata = edata[len_kdata + 2:-self.iv_size] <NEW_LINE> iv = edata[-self.iv_size:] <NEW_LINE> aes_key = self._decrypt_method(kdata) <NEW_LINE> if len(aes_key) != self.aes_key_size: <NEW_LINE> <INDENT> raise WrongKeyError("Data couldn't be decrypted. Probably your key is wrong") <NEW_LINE> <DEDENT> aes_cipher = CryptoAES.new(aes_key, self.aes_mode, iv) <NEW_LINE> datah = aes_cipher.decrypt(adata) <NEW_LINE> h = datah[-self.hash_size:] <NEW_LINE> data = datah[:-self.hash_size] <NEW_LINE> if sha256(data).digest() == h: <NEW_LINE> <INDENT> return data <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise WrongKeyError("Data couldn't be decrypted. Probably your key is wrong") <NEW_LINE> <DEDENT> <DEDENT> def get_pubkey(self): <NEW_LINE> <INDENT> return self.afgh_key.dump_pub() <NEW_LINE> <DEDENT> def get_re_key(self, pub): <NEW_LINE> <INDENT> return self.afgh_key.re_key(pub).dump()
AFGH proxy re-encryption combined with AES. This class is to encrypt and decrypt whatever is encrypted for us
62598faceab8aa0e5d30bd3e
class HTTP_FILTER_AUTHENT(object): <NEW_LINE> <INDENT> def __new__(cls): <NEW_LINE> <INDENT> raise Exception('This class just for typing, can not be instanced!') <NEW_LINE> <DEDENT> @property <NEW_LINE> def User(self)->'str': <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @property <NEW_LINE> def Password(self)->'str': <NEW_LINE> <INDENT> pass
A Python representation of an ISAPI HTTP_FILTER_AUTHENT structure.
62598fac498bea3a75a57ad0
class Enemy(Role, object): <NEW_LINE> <INDENT> _uid = Role._uid <NEW_LINE> def __init__(self, family, health, attack, jump_height, texture_path): <NEW_LINE> <INDENT> super(Enemy, self).__init__(family, health, attack, jump_height, texture_path) <NEW_LINE> self._hostile = True <NEW_LINE> <DEDENT> @property <NEW_LINE> def hostile(self): <NEW_LINE> <INDENT> return self._hostile
The actor will be an enemy to/able to be fought by the player.
62598fac76e4537e8c3ef560
class ClientSalaryHistoryView(Viewable): <NEW_LINE> <INDENT> id = ClientSalaryHistory.id <NEW_LINE> date = ClientSalaryHistory.date <NEW_LINE> new_salary = ClientSalaryHistory.new_salary <NEW_LINE> user = Person.name <NEW_LINE> tables = [ ClientSalaryHistory, LeftJoin(LoginUser, LoginUser.id == ClientSalaryHistory.user_id), LeftJoin(Person, LoginUser.person_id == Person.id), ] <NEW_LINE> @classmethod <NEW_LINE> def find_by_client(cls, store, client): <NEW_LINE> <INDENT> resultset = store.find(cls) <NEW_LINE> if client is not None: <NEW_LINE> <INDENT> resultset = resultset.find(ClientSalaryHistory.client == client) <NEW_LINE> <DEDENT> return resultset
Store information about a client's salary history
62598fac99cbb53fe6830e8a
class HeteroskedasticDecoder(nn.Module): <NEW_LINE> <INDENT> def __init__(self, x_dim, rep_dim, y_dim, hid_dim, num_hid): <NEW_LINE> <INDENT> super(HeteroskedasticDecoder, self).__init__() <NEW_LINE> self.x_dim = x_dim <NEW_LINE> self.rep_dim = rep_dim <NEW_LINE> self.y_dim = y_dim <NEW_LINE> self.hid_dim = hid_dim <NEW_LINE> self.num_hid = num_hid <NEW_LINE> self.x_rep_to_hidden = MLP(self.x_dim + self.rep_dim, self.hid_dim, self.hid_dim, self.num_hid) <NEW_LINE> self.hidden_to_mu = nn.Linear(self.hid_dim, self.y_dim) <NEW_LINE> self.hidden_to_pre_sigma = nn.Linear(self.hid_dim, self.y_dim) <NEW_LINE> <DEDENT> def forward(self, x, rep): <NEW_LINE> <INDENT> batch_size, num_points, _ = x.size() <NEW_LINE> rep = rep.view(batch_size * num_points, self.rep_dim) <NEW_LINE> x = x.view(batch_size * num_points, self.x_dim) <NEW_LINE> input = torch.cat((x, rep), dim=1) <NEW_LINE> hidden = nn.functional.relu(self.x_rep_to_hidden(input)) <NEW_LINE> mu = self.hidden_to_mu(hidden) <NEW_LINE> pre_sigma = self.hidden_to_pre_sigma(hidden) <NEW_LINE> mu = mu.view(batch_size, num_points, self.y_dim) <NEW_LINE> pre_sigma = pre_sigma.view(batch_size, num_points, self.y_dim) <NEW_LINE> sigma = 0.1 + 0.9 * F.softplus(pre_sigma) <NEW_LINE> return mu, sigma
Maps target inputs x and samples of the latent representaion z (which encodes the context points) to target outputs y. Predicts both the mean and variance of the process. Parameters ---------- x_dim : int Dimension of the x values. rep_dim : int Dimension of the representation variable (r+z). y_dim : int Dimension of the y values. hid_dim : int Dimension of the hidden layers. num_hid : int Number of hidden layers in the decoder.
62598fac4428ac0f6e6584d7