code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class CheckAllOutputTest(unittest.TestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def _call(cls, *args, **kwargs): <NEW_LINE> <INDENT> from certbot_postfix.util import check_all_output <NEW_LINE> return check_all_output(*args, **kwargs) <NEW_LINE> <DEDENT> @mock.patch('certbot_postfix.util.logger') <NEW_LINE> @mock.patch('certbot_postfix.util.subprocess.Popen') <NEW_LINE> def test_command_error(self, mock_popen, mock_logger): <NEW_LINE> <INDENT> command = 'foo' <NEW_LINE> retcode = 42 <NEW_LINE> output = 'bar' <NEW_LINE> err = 'baz' <NEW_LINE> mock_popen().communicate.return_value = (output, err) <NEW_LINE> mock_popen().poll.return_value = 42 <NEW_LINE> self.assertRaises(subprocess.CalledProcessError, self._call, command) <NEW_LINE> log_args = mock_logger.debug.call_args[0] <NEW_LINE> for value in (command, retcode, output, err,): <NEW_LINE> <INDENT> self.assertTrue(value in log_args) <NEW_LINE> <DEDENT> <DEDENT> @mock.patch('certbot_postfix.util.subprocess.Popen') <NEW_LINE> def test_success(self, mock_popen): <NEW_LINE> <INDENT> command = 'foo' <NEW_LINE> expected = ('bar', '') <NEW_LINE> mock_popen().communicate.return_value = expected <NEW_LINE> mock_popen().poll.return_value = 0 <NEW_LINE> self.assertEqual(self._call(command), expected) <NEW_LINE> <DEDENT> def test_stdout_error(self): <NEW_LINE> <INDENT> self.assertRaises(ValueError, self._call, stdout=None) <NEW_LINE> <DEDENT> def test_stderr_error(self): <NEW_LINE> <INDENT> self.assertRaises(ValueError, self._call, stderr=None) <NEW_LINE> <DEDENT> def test_universal_newlines_error(self): <NEW_LINE> <INDENT> self.assertRaises(ValueError, self._call, universal_newlines=False)
Tests for certbot_postfix.util.check_all_output.
62598fa3baa26c4b54d4f139
class RegExpIdBase(Rule): <NEW_LINE> <INDENT> labels = [ _('Text:') ] <NEW_LINE> name = _('Objects with <Id>') <NEW_LINE> description = _("Matches objects whose Gramps ID contains a substring " "or matches a regular expression") <NEW_LINE> category = _('General filters') <NEW_LINE> allow_regex = True <NEW_LINE> def apply(self, db, obj): <NEW_LINE> <INDENT> return self.match_substring(0, obj.gramps_id)
Rule that checks for an object whose GRAMPS ID matches regular expression.
62598fa3a17c0f6771d5c0c3
class BSFilter: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.keywords = [] <NEW_LINE> self.kwsets = set([]) <NEW_LINE> self.bsdict = defaultdict(set) <NEW_LINE> self.pat_en = re.compile(r'^[0-9a-zA-Z]+$') <NEW_LINE> <DEDENT> def add(self, keyword): <NEW_LINE> <INDENT> if not isinstance(keyword, str): <NEW_LINE> <INDENT> keyword = keyword.decode('utf-8') <NEW_LINE> <DEDENT> keyword = keyword.lower() <NEW_LINE> if keyword not in self.kwsets: <NEW_LINE> <INDENT> self.keywords.append(keyword) <NEW_LINE> self.kwsets.add(keyword) <NEW_LINE> index = len(self.keywords) - 1 <NEW_LINE> for word in keyword.split(): <NEW_LINE> <INDENT> if self.pat_en.search(word): <NEW_LINE> <INDENT> self.bsdict[word].add(index) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for char in word: <NEW_LINE> <INDENT> self.bsdict[char].add(index) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def parse(self, path): <NEW_LINE> <INDENT> with open(path, "r") as f: <NEW_LINE> <INDENT> for keyword in f: <NEW_LINE> <INDENT> self.add(keyword.strip()) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def filter(self, message, repl="*"): <NEW_LINE> <INDENT> if not isinstance(message, str): <NEW_LINE> <INDENT> message = message.decode('utf-8') <NEW_LINE> <DEDENT> message = message.lower() <NEW_LINE> for word in message.split(): <NEW_LINE> <INDENT> if self.pat_en.search(word): <NEW_LINE> <INDENT> for index in self.bsdict[word]: <NEW_LINE> <INDENT> message = message.replace(self.keywords[index], repl) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for char in word: <NEW_LINE> <INDENT> for index in self.bsdict[char]: <NEW_LINE> <INDENT> message = message.replace(self.keywords[index], repl) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return message
Filter Messages from keywords Use Back Sorted Mapping to reduce replacement times >>> f = BSFilter() >>> f.add("sexy") >>> f.filter("hello sexy baby") hello **** baby
62598fa34e4d5625663722ad
class Token(Enum): <NEW_LINE> <INDENT> OR = ("or", 0, Associative.LEFT, TokenType.OPERATOR) <NEW_LINE> AND = ("and", 1, Associative.LEFT, TokenType.OPERATOR) <NEW_LINE> NOT = ("not", 2, Associative.RIGHT, TokenType.OPERATOR) <NEW_LINE> OPEN_PARENTHESIS = ("(", -2) <NEW_LINE> CLOSE_PARENTHESIS = (")", -1) <NEW_LINE> def __init__(self, keyword, precedence, assoc=None, token_type=TokenType.OPERAND): <NEW_LINE> <INDENT> self.keyword = keyword <NEW_LINE> self.precedence = precedence <NEW_LINE> self.assoc = assoc <NEW_LINE> self.token_type = token_type <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_operation(self): <NEW_LINE> <INDENT> return self.token_type is TokenType.OPERATOR <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_binary(self): <NEW_LINE> <INDENT> return self in (Token.OR, Token.AND) <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_unary(self): <NEW_LINE> <INDENT> return self is Token.NOT <NEW_LINE> <DEDENT> def has_lower_precedence_than(self, other): <NEW_LINE> <INDENT> return ( ((self.assoc == Associative.LEFT) and (self.precedence <= other.precedence)) or ((self.assoc == Associative.RIGHT) and (self.precedence < other.precedence)) ) <NEW_LINE> <DEDENT> def matches(self, text): <NEW_LINE> <INDENT> return self.keyword == text
Describes tokens and their abilities for tag-expression parsing.
62598fa39c8ee823130400b3
class Reader: <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def read_file(file_path): <NEW_LINE> <INDENT> text = '' <NEW_LINE> with open(file_path, 'r') as file: <NEW_LINE> <INDENT> for line in file.readlines(): <NEW_LINE> <INDENT> text += line <NEW_LINE> <DEDENT> <DEDENT> return text <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def read_input(): <NEW_LINE> <INDENT> read = sys.stdin.readlines() <NEW_LINE> text = '' <NEW_LINE> for line in read: <NEW_LINE> <INDENT> text += line <NEW_LINE> <DEDENT> return text
Used in handling reading input.
62598fa3097d151d1a2c0eb4
class ProjectVersionsView(generics.ListAPIView): <NEW_LINE> <INDENT> serializer_class = serializers.VerboseVersionSerializer <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> documents = utils.list_versions(self.kwargs['name']) <NEW_LINE> if documents: <NEW_LINE> <INDENT> return documents <NEW_LINE> <DEDENT> raise Http404
Displays all the versions associated with a specific project.
62598fa3d7e4931a7ef3bf23
class ReaderTester: <NEW_LINE> <INDENT> filename = Undefined <NEW_LINE> start_time = Undefined <NEW_LINE> end_time = Undefined <NEW_LINE> time_zone = Undefined <NEW_LINE> name = Undefined <NEW_LINE> lat_long = Undefined <NEW_LINE> fields = Undefined <NEW_LINE> units = Undefined <NEW_LINE> sample_data = Undefined <NEW_LINE> def test_start_time(self): <NEW_LINE> <INDENT> assert_equal(self.MD.Times[0], self.start_time) <NEW_LINE> <DEDENT> def test_end_time(self): <NEW_LINE> <INDENT> if self.end_time is not Undefined: <NEW_LINE> <INDENT> assert_equal(self.MD.Times[-1], self.end_time) <NEW_LINE> <DEDENT> <DEDENT> def test_fields(self): <NEW_LINE> <INDENT> if self.fields is not Undefined: <NEW_LINE> <INDENT> assert_equal(set(self.MD.Fields.keys()), set(self.fields)) <NEW_LINE> <DEDENT> <DEDENT> def test_units(self): <NEW_LINE> <INDENT> if self.units is not Undefined: <NEW_LINE> <INDENT> for key, value in list(self.units.items()): <NEW_LINE> <INDENT> assert_equal(self.MD.Units[key], value) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def test_time_zone(self): <NEW_LINE> <INDENT> if self.time_zone is not Undefined: <NEW_LINE> <INDENT> assert_equal(self.MD.TimeZone, self.time_zone) <NEW_LINE> <DEDENT> <DEDENT> def test_name(self): <NEW_LINE> <INDENT> if self.name is not Undefined: <NEW_LINE> <INDENT> assert_equal(self.MD.Name, self.name) <NEW_LINE> <DEDENT> <DEDENT> def test_lat_long(self): <NEW_LINE> <INDENT> if self.lat_long is not Undefined: <NEW_LINE> <INDENT> assert_equal(self.MD.LatLong, self.lat_long)
a base class for a set of tests on a file reader
62598fa3ac7a0e7691f72394
class InitProfile(ExtendedApiResource): <NEW_LINE> <INDENT> @deck.apimethod <NEW_LINE> def post(self): <NEW_LINE> <INDENT> j = self.get_input() <NEW_LINE> key = 'userid' <NEW_LINE> if key not in j: <NEW_LINE> <INDENT> return self.response( "No user identifier specified to init the profile", fail=True, code=hcodes.HTTP_DEFAULT_SERVICE_FAIL) <NEW_LINE> <DEDENT> key1 = 'name' <NEW_LINE> key2 = 'surname' <NEW_LINE> if key1 not in j or key2 not in j: <NEW_LINE> <INDENT> return self.response( "No profile info: name and/or surname", fail=True, code=hcodes.HTTP_DEFAULT_SERVICE_FAIL) <NEW_LINE> <DEDENT> user = User.query.get(int(j[key])) <NEW_LINE> if user is None: <NEW_LINE> <INDENT> return self.response( "Invalid account", fail=True, code=hcodes.HTTP_DEFAULT_SERVICE_FAIL) <NEW_LINE> <DEDENT> user.first_name = j[key1] <NEW_LINE> user.last_name = j[key2] <NEW_LINE> user.active = False <NEW_LINE> user.confirmed_at = None <NEW_LINE> role = Role.query.filter_by(name=config.ROLE_USER).first() <NEW_LINE> user.roles.append(role) <NEW_LINE> db.session.add(user) <NEW_LINE> db.session.commit() <NEW_LINE> return self.response({'message': 'Profiling activated'})
Token authentication test
62598fa3627d3e7fe0e06d35
class FramerState(Singleton): <NEW_LINE> <INDENT> Initializing = 1 <NEW_LINE> ReadingHeader = 2 <NEW_LINE> ReadingContent = 3 <NEW_LINE> CompleteFrame = 4 <NEW_LINE> ErrorInFrame = 5
Represents the state machine of a modbus framer .. attribute:: Initializing This indicates that the framer is waiting for a new message to process. .. attribute:: ReadingHeader This indicates that the framer is currently reading the fixed size header of the current frame. .. attribute:: ReadingContent This indicates that the framer is currently reading the content as specified by the header. .. attribute:: CompleteFrame This indicates that the framer has finished reading a frame and is ready to pass it off to the application. .. attribute:: ErrorInFrame This indicates that there is an error in the current frame and that it should be discarded.
62598fa37d847024c075c24f
class lazy_property: <NEW_LINE> <INDENT> def __init__(self, deferred): <NEW_LINE> <INDENT> self._deferred = deferred <NEW_LINE> self.__doc__ = deferred.__doc__ <NEW_LINE> <DEDENT> def __get__(self, obj, cls): <NEW_LINE> <INDENT> if obj is None: <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> value = self._deferred(obj) <NEW_LINE> setattr(obj, self._deferred.__name__, value) <NEW_LINE> return value
A @property that is only evaluated once.
62598fa3adb09d7d5dc0a414
class BeatTrackExtractor(LibrosaFeatureExtractor): <NEW_LINE> <INDENT> _feature = 'beat_track'
Dynamic programming beat tracker (beat_track) from audio using the Librosa library. For details on argument specification visit: https://librosa.org/doc/latest/generated/librosa.beat.beat_track.html.
62598fa3fff4ab517ebcd66e
class LinksSpider(scrapy.Spider): <NEW_LINE> <INDENT> name = "od_links" <NEW_LINE> black_list = ( "?C=N;O=D", "?C=M;O=A", "?C=S;O=A", "?C=D;O=A", ) <NEW_LINE> saved_links = set() <NEW_LINE> def __index__(self, **kw): <NEW_LINE> <INDENT> super(LinksSpider, self).__init__(**kw) <NEW_LINE> self.base_url = kw.get("base_url") <NEW_LINE> <DEDENT> def should_save(self, link): <NEW_LINE> <INDENT> return link not in self.saved_links and not link.rsplit("?", maxsplit=1)[0].endswith("/") <NEW_LINE> <DEDENT> def should_crawl(self, link): <NEW_LINE> <INDENT> if link.endswith(tuple(self.black_list)): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if not link.startswith(self.base_url): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return link.rsplit("?", maxsplit=1)[0].endswith("/") <NEW_LINE> <DEDENT> def start_requests(self): <NEW_LINE> <INDENT> yield scrapy.Request(url=self.base_url, callback=self.parse) <NEW_LINE> <DEDENT> def parse(self, response): <NEW_LINE> <INDENT> links = response.xpath('//a/@href').extract() <NEW_LINE> for link in links: <NEW_LINE> <INDENT> full_link = response.urljoin(link) <NEW_LINE> if self.should_save(full_link): <NEW_LINE> <INDENT> self.saved_links.add(full_link) <NEW_LINE> yield { "link": full_link } <NEW_LINE> <DEDENT> if self.should_crawl(full_link): <NEW_LINE> <INDENT> yield response.follow(full_link, callback=self.parse)
Scrapy spider for open directories. Will gather all download links recursively
62598fa3442bda511e95c2e5
class hashtag(models.Model): <NEW_LINE> <INDENT> blogId = models.ForeignKey(userpost) <NEW_LINE> hashtags = models.ManyToManyField(hashs) <NEW_LINE> @property <NEW_LINE> def hashlist(self): <NEW_LINE> <INDENT> return list(self.hashtags.all())
docstring for hashtags
62598fa3009cb60464d013af
class RegistrationView(utils.SendEmailViewMixin, generics.CreateAPIView): <NEW_LINE> <INDENT> serializer_class = serializers.UserRegistrationSerializer <NEW_LINE> permission_classes = ( permissions.AllowAny, ) <NEW_LINE> token_generator = default_token_generator <NEW_LINE> subject_template_name = 'activation_email_subject.txt' <NEW_LINE> plain_body_template_name = 'activation_email_body.txt' <NEW_LINE> def create(self, request, *args, **kwargs): <NEW_LINE> <INDENT> serializer = self.get_serializer(data=request.data) <NEW_LINE> serializer.is_valid(raise_exception=True) <NEW_LINE> if self.perform_create(serializer): <NEW_LINE> <INDENT> headers = self.get_success_headers(serializer.data) <NEW_LINE> return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Response('Missing arguments for UserProfile', status=status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> <DEDENT> def perform_create(self, serializer): <NEW_LINE> <INDENT> key_set = set([x for x in self.request.data.keys()]) <NEW_LINE> if not {'displayName', 'isCoach', 'city'}.issubset(key_set): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> profile_data = {} <NEW_LINE> for k in key_set: <NEW_LINE> <INDENT> if k in {'displayName', 'isCoach', 'city', 'birthdate', 'description'}: <NEW_LINE> <INDENT> profile_data[k] = self.request.data[k] <NEW_LINE> <DEDENT> <DEDENT> print(profile_data) <NEW_LINE> u = serializer.save() <NEW_LINE> up = UserProfile.objects.create(user=u, **profile_data) <NEW_LINE> try: <NEW_LINE> <INDENT> levels = self.request.data['levels'] <NEW_LINE> up.levels = levels <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> up.user = u <NEW_LINE> up.save() <NEW_LINE> return True <NEW_LINE> <DEDENT> def get_email_context(self, user): <NEW_LINE> <INDENT> context = super(RegistrationView, self).get_email_context(user) <NEW_LINE> context['url'] = settings.get('ACTIVATION_URL').format(**context) <NEW_LINE> return context
Use this endpoint to register new user.
62598fa30c0af96317c5620b
class RoRStatUpgrade(StatUpgrade): <NEW_LINE> <INDENT> def is_unique(self) -> bool: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return f"RoRStatUpgrade<{self.get_id()}>"
Upgrades attributes of units/buildings or other stats in the game.
62598fa3851cf427c66b8152
class ZetaSaver(object): <NEW_LINE> <INDENT> def __init__(self, output_filename): <NEW_LINE> <INDENT> self.output_filename = output_filename <NEW_LINE> <DEDENT> def __call__(self, inverse_solver, count, data): <NEW_LINE> <INDENT> zeta = data.zeta <NEW_LINE> zeta.metadata().set_name('zeta_inv') <NEW_LINE> zeta.metadata().set_string('long_name', 'last iteration of parameterized basal yeild stress computed by inversion') <NEW_LINE> zeta.write(self.output_filename)
Iteration listener used to save a copy of the current value of :math:`\zeta` (i.e. a parameterized design variable such as :math:`\tau_c` or hardness) at each iteration during an inversion. The intent is to use a saved value to restart an inversion if need be.
62598fa301c39578d7f12c09
class OntologyConfigSchema(Schema): <NEW_LINE> <INDENT> id = fields.Str(description="local identifier") <NEW_LINE> handle = fields.Str(description="ontology handle") <NEW_LINE> pre_load = fields.Bool(description="if true, load this ontology at startup") <NEW_LINE> @post_load <NEW_LINE> def make_object(self, data, **kwargs): <NEW_LINE> <INDENT> return OntologyConfig(**data)
Set of ontologies
62598fa3e1aae11d1e7ce768
class ASAxesPlotBuilderNoTitle(ASAxesPlotBuilder): <NEW_LINE> <INDENT> def _get_axes_rect(self): <NEW_LINE> <INDENT> return [0.08, 0.15, 0.85, 0.8] <NEW_LINE> <DEDENT> def _get_title_kwargs(self): <NEW_LINE> <INDENT> kw = super()._get_title_kwargs() <NEW_LINE> kw.update({"visible": False}) <NEW_LINE> return kw
AS Axes plot without the tile string, this leaves more space for the plot
62598fa324f1403a926857f8
class MetaToPair(gr.sync_block): <NEW_LINE> <INDENT> def __init__(self, incomingKeyName, outgoingPairName): <NEW_LINE> <INDENT> gr.sync_block.__init__(self, name="MetaToPair", in_sig=None, out_sig=None) <NEW_LINE> self.incomingKeyName = str(incomingKeyName) <NEW_LINE> self.outgoingPairName = str(outgoingPairName) <NEW_LINE> self.message_port_register_in(pmt.intern("inmeta")) <NEW_LINE> self.set_msg_handler(pmt.intern("inmeta"), self.msg_handler) <NEW_LINE> self.message_port_register_out(pmt.intern("outpair")) <NEW_LINE> <DEDENT> def msg_handler(self, msg): <NEW_LINE> <INDENT> if not pmt.is_pair(msg): <NEW_LINE> <INDENT> gr.log.warn("Incoming message is not a pair. Only pairs are supported. " "No message generated.") <NEW_LINE> return <NEW_LINE> <DEDENT> meta = pmt.to_python(pmt.car(msg)) <NEW_LINE> if not type(meta) is dict: <NEW_LINE> <INDENT> gr.log.warn("Incoming message does not contain a dictionary. " "No message generated.") <NEW_LINE> return <NEW_LINE> <DEDENT> if not self.incomingKeyName in meta: <NEW_LINE> <INDENT> gr.log.warn("Incoming message dictionary does not contain key %s. " "No message generated." % self.incomingKeyName) <NEW_LINE> return <NEW_LINE> <DEDENT> incomingVal = meta[self.incomingKeyName] <NEW_LINE> new_pair = None <NEW_LINE> try: <NEW_LINE> <INDENT> new_pair = pmt.cons(pmt.intern(self.outgoingPairName), pmt.to_pmt(incomingVal)) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> gr.log.error("Cannot construct new message: %s" % str(e)) <NEW_LINE> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.message_port_pub(pmt.intern("outpair"), new_pair) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> gr.log.error("Cannot send message: %s" % str(e)) <NEW_LINE> gr.log.error("Incoming dictionary (%s):" % str(type(meta))) <NEW_LINE> gr.log.error(str(meta)) <NEW_LINE> <DEDENT> <DEDENT> def stop(self): <NEW_LINE> <INDENT> return True
This block converts a metadata dictionary item to a pmt pair that is compatible with other blocks expecting a pair in. You can specify which item in the incoming metadata to output as a pair and what the pair name is.
62598fa399cbb53fe6830d5e
class CreateObjects(MethodCall): <NEW_LINE> <INDENT> def __init__(self, **kw): <NEW_LINE> <INDENT> objs = [] <NEW_LINE> for path, interfaces in kw.pop('objs').iteritems(): <NEW_LINE> <INDENT> key_o = TrivialArgument( value=path, type='string', decorators=[Literal('string')]) <NEW_LINE> value_i = [] <NEW_LINE> for interface, properties, in interfaces.iteritems(): <NEW_LINE> <INDENT> key_i = TrivialArgument(value=interface, type='string') <NEW_LINE> value_p = [] <NEW_LINE> if properties: <NEW_LINE> <INDENT> for prop, value in properties.iteritems(): <NEW_LINE> <INDENT> key_p = TrivialArgument(value=prop, type='string') <NEW_LINE> value_v = TrivialArgument( decorators=[Literal(value.get('type', None))], **value) <NEW_LINE> value_p.append(InitializerList(values=[key_p, value_v])) <NEW_LINE> <DEDENT> <DEDENT> value_p = InitializerList(values=value_p) <NEW_LINE> value_i.append(InitializerList(values=[key_i, value_p])) <NEW_LINE> <DEDENT> value_i = InitializerList(values=value_i) <NEW_LINE> objs.append(InitializerList(values=[key_o, value_i])) <NEW_LINE> <DEDENT> kw['args'] = [InitializerList(values=objs)] <NEW_LINE> kw['namespace'] = ['functor'] <NEW_LINE> super(CreateObjects, self).__init__(**kw)
Assemble a createObjects functor.
62598fa35166f23b2e243262
class ListPolicy(lister.Lister): <NEW_LINE> <INDENT> log = logging.getLogger(__name__ + '.ListPolicy') <NEW_LINE> def get_parser(self, prog_name): <NEW_LINE> <INDENT> parser = super(ListPolicy, self).get_parser(prog_name) <NEW_LINE> parser.add_argument( '--include-blob', action='store_true', default=False, help='Additional fields are listed in output', ) <NEW_LINE> return parser <NEW_LINE> <DEDENT> def take_action(self, parsed_args): <NEW_LINE> <INDENT> self.log.debug('take_action(%s)' % parsed_args) <NEW_LINE> if parsed_args.include_blob: <NEW_LINE> <INDENT> columns = ('ID', 'Type', 'Blob') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> columns = ('ID', 'Type') <NEW_LINE> <DEDENT> data = self.app.client_manager.identity.policies.list() <NEW_LINE> return (columns, (utils.get_item_properties( s, columns, formatters={}, ) for s in data))
List policy command
62598fa366673b3332c30252
class CasePuits(Case): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> Case.__init__(self, "le puits", "O", "|rg|", "dans", "tombez", "tombe", " !") <NEW_LINE> <DEDENT> def __getnewargs__(self): <NEW_LINE> <INDENT> return () <NEW_LINE> <DEDENT> def arrive(self, jeu, plateau, partie, personnage, coup): <NEW_LINE> <INDENT> Case.arrive(self, jeu, plateau, partie, personnage, coup) <NEW_LINE> if jeu.puits: <NEW_LINE> <INDENT> autre = jeu.puits <NEW_LINE> autre << "Vous pouvez sortir du puits !" <NEW_LINE> a_pion = jeu.pions[autre] <NEW_LINE> partie.envoyer("Le pion {} sort du puits.".format(a_pion.couleur), autre) <NEW_LINE> <DEDENT> pion = jeu.pions[personnage] <NEW_LINE> personnage << "Vous devez attendre que quelqu'un vous délivre." <NEW_LINE> jeu.puits = personnage
Classe représentant le puits.
62598fa34f6381625f199402
class Point(O): <NEW_LINE> <INDENT> def __init__(self, decisions): <NEW_LINE> <INDENT> O.__init__(self) <NEW_LINE> self.decisions = decisions <NEW_LINE> self.objectives = [] <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash(tuple(self.decisions)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.decisions == other.decisions <NEW_LINE> <DEDENT> def clone(self): <NEW_LINE> <INDENT> new = Point(self.decisions[:]) <NEW_LINE> new.objectives = self.objectives[:] <NEW_LINE> return new
Represents a member of the population
62598fa3dd821e528d6d8dbf
class Agenda(models.Model): <NEW_LINE> <INDENT> patient = models.ForeignKey(Patient, on_delete=models.CASCADE, related_name = 'agenda_patient') <NEW_LINE> clinicien = models.ForeignKey(Clinicien, on_delete=models.CASCADE, related_name = 'agenda_clini') <NEW_LINE> objet = models.CharField(max_length=250) <NEW_LINE> debut = models.DateTimeField(default=timezone.now) <NEW_LINE> duree = models.DurationField(null=True) <NEW_LINE> class Meta : <NEW_LINE> <INDENT> ordering =["patient","debut"] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "rdv de {0} avec {1} pour {2} ".format(self.patient.user.first_name,self.clinicien.user.last_name,self.objet)
Utilisation d'un graphe pour créneau agenda
62598fa37047854f4633f262
class BaseView(object): <NEW_LINE> <INDENT> def __call__(self, request, *args, **kwargs): <NEW_LINE> <INDENT> method = request.method.lower() <NEW_LINE> if hasattr(self, method): <NEW_LINE> <INDENT> return getattr(self, method)(request, *args, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Http404('Not supported HTTP method.') <NEW_LINE> <DEDENT> <DEDENT> def error(self, status): <NEW_LINE> <INDENT> raise Http404('Not found')
A base class for views that delegates handling to GET, POST methods based on reques method. An instance of this class must be created to be used in the url patterns.
62598fa34f88993c371f044f
class IVImageFilterType(): <NEW_LINE> <INDENT> ImageFilter_Gaussion3 = 0 <NEW_LINE> ImageFilter_Gaussion5 = 1 <NEW_LINE> ImageFilter_Gaussion = 2 <NEW_LINE> ImageFilter_Median = 3 <NEW_LINE> ImageFilter_Sharpen = 4 <NEW_LINE> ImageFilter_SobelX = 5, <NEW_LINE> ImageFilter_SobelY = 6 <NEW_LINE> ImageFilter_SobelA = 7 <NEW_LINE> ImageFilter_Blur = 8 <NEW_LINE> ImageFilter_Edge = 9 <NEW_LINE> ImageFilter_Contour = 10 <NEW_LINE> ImageFilter_UnsharpMask = 11 <NEW_LINE> ImageFilter_Linear = 12
Image filter type
62598fa321bff66bcd722af0
class MembershipType(models.Model): <NEW_LINE> <INDENT> name = models.CharField( max_length=200, ) <NEW_LINE> description = models.TextField( blank=True, null=True, ) <NEW_LINE> def publish(self): <NEW_LINE> <INDENT> self.save() <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.name
MembershipType data model.
62598fa330dc7b766599f6d8
class OperatingPoint(object): <NEW_LINE> <INDENT> def __init__(self, omega, rms_motor_power, rms_output_power, rms_input_power, average_motor_power, torque): <NEW_LINE> <INDENT> self._omega = omega <NEW_LINE> self._rms_motor_power = rms_motor_power <NEW_LINE> self._rms_output_power = rms_output_power <NEW_LINE> self._rms_input_power = rms_input_power <NEW_LINE> self._average_motor_power = average_motor_power <NEW_LINE> self._torque = torque <NEW_LINE> <DEDENT> @property <NEW_LINE> def omega(self): <NEW_LINE> <INDENT> return self._omega <NEW_LINE> <DEDENT> @property <NEW_LINE> def rms_input_power(self): <NEW_LINE> <INDENT> return self._rms_input_power <NEW_LINE> <DEDENT> @property <NEW_LINE> def average_input_power(self): <NEW_LINE> <INDENT> return self.average_motor_power + self.average_output_power <NEW_LINE> <DEDENT> @property <NEW_LINE> def torque(self): <NEW_LINE> <INDENT> return self._torque <NEW_LINE> <DEDENT> @property <NEW_LINE> def rms_motor_power(self): <NEW_LINE> <INDENT> return self._rms_motor_power <NEW_LINE> <DEDENT> @property <NEW_LINE> def rms_output_power(self): <NEW_LINE> <INDENT> return self._rms_output_power <NEW_LINE> <DEDENT> @property <NEW_LINE> def average_motor_power(self): <NEW_LINE> <INDENT> return self._average_motor_power <NEW_LINE> <DEDENT> def rms_input_current(self, input_voltage): <NEW_LINE> <INDENT> return self.rms_input_power / input_voltage <NEW_LINE> <DEDENT> @property <NEW_LINE> def average_output_power(self): <NEW_LINE> <INDENT> return self.omega * self.torque <NEW_LINE> <DEDENT> @property <NEW_LINE> def efficiency(self): <NEW_LINE> <INDENT> return self.average_output_power / (self.rms_input_power + self.average_output_power)
Represents one operating point of a motor. This is intended to include all of the useful output metrics for an operating point (speed, torque, etc) of a motor. Attributes ---------- omega : float The speed of the motor in rad/s. rms_motor_power : float The RMS power dissipated in the motor in W. rms_output_power : float The RMS output power in W. rms_input_power: float The RMS input power in W. average_motor_power : float The average power dissipated in the motor in W. torque : float The average torque (for all phases) in N*m.
62598fa3a17c0f6771d5c0c4
class SnippetSourceDirective(SphinxDirective): <NEW_LINE> <INDENT> required_arguments = 1 <NEW_LINE> optional_arguments = 1 <NEW_LINE> has_content = True <NEW_LINE> option_spec = { 'emphasize-lines': directives.unchanged_required, 'caption': directives.unchanged_required, 'commercial': directives.flag, } <NEW_LINE> def run(self): <NEW_LINE> <INDENT> document = self.state.document <NEW_LINE> source_file = self.arguments[0] <NEW_LINE> code = u'\n'.join(self.content) <NEW_LINE> emphasized_lines = self.options.get('emphasize-lines') <NEW_LINE> if emphasized_lines: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> nlines = len(self.content) <NEW_LINE> hl_lines = parselinenos(emphasized_lines, nlines) <NEW_LINE> if any(i >= nlines for i in hl_lines): <NEW_LINE> <INDENT> raise RuntimeError('line number spec out of range 1-%d: %r' % ( (nlines, self.options['emphasize-lines']))) <NEW_LINE> <DEDENT> hl_lines = [i + 1 for i in hl_lines] <NEW_LINE> <DEDENT> except ValueError as err: <NEW_LINE> <INDENT> return [document.reporter.warning(err, line=self.lineno)] <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> hl_lines = None <NEW_LINE> <DEDENT> node = SnippetSourceNode(source_file, self.lineno, code, code) <NEW_LINE> if hl_lines is not None: <NEW_LINE> <INDENT> node['highlight_args'] = { 'hl_lines': hl_lines } <NEW_LINE> <DEDENT> node['commercial'] = ('commercial' in self.options) <NEW_LINE> caption = self.options.get('caption') <NEW_LINE> if caption: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> node = container_wrapper(self, node, caption) <NEW_LINE> <DEDENT> except ValueError as exc: <NEW_LINE> <INDENT> return [document.reporter.warning(exc, line=self.lineno)] <NEW_LINE> <DEDENT> <DEDENT> self.add_name(node) <NEW_LINE> return [node]
.. snippet-source:: filepath_relative_to_project_root [code]
62598fa3baa26c4b54d4f13b
class Grade(Base): <NEW_LINE> <INDENT> __tablename__ = 'grades' <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> name = Column(String(32),nullable=False) <NEW_LINE> student = relationship('Student', secondary=grade_m2m_student, backref='grades') <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return "课程名称:%s" %self.name
课程表,id,课程名,对grade_m2m_student,grade_record表进行关联,一个课程对应多个学生,一个学生也可以对应多个课程
62598fa33539df3088ecc13f
class ActiveEnrichmentSessionResponse(object): <NEW_LINE> <INDENT> swagger_types = { 'payload': 'ActiveEnrichmentSession' } <NEW_LINE> attribute_map = { 'payload': 'payload' } <NEW_LINE> def __init__(self, payload=None): <NEW_LINE> <INDENT> self._payload = None <NEW_LINE> self.discriminator = None <NEW_LINE> if payload is not None: <NEW_LINE> <INDENT> self.payload = payload <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def payload(self): <NEW_LINE> <INDENT> return self._payload <NEW_LINE> <DEDENT> @payload.setter <NEW_LINE> def payload(self, payload): <NEW_LINE> <INDENT> self._payload = payload <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> if issubclass(ActiveEnrichmentSessionResponse, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, ActiveEnrichmentSessionResponse): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
62598fa3d58c6744b42dc219
class Cert_TrustPointSetInfoIDL_args(object): <NEW_LINE> <INDENT> thrift_spec = (None, (1, TType.STRING, 'TrustPointName', None, None), (2, TType.I32, 'action', None, None), (3, TType.STRUCT, 'SetInfo', (CertTrustpointInfoInIDL, CertTrustpointInfoInIDL.thrift_spec), None)) <NEW_LINE> def __init__(self, TrustPointName = None, action = None, SetInfo = None): <NEW_LINE> <INDENT> self.TrustPointName = TrustPointName <NEW_LINE> self.action = action <NEW_LINE> self.SetInfo = SetInfo <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.STRING: <NEW_LINE> <INDENT> self.TrustPointName = iprot.readString() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 2: <NEW_LINE> <INDENT> if ftype == TType.I32: <NEW_LINE> <INDENT> self.action = iprot.readI32() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 3: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.SetInfo = CertTrustpointInfoInIDL() <NEW_LINE> self.SetInfo.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('Cert_TrustPointSetInfoIDL_args') <NEW_LINE> if self.TrustPointName != None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('TrustPointName', TType.STRING, 1) <NEW_LINE> oprot.writeString(self.TrustPointName) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.action != None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('action', TType.I32, 2) <NEW_LINE> oprot.writeI32(self.action) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.SetInfo != None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('SetInfo', TType.STRUCT, 3) <NEW_LINE> self.SetInfo.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> def validate(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <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: - TrustPointName - action - SetInfo
62598fa31f5feb6acb162aad
class Handler(handler.handler): <NEW_LINE> <INDENT> def dispatch(self, session): <NEW_LINE> <INDENT> req_body = self.context.request.body <NEW_LINE> resp_body = self.context.response.body <NEW_LINE> user_id = req_body.userid <NEW_LINE> if not user_id: <NEW_LINE> <INDENT> raise Error(-1, '用户id参数缺失') <NEW_LINE> <DEDENT> to_pay = session.query(WechatshopOrder).filter(WechatshopOrder.user_id == user_id).filter(WechatshopOrder.is_delete == 0).filter(WechatshopOrder.order_type < 7).filter(WechatshopOrder.order_status.in_(['101', '801'])).count() <NEW_LINE> to_delivery = session.query(WechatshopOrder).filter(WechatshopOrder.user_id == user_id).filter(WechatshopOrder.is_delete == 0).filter(WechatshopOrder.order_type < 7).filter(WechatshopOrder.order_status == 300).count() <NEW_LINE> to_receive = session.query(WechatshopOrder).filter(WechatshopOrder.user_id == user_id).filter(WechatshopOrder.order_type < 7).filter(WechatshopOrder.is_delete == 0).filter(WechatshopOrder.order_status == 301).count() <NEW_LINE> resp_body.data = dict( toPay=to_pay, toDelivery=to_delivery, toReceive=to_receive )
我的订单数目
62598fa3dd821e528d6d8dc0
class ManagedClusterPoolUpgradeProfile(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'kubernetes_version': {'required': True}, 'os_type': {'required': True}, } <NEW_LINE> _attribute_map = { 'kubernetes_version': {'key': 'kubernetesVersion', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'os_type': {'key': 'osType', 'type': 'str'}, 'upgrades': {'key': 'upgrades', 'type': '[ManagedClusterPoolUpgradeProfileUpgradesItem]'}, } <NEW_LINE> def __init__( self, *, kubernetes_version: str, os_type: Union[str, "OSType"] = "Linux", name: Optional[str] = None, upgrades: Optional[List["ManagedClusterPoolUpgradeProfileUpgradesItem"]] = None, **kwargs ): <NEW_LINE> <INDENT> super(ManagedClusterPoolUpgradeProfile, self).__init__(**kwargs) <NEW_LINE> self.kubernetes_version = kubernetes_version <NEW_LINE> self.name = name <NEW_LINE> self.os_type = os_type <NEW_LINE> self.upgrades = upgrades
The list of available upgrade versions. All required parameters must be populated in order to send to Azure. :ivar kubernetes_version: Required. Kubernetes version (major, minor, patch). :vartype kubernetes_version: str :ivar name: Pool name. :vartype name: str :ivar os_type: Required. OsType to be used to specify os type. Choose from Linux and Windows. Default to Linux. Possible values include: "Linux", "Windows". Default value: "Linux". :vartype os_type: str or ~azure.mgmt.containerservice.v2020_01_01.models.OSType :ivar upgrades: List of orchestrator types and versions available for upgrade. :vartype upgrades: list[~azure.mgmt.containerservice.v2020_01_01.models.ManagedClusterPoolUpgradeProfileUpgradesItem]
62598fa3627d3e7fe0e06d37
class SortedListNode(object): <NEW_LINE> <INDENT> IS_GREATER = True <NEW_LINE> def __init__(self, index, value): <NEW_LINE> <INDENT> super(SortedListNode, self).__init__() <NEW_LINE> self.index = index <NEW_LINE> self.value = value <NEW_LINE> self._is_delete = False <NEW_LINE> return None <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return ("(%d, %f)" % (self.index, self.value)) <NEW_LINE> <DEDENT> def __gt__(self, other): <NEW_LINE> <INDENT> return (not self.__le__(other)) <NEW_LINE> <DEDENT> def __lt__(self, other): <NEW_LINE> <INDENT> return (not self.__ge__(other)) <NEW_LINE> <DEDENT> def __ge__(self, other): <NEW_LINE> <INDENT> if (self.__eq__(other)): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if (Math.is_equal(self.value, other.value)): <NEW_LINE> <INDENT> return (self.index > other.index) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return (self.value > other.value) <NEW_LINE> <DEDENT> <DEDENT> return None <NEW_LINE> <DEDENT> def __le__(self, other): <NEW_LINE> <INDENT> if (self.__eq__(other)): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if (Math.is_equal(self.value, other.value)): <NEW_LINE> <INDENT> return (self.index < other.index) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return (self.value < other.value) <NEW_LINE> <DEDENT> <DEDENT> return None <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return (self.index == other.index) <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return (not self.__eq__(other)) <NEW_LINE> <DEDENT> def delete(self): <NEW_LINE> <INDENT> self._is_delete = True <NEW_LINE> return None
Documentation for SortedListNode
62598fa367a9b606de545e56
class RMVDepartureSensor(SensorEntity): <NEW_LINE> <INDENT> def __init__( self, station, destinations, direction, lines, products, time_offset, max_journeys, name, timeout, ): <NEW_LINE> <INDENT> self._station = station <NEW_LINE> self._name = name <NEW_LINE> self._state = None <NEW_LINE> self.data = RMVDepartureData( station, destinations, direction, lines, products, time_offset, max_journeys, timeout, ) <NEW_LINE> self._icon = ICONS[None] <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @property <NEW_LINE> def available(self): <NEW_LINE> <INDENT> return self._state is not None <NEW_LINE> <DEDENT> @property <NEW_LINE> def state(self): <NEW_LINE> <INDENT> return self._state <NEW_LINE> <DEDENT> @property <NEW_LINE> def extra_state_attributes(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return { "next_departures": self.data.departures[1:], "direction": self.data.departures[0].get("direction"), "line": self.data.departures[0].get("line"), "minutes": self.data.departures[0].get("minutes"), "departure_time": self.data.departures[0].get("departure_time"), "product": self.data.departures[0].get("product"), ATTR_ATTRIBUTION: ATTRIBUTION, } <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def icon(self): <NEW_LINE> <INDENT> return self._icon <NEW_LINE> <DEDENT> @property <NEW_LINE> def unit_of_measurement(self): <NEW_LINE> <INDENT> return TIME_MINUTES <NEW_LINE> <DEDENT> async def async_update(self): <NEW_LINE> <INDENT> await self.data.async_update() <NEW_LINE> if self._name == DEFAULT_NAME: <NEW_LINE> <INDENT> self._name = self.data.station <NEW_LINE> <DEDENT> self._station = self.data.station <NEW_LINE> if not self.data.departures: <NEW_LINE> <INDENT> self._state = None <NEW_LINE> self._icon = ICONS[None] <NEW_LINE> return <NEW_LINE> <DEDENT> self._state = self.data.departures[0].get("minutes") <NEW_LINE> self._icon = ICONS[self.data.departures[0].get("product")]
Implementation of an RMV departure sensor.
62598fa34527f215b58e9d6e
class DateTimeField(Field): <NEW_LINE> <INDENT> def clean_param_value(self, value): <NEW_LINE> <INDENT> value = super(DateTimeField, self).clean_param_value(value) <NEW_LINE> return self._parse_datetime_string(value) <NEW_LINE> <DEDENT> def clean_result_value(self, value): <NEW_LINE> <INDENT> value = super(DateTimeField, self).clean_result_value(value) <NEW_LINE> if isinstance(value, datetime.datetime): <NEW_LINE> <INDENT> return datetime_utc_normalize(value) <NEW_LINE> <DEDENT> if isinstance(value, basestring): <NEW_LINE> <INDENT> return self._parse_datetime_string(value) <NEW_LINE> <DEDENT> raise TypeError( '{!r} is neither a str/unicode nor a ' 'datetime.datetime object'.format(value)) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _parse_datetime_string(value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return parse_iso_datetime_to_utc(value) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> raise FieldValueError(public_message=( u'"{}" is not a valid date + ' u'time specification'.format(ascii_str(value))))
For date-and-time (timestamp) values, automatically normalized to UTC.
62598fa363d6d428bbee263d
class AbstractNotifier(threading.Thread): <NEW_LINE> <INDENT> __metaclass__ = ABCMeta <NEW_LINE> def __init__(self, config, logger, msg_queue): <NEW_LINE> <INDENT> super(AbstractNotifier, self).__init__() <NEW_LINE> self._config = config <NEW_LINE> self._msg_queue = msg_queue <NEW_LINE> self._logger = logger <NEW_LINE> <DEDENT> def _read_my_queue(self): <NEW_LINE> <INDENT> msg = None <NEW_LINE> try: <NEW_LINE> <INDENT> msg = self._msg_queue.get() <NEW_LINE> <DEDENT> except Exception as exception: <NEW_LINE> <INDENT> self._logger.exception(exception) <NEW_LINE> <DEDENT> return msg <NEW_LINE> <DEDENT> def _is_my_queue_empty(self): <NEW_LINE> <INDENT> q = self._msg_queue <NEW_LINE> return q.empty() <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def run(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def get_name(self): <NEW_LINE> <INDENT> return self.name
Serves as a base class for all plugins
62598fa3a8370b77170f0265
class User(db.Model): <NEW_LINE> <INDENT> id = db.Column(db.Integer, nullable=False, autoincrement=True, primary_key=True) <NEW_LINE> email = db.Column(db.String, nullable=False, unique=True) <NEW_LINE> phone = db.Column(db.String, unique=True) <NEW_LINE> name = db.Column(db.String, nullable=False) <NEW_LINE> hashed_password = db.Column(db.String, nullable=False) <NEW_LINE> @property <NEW_LINE> def password(self): <NEW_LINE> <INDENT> raise AttributeError('password is not a readable attribute') <NEW_LINE> <DEDENT> @password.setter <NEW_LINE> def password(self, password): <NEW_LINE> <INDENT> self.hashed_password = generate_password_hash(password) <NEW_LINE> <DEDENT> register_date = db.Column(db.DateTime, default=datetime.utcnow()) <NEW_LINE> token = db.relationship('Token', backref='user', lazy='dynamic') <NEW_LINE> books = db.relationship('UserBook', backref='belong_to', lazy='dynamic') <NEW_LINE> def verify_password(self, password): <NEW_LINE> <INDENT> return check_password_hash(self.hashed_password, password) <NEW_LINE> <DEDENT> def __init__(self, email, phone, name): <NEW_LINE> <INDENT> self.email = email <NEW_LINE> self.phone = phone <NEW_LINE> self.name = name <NEW_LINE> <DEDENT> def toJSON(self): <NEW_LINE> <INDENT> return { 'id': self.id, 'email': self.email, 'phone': self.phone, 'name': self.name, 'register_date': self.register_date.strftime(DATETIME_FORMAT), } <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<User {} - {} - {} @ {}>'.format(self.email, self.phone, self.name, self.register_date)
model of user
62598fa3a8ecb0332587109a
class Meta(object): <NEW_LINE> <INDENT> model = DashboardSettings <NEW_LINE> fields = ('user', 'layout_uid', 'title', 'is_public')
Meta.
62598fa38da39b475be0306c
class UserTicketSubscription(TicketSubscription): <NEW_LINE> <INDENT> __mapper_args__ = { 'polymorphic_identity': TicketSubscriptionType.user } <NEW_LINE> def get_addresses(self): <NEW_LINE> <INDENT> if not self.user: <NEW_LINE> <INDENT> raise StopIteration <NEW_LINE> <DEDENT> for addr in self.user.email_addresses: <NEW_LINE> <INDENT> yield addr.address <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def template_vars(self): <NEW_LINE> <INDENT> if self.user: <NEW_LINE> <INDENT> return {'recipient_type': 'user', 'user': self.user} <NEW_LINE> <DEDENT> return {}
Describes one link between a ticket and a user.
62598fa37d847024c075c252
class CNN: <NEW_LINE> <INDENT> def __init__(self, train_x, train_y, test_x, test_y, epochs = 15, batch_size=128, ): <NEW_LINE> <INDENT> self.batch_size = batch_size <NEW_LINE> self.epochs = epochs <NEW_LINE> print (len(train_x)) <NEW_LINE> print (len([elem for elem in train_x])) <NEW_LINE> self.train_y = np.array(train_y) <NEW_LINE> self.test_y = np.array(test_y) <NEW_LINE> img_x, img_y = 28, 28 <NEW_LINE> input_shape = (img_x, img_y, 1) <NEW_LINE> self.train_x = train_x.reshape(train_x.shape[0], img_x, img_y, 1) <NEW_LINE> self.test_x = test_x.reshape(test_x.shape[0], img_x, img_y, 1) <NEW_LINE> print (self.train_x.shape, self.test_x.shape, self.train_y.shape, self.test_y.shape) <NEW_LINE> num_classes = len(set(train_y)) <NEW_LINE> one_hot_train_y = [ [0 if elem != idx else 1 for idx in range(num_classes) ] for elem in train_y] <NEW_LINE> one_hot_test_y = [ [0 if elem != idx else 1 for idx in range(num_classes) ] for elem in test_y] <NEW_LINE> self.train_y = one_hot_train_y <NEW_LINE> self.test_y = one_hot_test_y <NEW_LINE> model = Sequential() <NEW_LINE> model.add(Conv2D(32, kernel_size=(5, 5), strides=(1, 1), activation='relu', input_shape=input_shape)) <NEW_LINE> model.add(MaxPool2D(pool_size=(2, 2), strides=(2, 2))) <NEW_LINE> model.add(Dropout(0.5)) <NEW_LINE> model.add(Conv2D(64, (5, 5), activation='relu')) <NEW_LINE> model.add(MaxPool2D(pool_size=(2, 2))) <NEW_LINE> model.add(Dropout(0.5)) <NEW_LINE> model.add(Conv2D(64, (5, 5), activation='relu')) <NEW_LINE> model.add(MaxPool2D(pool_size=(2, 2))) <NEW_LINE> model.add(Dropout(0.5)) <NEW_LINE> model.add(Flatten()) <NEW_LINE> model.add(Dense(1000, activation='relu')) <NEW_LINE> model.add(Dropout(0.5)) <NEW_LINE> model.add(Dense(num_classes, activation='softmax')) <NEW_LINE> model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.SGD(lr=0.01), metrics=['accuracy']) <NEW_LINE> self.model = model <NEW_LINE> <DEDENT> def train(self): <NEW_LINE> <INDENT> self.model.fit(self.train_x, self.train_y, batch_size=self.batch_size, epochs=self.epochs, verbose=1, validation_data=(self.test_x, self.test_y)) <NEW_LINE> <DEDENT> def evaluate(self): <NEW_LINE> <INDENT> acc = self.model.evaluate(self.test_x, self.test_y) <NEW_LINE> return acc
CNN classifier
62598fa3009cb60464d013b1
class Controller(object): <NEW_LINE> <INDENT> def __init__(self, display): <NEW_LINE> <INDENT> self.display = display <NEW_LINE> <DEDENT> def control_quit(self): <NEW_LINE> <INDENT> for event in pygame.event.get(): <NEW_LINE> <INDENT> if event.type == pygame.QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): <NEW_LINE> <INDENT> pygame.quit() <NEW_LINE> sys.exit() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def control_menu(self, m): <NEW_LINE> <INDENT> for event in pygame.event.get(): <NEW_LINE> <INDENT> if event.type == pygame.MOUSEBUTTONDOWN and ((200, 200) < pygame.mouse.get_pos() < (400, 400)): <NEW_LINE> <INDENT> m.destroy(self.display) <NEW_LINE> return 1 <NEW_LINE> <DEDENT> elif event.type == pygame.MOUSEBUTTONDOWN and ((600, 200) < pygame.mouse.get_pos() < (800, 400)): <NEW_LINE> <INDENT> m.destroy(self.display) <NEW_LINE> return 0
This is the event controller - NOT USED AT THE MOMENT
62598fa30c0af96317c5620d
@public <NEW_LINE> class DigestMemberRoster(DeliveryMemberRoster): <NEW_LINE> <INDENT> name = 'digest_members' <NEW_LINE> @property <NEW_LINE> def members(self): <NEW_LINE> <INDENT> yield from self._get_members( DeliveryMode.plaintext_digests, DeliveryMode.mime_digests, DeliveryMode.summary_digests)
Return all the regular delivery members of a list.
62598fa301c39578d7f12c0b
@patch("dakara_player.__main__.exit") <NEW_LINE> @patch.object(ArgumentParser, "parse_args") <NEW_LINE> class MainTestCase(TestCase): <NEW_LINE> <INDENT> def test_normal_exit(self, mocked_parse_args, mocked_exit): <NEW_LINE> <INDENT> function = MagicMock() <NEW_LINE> mocked_parse_args.return_value = Namespace(function=function, debug=False) <NEW_LINE> main() <NEW_LINE> function.assert_called_with(ANY) <NEW_LINE> mocked_exit.assert_called_with(0) <NEW_LINE> <DEDENT> def test_known_error(self, mocked_parse_args, mocked_exit): <NEW_LINE> <INDENT> def function(args): <NEW_LINE> <INDENT> raise DakaraError("error") <NEW_LINE> <DEDENT> mocked_parse_args.return_value = Namespace(function=function, debug=False) <NEW_LINE> with self.assertLogs("dakara_player.__main__", "DEBUG") as logger: <NEW_LINE> <INDENT> main() <NEW_LINE> <DEDENT> mocked_exit.assert_called_with(1) <NEW_LINE> self.assertListEqual(logger.output, ["CRITICAL:dakara_player.__main__:error"]) <NEW_LINE> <DEDENT> def test_known_error_debug(self, mocked_parse_args, mocked_exit): <NEW_LINE> <INDENT> def function(args): <NEW_LINE> <INDENT> raise DakaraError("error message") <NEW_LINE> <DEDENT> mocked_parse_args.return_value = Namespace(function=function, debug=True) <NEW_LINE> with self.assertRaisesRegex(DakaraError, "error message"): <NEW_LINE> <INDENT> main() <NEW_LINE> <DEDENT> mocked_exit.assert_not_called() <NEW_LINE> <DEDENT> def test_unknown_error(self, mocked_parse_args, mocked_exit): <NEW_LINE> <INDENT> def function(args): <NEW_LINE> <INDENT> raise Exception("error") <NEW_LINE> <DEDENT> mocked_parse_args.return_value = Namespace(function=function, debug=False) <NEW_LINE> with self.assertLogs("dakara_player.__main__", "DEBUG") as logger: <NEW_LINE> <INDENT> main() <NEW_LINE> <DEDENT> mocked_exit.assert_called_with(128) <NEW_LINE> self.assertListEqual( logger.output, [ ANY, "CRITICAL:dakara_player.__main__:Please fill a bug report at " "https://github.com/DakaraProject/dakara-player/issues", ], ) <NEW_LINE> <DEDENT> def test_unknown_error_debug(self, mocked_parse_args, mocked_exit): <NEW_LINE> <INDENT> def function(args): <NEW_LINE> <INDENT> raise Exception("error message") <NEW_LINE> <DEDENT> mocked_parse_args.return_value = Namespace(function=function, debug=True) <NEW_LINE> with self.assertRaisesRegex(Exception, "error message"): <NEW_LINE> <INDENT> main() <NEW_LINE> <DEDENT> mocked_exit.assert_not_called()
Test the main action.
62598fa307f4c71912baf2cf
class Bishop(Piece): <NEW_LINE> <INDENT> def __init__(self, player: object, row: int, column: int): <NEW_LINE> <INDENT> super().__init__(player=player, row=row, column=column, name='bishop', evaluation=3) <NEW_LINE> <DEDENT> def legal_moves(self, board: object, pins: list = ()) -> list[object]: <NEW_LINE> <INDENT> unprepared_directions: list[tuple] = [(1, 1), (-1, 1), (-1, -1), (1, -1)] <NEW_LINE> moves: list[object] = [] <NEW_LINE> directions = self.prepare_directions(unprepared_directions, pins) <NEW_LINE> for direction in directions: <NEW_LINE> <INDENT> moves += [i for i in self.iterative_moves(direction, board)] <NEW_LINE> <DEDENT> return moves <NEW_LINE> <DEDENT> def __repr__(self) -> str: <NEW_LINE> <INDENT> return 'B' if self.player.color[0] == 'w' else 'b'
A 'Bishop' moves any distance in all diagonal directions. The bishop always remains on squares of the same color during a game. That is why each player has a white-squared bishop and a black-squared bishop at the beginning. Both together (the bishop pair) can be a particularly great power, as they complement each other well and can dominate the whole board.
62598fa33317a56b869be48f
class DirRecTabularRegressionForecaster(_DirRecReducer): <NEW_LINE> <INDENT> _estimator_scitype = "tabular-regressor"
Dir-rec reduction from forecasting to tabular regression. For the hybrid dir-rec strategy, a separate forecaster is fitted for each step ahead of the forecasting horizon and then the previous forecasting horizon is added as an input for training the next forecaster, following the recusrive strategy. Parameters ---------- estimator : sklearn estimator object Tabular regressor. window_length : int, optional (default=10) The length of the sliding window used to transform the series into a tabular matrix
62598fa32c8b7c6e89bd3652
class CODE_TYPE(object): <NEW_LINE> <INDENT> FLOW = 1 <NEW_LINE> ORDER = 2
编号类型
62598fa391af0d3eaad39c99
class Solution: <NEW_LINE> <INDENT> def uniquePaths(self, m, n): <NEW_LINE> <INDENT> dp = [[0] * n for _ in range(m)] <NEW_LINE> for i in range(m): <NEW_LINE> <INDENT> dp[i][0] = 1 <NEW_LINE> <DEDENT> for j in range(n): <NEW_LINE> <INDENT> dp[0][j] = 1 <NEW_LINE> <DEDENT> for i in range(1, m): <NEW_LINE> <INDENT> for j in range(1, n): <NEW_LINE> <INDENT> dp[i][j] = dp[i - 1][j] + dp[i][j - 1] <NEW_LINE> <DEDENT> <DEDENT> return dp[m - 1][n - 1]
@param m: positive integer (1 <= m <= 100) @param n: positive integer (1 <= n <= 100) @return: An integer
62598fa3e64d504609df92ff
class IDataCubeSettings(Interface): <NEW_LINE> <INDENT> datacube_thumbnail = schema.TextLine( title=_(u"DataCube thumbnail"), description=_(u"Default picture URL when no thumbnail is available"), required=True, default=u"++resource++scoreboard.theme.images/connect_thumbnail.png" ) <NEW_LINE> visualization_thumbnail = schema.TextLine( title=_(u"Visualization thumbnail"), description=_(u"Default picture URL when no thumbnail is available"), required=True, default=u"++resource++scoreboard.theme.images/map_thumbnail.png" )
Settings for datacube
62598fa367a9b606de545e57
class StorageFileField(forms.MultiValueField): <NEW_LINE> <INDENT> def __init__(self, language=None, *args, **kwargs): <NEW_LINE> <INDENT> attrs = kwargs.pop('attrs', {}) <NEW_LINE> language_initial = getattr(language, 'code', None) <NEW_LINE> if language_initial: <NEW_LINE> <INDENT> language_queryset = Language.objects.filter(code=language_initial) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> language_queryset = Language.objects.all() <NEW_LINE> <DEDENT> language_choices = [(l.code, l) for l in language_queryset] <NEW_LINE> storagefile_choices = StorageFile.objects.all() <NEW_LINE> fields = [ forms.ChoiceField(choices=language_choices, initial=language_initial), forms.ModelChoiceField(queryset=storagefile_choices) ] <NEW_LINE> widget = StorageFileWidget(attrs=attrs, language=language, language_choices=language_choices, *args, **kwargs) <NEW_LINE> kwargs.pop('display_language', None) <NEW_LINE> super(StorageFileField, self).__init__(fields, widget=widget, *args, **kwargs) <NEW_LINE> <DEDENT> def compress(self, data_list): <NEW_LINE> <INDENT> if data_list: <NEW_LINE> <INDENT> return data_list <NEW_LINE> <DEDENT> return ['',''] <NEW_LINE> <DEDENT> def clean(self, value): <NEW_LINE> <INDENT> data = super(StorageFileField, self).clean(value) <NEW_LINE> return data[1]
Field for handling creation/deletion of StorageFile objects based on file upload. Whenever a file is chosen to be uploaded, the upload happens through AJAX using the storage app API, creating a StorageFile object accordingly. The deletion of the uploaded file happens through AJAX too, as the setting of the related language to the StogareFile object. In the end this field just returns the StorageFile id, which is the important data used in the forms.
62598fa33eb6a72ae038a4d0
class WordSet: <NEW_LINE> <INDENT> def __init__(self, words=None): <NEW_LINE> <INDENT> if words == None: <NEW_LINE> <INDENT> self.words = set() <NEW_LINE> self.letterFreq = collections.Counter() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.words = words.copy() <NEW_LINE> self.updated() <NEW_LINE> <DEDENT> <DEDENT> def copy(self): <NEW_LINE> <INDENT> retVal = WordSet() <NEW_LINE> retVal.words = self.words.copy() <NEW_LINE> retVal.letterFreq = self.letterFreq.copy() <NEW_LINE> return retVal <NEW_LINE> <DEDENT> def updated(self): <NEW_LINE> <INDENT> self.letterFreq = collections.Counter([letter for sublist in map(set,self.words) for letter in sublist]) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.words) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.words) + " " + str(self.letterFreq)
Simple class to encapsulate a set of possible words and the letter frequency assoicated with it.
62598fa34f6381625f199403
class SetVolume(command.Command): <NEW_LINE> <INDENT> def get_parser(self, prog_name): <NEW_LINE> <INDENT> parser = super(SetVolume, self).get_parser(prog_name) <NEW_LINE> parser.add_argument( 'volume', metavar='<volume>', help=_('Volume to modify (name or ID)'), ) <NEW_LINE> parser.add_argument( '--name', metavar='<name>', help=_('New volume name'), ) <NEW_LINE> parser.add_argument( '--size', metavar='<size>', type=int, help=_('Extend volume size in GB'), ) <NEW_LINE> parser.add_argument( '--description', metavar='<description>', help=_('New volume description'), ) <NEW_LINE> parser.add_argument( '--property', metavar='<key=value>', action=parseractions.KeyValueAction, help=_('Set a property on this volume ' '(repeat option to set multiple properties)'), ) <NEW_LINE> parser.add_argument( '--image-property', metavar='<key=value>', action=parseractions.KeyValueAction, help=_('Set an image property on this volume ' '(repeat option to set multiple image properties)'), ) <NEW_LINE> return parser <NEW_LINE> <DEDENT> def take_action(self, parsed_args): <NEW_LINE> <INDENT> volume_client = self.app.client_manager.volume <NEW_LINE> volume = utils.find_resource(volume_client.volumes, parsed_args.volume) <NEW_LINE> if parsed_args.size: <NEW_LINE> <INDENT> if volume.status != 'available': <NEW_LINE> <INDENT> self.app.log.error(_("Volume is in %s state, it must be " "available before size can be extended") % volume.status) <NEW_LINE> return <NEW_LINE> <DEDENT> if parsed_args.size <= volume.size: <NEW_LINE> <INDENT> self.app.log.error(_("New size must be greater than %s GB") % volume.size) <NEW_LINE> return <NEW_LINE> <DEDENT> volume_client.volumes.extend(volume.id, parsed_args.size) <NEW_LINE> <DEDENT> if parsed_args.property: <NEW_LINE> <INDENT> volume_client.volumes.set_metadata(volume.id, parsed_args.property) <NEW_LINE> <DEDENT> if parsed_args.image_property: <NEW_LINE> <INDENT> volume_client.volumes.set_image_metadata( volume.id, parsed_args.image_property) <NEW_LINE> <DEDENT> kwargs = {} <NEW_LINE> if parsed_args.name: <NEW_LINE> <INDENT> kwargs['display_name'] = parsed_args.name <NEW_LINE> <DEDENT> if parsed_args.description: <NEW_LINE> <INDENT> kwargs['display_description'] = parsed_args.description <NEW_LINE> <DEDENT> if kwargs: <NEW_LINE> <INDENT> volume_client.volumes.update(volume.id, **kwargs)
Set volume properties
62598fa3d6c5a102081e1fd3
class SetOwnershipView(BaseLoggedInPage): <NEW_LINE> <INDENT> @View.nested <NEW_LINE> class form(View): <NEW_LINE> <INDENT> user_name = BootstrapSelect('user_name') <NEW_LINE> group_name = BootstrapSelect('group_name') <NEW_LINE> entities = View.nested(BaseNonInteractiveEntitiesView) <NEW_LINE> save_button = Button('Save') <NEW_LINE> reset_button = Button('Reset') <NEW_LINE> cancel_button = Button('Cancel') <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_displayed(self): <NEW_LINE> <INDENT> return False
Set vms/instance ownership page The title actually as Instance|VM.VM_TYPE string in it, otherwise the same
62598fa3090684286d593621
class AnchorPosWrapper(QObject): <NEW_LINE> <INDENT> _spinbox_changed_signal = pyqtSignal(float) <NEW_LINE> _SPINNER_THRESHOLD = 0.001 <NEW_LINE> def __init__(self, x, y, z): <NEW_LINE> <INDENT> super(AnchorPosWrapper, self).__init__() <NEW_LINE> self._x = x <NEW_LINE> self._y = y <NEW_LINE> self._z = z <NEW_LINE> self._ref_x = 0 <NEW_LINE> self._ref_y = 0 <NEW_LINE> self._ref_z = 0 <NEW_LINE> self._has_ref_set = False <NEW_LINE> self._spinbox_changed_signal.connect(self._compare_all_ref_positions) <NEW_LINE> self._x.valueChanged.connect(self._spinbox_changed_signal) <NEW_LINE> self._y.valueChanged.connect(self._spinbox_changed_signal) <NEW_LINE> self._z.valueChanged.connect(self._spinbox_changed_signal) <NEW_LINE> <DEDENT> def get_position(self): <NEW_LINE> <INDENT> return (self._x.value(), self._y.value(), self._z.value()) <NEW_LINE> <DEDENT> def _compare_one_ref_position(self, spinner, ref): <NEW_LINE> <INDENT> if (abs(spinner.value() - ref) < self._SPINNER_THRESHOLD): <NEW_LINE> <INDENT> spinner.setStyleSheet(STYLE_GREEN_BACKGROUND) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> spinner.setStyleSheet(STYLE_RED_BACKGROUND) <NEW_LINE> <DEDENT> <DEDENT> def _compare_all_ref_positions(self): <NEW_LINE> <INDENT> if self._has_ref_set: <NEW_LINE> <INDENT> self._compare_one_ref_position(self._x, self._ref_x) <NEW_LINE> self._compare_one_ref_position(self._y, self._ref_y) <NEW_LINE> self._compare_one_ref_position(self._z, self._ref_z) <NEW_LINE> <DEDENT> <DEDENT> def set_position(self, position): <NEW_LINE> <INDENT> self._x.setValue(position[0]) <NEW_LINE> self._y.setValue(position[1]) <NEW_LINE> self._z.setValue(position[2]) <NEW_LINE> <DEDENT> def set_ref_position(self, position): <NEW_LINE> <INDENT> self._ref_x = position[0] <NEW_LINE> self._ref_y = position[1] <NEW_LINE> self._ref_z = position[2] <NEW_LINE> self._has_ref_set = True <NEW_LINE> self._compare_all_ref_positions() <NEW_LINE> <DEDENT> def enable(self, enabled): <NEW_LINE> <INDENT> self._x.setEnabled(enabled) <NEW_LINE> self._y.setEnabled(enabled) <NEW_LINE> self._z.setEnabled(enabled) <NEW_LINE> if not enabled: <NEW_LINE> <INDENT> self._has_ref_set = False <NEW_LINE> self._x.setStyleSheet(STYLE_NO_BACKGROUND) <NEW_LINE> self._y.setStyleSheet(STYLE_NO_BACKGROUND) <NEW_LINE> self._z.setStyleSheet(STYLE_NO_BACKGROUND)
Wraps the UI elements of one anchor position
62598fa3c432627299fa2e67
class PermalinkHandler(tornado.web.RequestHandler): <NEW_LINE> <INDENT> async def post(self): <NEW_LINE> <INDENT> def encode(s): <NEW_LINE> <INDENT> return base64.urlsafe_b64encode( zlib.compress(s.encode("utf8"))).decode("utf8") <NEW_LINE> <DEDENT> args = self.request.arguments <NEW_LINE> logger.debug("Storing permalink %s", args) <NEW_LINE> code = self.get_argument("code") <NEW_LINE> language = self.get_argument("language", "sage") <NEW_LINE> interacts = self.get_argument("interacts", "[]") <NEW_LINE> retval = {} <NEW_LINE> retval["zip"] = encode(code) <NEW_LINE> retval["query"] = await self.application.db.add( code, language, interacts) <NEW_LINE> retval["interacts"] = encode(interacts) <NEW_LINE> if "n" in args: <NEW_LINE> <INDENT> retval["n"] = int(self.get_argument("n")) <NEW_LINE> <DEDENT> if "frame" in args: <NEW_LINE> <INDENT> retval = ('<script>parent.postMessage(%r,"*");</script>' % json.dumps(retval)) <NEW_LINE> self.set_header("Content-Type", "text/html") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.set_header("Access-Control-Allow-Origin", self.request.headers.get("Origin", "*")) <NEW_LINE> self.set_header("Access-Control-Allow-Credentials", "true") <NEW_LINE> <DEDENT> self.write(retval) <NEW_LINE> self.finish() <NEW_LINE> <DEDENT> async def get(self): <NEW_LINE> <INDENT> q = self.get_argument("q") <NEW_LINE> try: <NEW_LINE> <INDENT> logger.debug("Looking up permalink %s", q) <NEW_LINE> response = await self.application.db.get(q) <NEW_LINE> <DEDENT> except LookupError: <NEW_LINE> <INDENT> logger.warning("ID not found in permalink database %s", q) <NEW_LINE> self.set_status(404) <NEW_LINE> self.finish("ID not found in permalink database") <NEW_LINE> return <NEW_LINE> <DEDENT> response = json.dumps(response) <NEW_LINE> if self.get_arguments("callback"): <NEW_LINE> <INDENT> self.write("%s(%r);" % (self.get_argument("callback"), response)) <NEW_LINE> self.set_header("Content-Type", "application/javascript") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.write(response) <NEW_LINE> self.set_header("Access-Control-Allow-Origin", self.request.headers.get("Origin", "*")) <NEW_LINE> self.set_header("Access-Control-Allow-Credentials", "true") <NEW_LINE> self.set_header("Content-Type", "application/json") <NEW_LINE> <DEDENT> self.finish()
Permalink generation request handler. This accepts the code and language strings and stores these in the permalink database. A zip and query string are returned. The specified id can be used to generate permalinks with the format ``<root_url>?q=<id>``.
62598fa3fff4ab517ebcd671
class BatchMakerWQ(BatchMakerShell): <NEW_LINE> <INDENT> def _write_scripts(self, tileid): <NEW_LINE> <INDENT> super(BatchMakerWQ,self)._write_scripts() <NEW_LINE> self._write_wq_script(tileid) <NEW_LINE> <DEDENT> def _write_wq_script(self, tileid): <NEW_LINE> <INDENT> pass
write wq submit scripts in addition to shell scripts
62598fa31f037a2d8b9e3f76
class AnnotatedTask: <NEW_LINE> <INDENT> on_changed = aioxmpp.callbacks.Signal() <NEW_LINE> def __init__(self, asyncio_task: asyncio.Task): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.__asyncio_task = asyncio_task <NEW_LINE> self.__text = None <NEW_LINE> self.__progress_ratio = None <NEW_LINE> <DEDENT> def add_done_callback(self, fn): <NEW_LINE> <INDENT> @functools.wraps(fn) <NEW_LINE> def wrapper(task): <NEW_LINE> <INDENT> fn(self) <NEW_LINE> <DEDENT> self.__asyncio_task.add_done_callback(wrapper) <NEW_LINE> <DEDENT> @property <NEW_LINE> def text(self) -> str: <NEW_LINE> <INDENT> return self.__text <NEW_LINE> <DEDENT> @text.setter <NEW_LINE> def text(self, value: str): <NEW_LINE> <INDENT> if self.__text == value: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.__text = value <NEW_LINE> self.on_changed() <NEW_LINE> <DEDENT> @property <NEW_LINE> def progress_ratio(self) -> typing.Optional[float]: <NEW_LINE> <INDENT> return self.__progress_ratio <NEW_LINE> <DEDENT> @progress_ratio.setter <NEW_LINE> def progress_ratio(self, value: typing.Optional[float]): <NEW_LINE> <INDENT> if value is not None: <NEW_LINE> <INDENT> value = float(value) <NEW_LINE> <DEDENT> if self.__progress_ratio == value: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.__progress_ratio = value <NEW_LINE> self.on_changed() <NEW_LINE> <DEDENT> @property <NEW_LINE> def asyncio_task(self) -> asyncio.Task: <NEW_LINE> <INDENT> return self.__asyncio_task
A :class:`asyncio.Task` wrapper with human-readable information. :param asyncio_task: The asyncio Task of this annotated task. :type asyncio_task: :class:`asyncio.Task`
62598fa3e5267d203ee6b799
class Rectangle(): <NEW_LINE> <INDENT> def __init__(self, width=0, height=0): <NEW_LINE> <INDENT> self.width = width <NEW_LINE> self.height = height <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> string = "" <NEW_LINE> if self.width == 0 or self.height == 0: <NEW_LINE> <INDENT> return string <NEW_LINE> <DEDENT> for i in range(0, self.height): <NEW_LINE> <INDENT> for j in range(0, self.width): <NEW_LINE> <INDENT> string += '#' <NEW_LINE> <DEDENT> if i != self.height - 1: <NEW_LINE> <INDENT> string += '\n' <NEW_LINE> <DEDENT> <DEDENT> return string <NEW_LINE> <DEDENT> @property <NEW_LINE> def height(self): <NEW_LINE> <INDENT> return self.__height <NEW_LINE> <DEDENT> @height.setter <NEW_LINE> def height(self, value): <NEW_LINE> <INDENT> if not isinstance(value, int): <NEW_LINE> <INDENT> raise TypeError("height must be an integer") <NEW_LINE> <DEDENT> elif value < 0: <NEW_LINE> <INDENT> raise ValueError("height must be >= 0") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.__height = value <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def width(self): <NEW_LINE> <INDENT> return self.__width <NEW_LINE> <DEDENT> @width.setter <NEW_LINE> def width(self, value): <NEW_LINE> <INDENT> if not isinstance(value, int): <NEW_LINE> <INDENT> raise TypeError("width must be an integer") <NEW_LINE> <DEDENT> elif value < 0: <NEW_LINE> <INDENT> raise ValueError("width must be >= 0") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.__width = value <NEW_LINE> <DEDENT> <DEDENT> def area(self): <NEW_LINE> <INDENT> return (self.width * self.height) <NEW_LINE> <DEDENT> def perimeter(self): <NEW_LINE> <INDENT> if self.width == 0 or self.height == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> return ((2 * self.width) + (2 * self.height))
rectangle class for storing rectangle data
62598fa33539df3088ecc141
class UpdateArticle(UpdateView): <NEW_LINE> <INDENT> model = Article <NEW_LINE> fields = ['title', 'intro', 'content'] <NEW_LINE> template_name = "articles/update_article.html" <NEW_LINE> def dispatch(self, request, *args, **kwargs): <NEW_LINE> <INDENT> if request.user != self.get_object().author and not request.user.is_staff: <NEW_LINE> <INDENT> raise PermissionDenied() <NEW_LINE> <DEDENT> return super(UpdateArticle, self).dispatch(request, *args, **kwargs) <NEW_LINE> <DEDENT> def get_object(self): <NEW_LINE> <INDENT> article = Article.objects.get(slug=self.kwargs['slug']) <NEW_LINE> article.content = bleach_html(article.content) <NEW_LINE> article.content = article.content.replace('"', '\\"') <NEW_LINE> print(article.content) <NEW_LINE> return article <NEW_LINE> <DEDENT> def get_success_url(self): <NEW_LINE> <INDENT> messages.success(self.request, 'Article modifié !', extra_tags='done') <NEW_LINE> return reverse_lazy("get_article", kwargs={'slug': self.object.slug})
Modification d'un article L'utilisateur qui veut modifier l'article doit en être l'auteur
62598fa39c8ee823130400b5
class TwitterRecentMessagesUser(): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self._trmu_initiate_loop(self, **kwargs) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _trmu_initiate_loop(cls, self, **kwargs): <NEW_LINE> <INDENT> for index, row in self.df_uref.iterrows(): <NEW_LINE> <INDENT> udict = self.user_dict[row['id']] <NEW_LINE> try: <NEW_LINE> <INDENT> df = self._trmu_get_return_tweets(self, index, row) <NEW_LINE> if isinstance(df, pd.DataFrame): <NEW_LINE> <INDENT> if not df.empty: <NEW_LINE> <INDENT> gte_df = GetTimestampsForEachRelTweet(row['id'], testing=False, verbose=self.verbose).df <NEW_LINE> if self.verbose: <NEW_LINE> <INDENT> msg = f"There were {str(gte_df.shape[0])} timestamps needed" <NEW_LINE> help_print_arg(msg, isp=inspect.stack()) <NEW_LINE> <DEDENT> <DEDENT> self.user_dict[row['id']]['tweet_by_id'] = pd.read_parquet(udict['fpath_reft']) <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> uname = udict['username'] <NEW_LINE> if self.verbose: <NEW_LINE> <INDENT> help_print_arg('') <NEW_LINE> help_print_arg(f'TwitterRecentMessagesUser failed for {uname}') <NEW_LINE> <DEDENT> self.elog(self, e, verbose=self.verbose) <NEW_LINE> continue <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def _trmu_get_return_tweets(cls, self, index, row): <NEW_LINE> <INDENT> start_time = getDate.tz_aware_dt_now(offset=self.offset, rfcc=True, utc=True) <NEW_LINE> end_time = getDate.tz_aware_dt_now(rfcc=True, utc=True) <NEW_LINE> if self.verbose: <NEW_LINE> <INDENT> help_print_arg(f"Start time: {start_time}. End time: {end_time}") <NEW_LINE> <DEDENT> params = ({'username': row['username'], 'params': {'max_results': self.max_results, 'start_time': start_time, 'end_time': end_time, 'exclude': 'retweets,replies'}}) <NEW_LINE> call = TwitterAPI(method='user_tweets', **params) <NEW_LINE> self.call_list.append(call) <NEW_LINE> time.sleep(.5) <NEW_LINE> df = call.df.copy() <NEW_LINE> if self.verbose: <NEW_LINE> <INDENT> crh = call.get.raw.getheaders() <NEW_LINE> msg = f"{row['username']} Twitter calls remaining {crh['x-rate-limit-remaining']}" <NEW_LINE> help_print_arg('') <NEW_LINE> help_print_arg(msg) <NEW_LINE> <DEDENT> return df
Recent messages per user, get timestamps if necessary.
62598fa3d58c6744b42dc21a
class Chromosome(list): <NEW_LINE> <INDENT> def __add__(self, other): <NEW_LINE> <INDENT> l = [] <NEW_LINE> for i,(pos,allele) in enumerate(self): <NEW_LINE> <INDENT> l.append(allele + other[i][1]) <NEW_LINE> <DEDENT> return l <NEW_LINE> <DEDENT> def __mul__(self, other): <NEW_LINE> <INDENT> swap = 0 <NEW_LINE> recomb = (Chromosome([self[0]]),Chromosome([other[0]])) <NEW_LINE> for i in range(1,len(self)): <NEW_LINE> <INDENT> distance = self[i][0] - self[i-1][0] <NEW_LINE> swap = (swap + int(stats.poisson(distance).rvs(1))) % 2 <NEW_LINE> recomb[swap].append(self[i]) <NEW_LINE> recomb[1-swap].append(other[i]) <NEW_LINE> <DEDENT> return recomb
list of (pos,allele) tuples, where x is position expressed as a genetic distance in Morgans, e.g. chr1 = Chromosome([(0.01,Wh),(0.3,Wr)])
62598fa3b7558d58954634bb
class Flocci(GenericTumblrV1): <NEW_LINE> <INDENT> name = "flocci" <NEW_LINE> long_name = "floccinaucinihilipilification" <NEW_LINE> url = "https://floccinaucinihilipilificationa.tumblr.com"
Class to retrieve floccinaucinihilipilification comics.
62598fa301c39578d7f12c0c
class Node: <NEW_LINE> <INDENT> def __init__(self, parent): <NEW_LINE> <INDENT> self.parent = parent <NEW_LINE> self.left = None <NEW_LINE> self.right = None <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def count_elements(node): <NEW_LINE> <INDENT> if node is None: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> return Node.count_elements(node.left) + Node.count_elements(node.right) + 1
Single node in Binary Tree
62598fa34527f215b58e9d70
class Param(object): <NEW_LINE> <INDENT> def __init__(self, name, class_name=None): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.class_name = class_name
This class represents the HTTP parameter.
62598fa3fff4ab517ebcd672
class Block(object): <NEW_LINE> <INDENT> def __init__(self, index, timestamp, current_transactions, proof, previous_hash): <NEW_LINE> <INDENT> self.index = index <NEW_LINE> self.timestamp = timestamp <NEW_LINE> self.transactions = current_transactions <NEW_LINE> self.proof = proof <NEW_LINE> self.previous_hash = previous_hash <NEW_LINE> <DEDENT> def find_block_by_index(self, index): <NEW_LINE> <INDENT> return DB.child('chain').child('blocks').child(index).get()
Constructor
62598fa332920d7e50bc5ee4
class A(Element): <NEW_LINE> <INDENT> tag_name = 'a' <NEW_LINE> def __init__(self, link, content): <NEW_LINE> <INDENT> super().__init__(content, href=link)
<a> tag
62598fa34a966d76dd5eed70
class DoubleStaircaseReinforced(AdaptiveBase): <NEW_LINE> <INDENT> def __init__(self, stims, rate_constant=.05, probe_rate=.1, sample_log=False, **kwargs): <NEW_LINE> <INDENT> super(DoubleStaircaseReinforced, self).__init__(**kwargs) <NEW_LINE> self.dblstaircase = DoubleStaircase(stims, rate_constant) <NEW_LINE> self.stims = stims <NEW_LINE> self.probe_rate = probe_rate <NEW_LINE> self.sample_log = sample_log <NEW_LINE> self.last_probe = False <NEW_LINE> self.update_error_str = "reinforced double staircase queue %s hasn't been updated since last trial" % (self.stims[0]) <NEW_LINE> <DEDENT> def update(self, correct, no_resp): <NEW_LINE> <INDENT> super(DoubleStaircaseReinforced, self).update(correct, no_resp) <NEW_LINE> if self.last_probe: <NEW_LINE> <INDENT> self.dblstaircase.update(correct, no_resp) <NEW_LINE> <DEDENT> self.last_probe = False <NEW_LINE> <DEDENT> def next(self): <NEW_LINE> <INDENT> super(DoubleStaircaseReinforced, self).next() <NEW_LINE> if random.random() < self.probe_rate: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ret = self.dblstaircase.next() <NEW_LINE> self.last_probe = True <NEW_LINE> return ret <NEW_LINE> <DEDENT> except StopIteration: <NEW_LINE> <INDENT> self.probe_rate = 0 <NEW_LINE> self.last_probe = False <NEW_LINE> return self.next() <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.last_probe = False <NEW_LINE> if random.random() < .5: <NEW_LINE> <INDENT> if self.sample_log: <NEW_LINE> <INDENT> val = int((1 - rand_from_log_shape_dist()) * self.dblstaircase.low_idx) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> val = random.randrange(self.dblstaircase.low_idx) <NEW_LINE> <DEDENT> return {'class': 'L', 'stim_name': self.stims[val]} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self.sample_log: <NEW_LINE> <INDENT> val = self.dblstaircase.high_idx + int(rand_from_log_shape_dist() * (len(self.stims) - self.dblstaircase.high_idx)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> val = self.dblstaircase.high_idx + random.randrange(len(self.stims) - self.dblstaircase.high_idx) <NEW_LINE> <DEDENT> return {'class': 'R', 'stim_name': self.stims[val]} <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def no_response(self): <NEW_LINE> <INDENT> super(DoubleStaircaseReinforced, self).no_response() <NEW_LINE> self.last_probe = False <NEW_LINE> <DEDENT> def on_load(self): <NEW_LINE> <INDENT> super(DoubleStaircaseReinforced, self).on_load() <NEW_LINE> self.dblstaircase.on_load()
Generates conditions as with DoubleStaircase, but 1-probe_rate proportion of the trials easier/known trials to reduce frustration. Easier trials are sampled from a log shaped distribution so that more trials are sampled from the edges than near the indices stims: an array of stimuli names ordered from most easily left to most easily right rate_constant: the step size is the rate_constant*(high_idx-low_idx) probe_rate: proportion of trials that are between [0, low_idx] or [high_idx, length(stims)]
62598fa3a8370b77170f0268
class LoginForm(Form, NextFormMixin): <NEW_LINE> <INDENT> email = StringField(get_form_field_label('email')) <NEW_LINE> password = PasswordField(get_form_field_label('password')) <NEW_LINE> remember = BooleanField(get_form_field_label('remember_me')) <NEW_LINE> submit = SubmitField(get_form_field_label('login')) <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(LoginForm, self).__init__(*args, **kwargs) <NEW_LINE> if not self.next.data: <NEW_LINE> <INDENT> self.next.data = request.args.get('next', '') <NEW_LINE> <DEDENT> self.remember.default = config_value('DEFAULT_REMEMBER_ME') <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> if not super(LoginForm, self).validate(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if self.email.data.strip() == '': <NEW_LINE> <INDENT> self.email.errors.append(get_message('EMAIL_NOT_PROVIDED')[0]) <NEW_LINE> return False <NEW_LINE> <DEDENT> if self.password.data.strip() == '': <NEW_LINE> <INDENT> self.password.errors.append(get_message('PASSWORD_NOT_PROVIDED')[0]) <NEW_LINE> return False <NEW_LINE> <DEDENT> self.user = _datastore.get_user(self.email.data) <NEW_LINE> if self.user is None: <NEW_LINE> <INDENT> self.email.errors.append(get_message('USER_DOES_NOT_EXIST')[0]) <NEW_LINE> return False <NEW_LINE> <DEDENT> if not self.user.password: <NEW_LINE> <INDENT> self.password.errors.append(get_message('PASSWORD_NOT_SET')[0]) <NEW_LINE> return False <NEW_LINE> <DEDENT> if not verify_and_update_password(self.password.data, self.user): <NEW_LINE> <INDENT> self.password.errors.append(get_message('INVALID_PASSWORD')[0]) <NEW_LINE> return False <NEW_LINE> <DEDENT> if requires_confirmation(self.user): <NEW_LINE> <INDENT> self.email.errors.append(get_message('CONFIRMATION_REQUIRED')[0]) <NEW_LINE> return False <NEW_LINE> <DEDENT> if not self.user.is_active(): <NEW_LINE> <INDENT> self.email.errors.append(get_message('DISABLED_ACCOUNT')[0]) <NEW_LINE> return False <NEW_LINE> <DEDENT> return True
The default login form
62598fa3cc0a2c111447ae9c
class TestValidDirRePlyPacket(object): <NEW_LINE> <INDENT> def test_get_message(self): <NEW_LINE> <INDENT> state = RET_SUCCESS <NEW_LINE> info = 'test infomation' <NEW_LINE> packet = ValidDirReplyPacket(state, info) <NEW_LINE> msg = packet.get_message() <NEW_LINE> eq_(OP_VALID_DIR_REPLY, msg['method']) <NEW_LINE> eq_(state, msg['state']) <NEW_LINE> eq_(info, msg['info']) <NEW_LINE> state = RET_FAILURE <NEW_LINE> info = {'error id': 12, 'error msg': 'test error'} <NEW_LINE> packet = ValidDirReplyPacket(state, info) <NEW_LINE> msg = packet.get_message() <NEW_LINE> eq_(OP_VALID_DIR_REPLY, msg['method']) <NEW_LINE> eq_(state, msg['state']) <NEW_LINE> eq_(info, msg['info'])
the valid dir reply packet
62598fa391f36d47f2230de9
class Student(): <NEW_LINE> <INDENT> def __init__(self, name, age, sex, id_num): <NEW_LINE> <INDENT> self.__name = name <NEW_LINE> self.__age = age <NEW_LINE> self.__sex = sex <NEW_LINE> self.__id = id_num <NEW_LINE> <DEDENT> def get_name(self): <NEW_LINE> <INDENT> return self.__name <NEW_LINE> <DEDENT> def get_age(self): <NEW_LINE> <INDENT> return self.__age <NEW_LINE> <DEDENT> def get_sex(self): <NEW_LINE> <INDENT> return self.__sex <NEW_LINE> <DEDENT> def get_id_num(self): <NEW_LINE> <INDENT> return self.__id <NEW_LINE> <DEDENT> def set_name(self, name): <NEW_LINE> <INDENT> self.__name = name <NEW_LINE> <DEDENT> def set_age(self, age): <NEW_LINE> <INDENT> self.__age = age <NEW_LINE> <DEDENT> def to_string(self): <NEW_LINE> <INDENT> return "name: " + str(self.__name) + " age: " + str(self.__age) + " sex: " + str(self.__sex) + " id: " + str(self.__id)
Define a student.
62598fa3097d151d1a2c0eb9
class moduleFormSet(BaseFormSet): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(moduleFormSet, self).__init__(*args, **kwargs) <NEW_LINE> <DEDENT> def clean(self): <NEW_LINE> <INDENT> if any(self.errors): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> l = [] <NEW_LINE> for form in self.forms: <NEW_LINE> <INDENT> nom = form.cleaned_data['nom'] <NEW_LINE> uv = form.cleaned_data['theuv'] <NEW_LINE> for i in l: <NEW_LINE> <INDENT> if i[0] == nom and uv == i[1]: <NEW_LINE> <INDENT> raise forms.ValidationError("Les modules doivent etre deux a deux distinct par uv") <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> l.append([nom, uv])
class for multiple forms in a same template
62598fa33eb6a72ae038a4d2
class Cache1(object): <NEW_LINE> <INDENT> def __init__(self, transforms=TRANSFORMS): <NEW_LINE> <INDENT> super(Cache1, self).__init__() <NEW_LINE> self.boards = {} <NEW_LINE> self.transforms = transforms <NEW_LINE> <DEDENT> def set(self, board, value): <NEW_LINE> <INDENT> for transform in self.transforms: <NEW_LINE> <INDENT> cells_2d = transform.execute(board.cells_2d()) <NEW_LINE> self.boards[cells_2d.tobytes()] = value <NEW_LINE> <DEDENT> <DEDENT> def get(self, board): <NEW_LINE> <INDENT> result = self.boards.get(board.cells_2d().tobytes(), None) <NEW_LINE> if result is None: <NEW_LINE> <INDENT> return None, False <NEW_LINE> <DEDENT> return result, True
docstring for Cache1
62598fa34f6381625f199404
@attr.s(kw_only=True) <NEW_LINE> class Group: <NEW_LINE> <INDENT> pass
Base class for Group attribute available at ALFAsim.
62598fa3be383301e0253686
class Ip(DataObject): <NEW_LINE> <INDENT> class_token = ['count', 'list'] <NEW_LINE> instance_token = ['info'] <NEW_LINE> all_token = class_token + instance_token <NEW_LINE> @classmethod <NEW_LINE> def count(cls, api): <NEW_LINE> <INDENT> info("Counting IPs") <NEW_LINE> with catch_fault(): <NEW_LINE> <INDENT> res = api.hosting.ip.count(APIKEY) <NEW_LINE> return "IP count: {}".format(res) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def list(cls, api): <NEW_LINE> <INDENT> res = {} <NEW_LINE> with catch_fault(): <NEW_LINE> <INDENT> for ip_addr in api.hosting.ip.list(APIKEY): <NEW_LINE> <INDENT> res[ip_addr['id']] = Ip(**ip_addr) <NEW_LINE> <DEDENT> return res <NEW_LINE> <DEDENT> <DEDENT> def info(self, api): <NEW_LINE> <INDENT> info("Info about IP {}".format(self['id'])) <NEW_LINE> with catch_fault(): <NEW_LINE> <INDENT> res = api.hosting.ip.info(APIKEY, self['id']) <NEW_LINE> return Ip(**res)
An IP address.
62598fa37047854f4633f266
class AppRunnerListener(object): <NEW_LINE> <INDENT> def preprocess(self) -> None: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def postprocess(self, pre_launch_timestamp: str) -> None: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def metrics_selector(self, am_start_output: str, pre_launch_timestamp: str) -> None: <NEW_LINE> <INDENT> pass
Interface for lisenter of AppRunner.
62598fa31f037a2d8b9e3f78
class SuiteNotFoundError(Exception): <NEW_LINE> <INDENT> pass
Suite not found or did not parse successfully.
62598fa3e5267d203ee6b79b
class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): <NEW_LINE> <INDENT> VERSION = 1 <NEW_LINE> async def async_step_import(self, data: dict[str, Any]) -> FlowResult: <NEW_LINE> <INDENT> name = data.get(CONF_NAME, DEFAULT_NAME) <NEW_LINE> host = data[CONF_HOST] <NEW_LINE> self._async_abort_entries_match({CONF_HOST: host}) <NEW_LINE> reason = None <NEW_LINE> try: <NEW_LINE> <INDENT> await validate_host(self.hass, host) <NEW_LINE> <DEDENT> except InvalidHost: <NEW_LINE> <INDENT> _LOGGER.error("An invalid host is configured for Vallox: %s", host) <NEW_LINE> reason = "invalid_host" <NEW_LINE> <DEDENT> except VALLOX_CONNECTION_EXCEPTIONS: <NEW_LINE> <INDENT> _LOGGER.error("Cannot connect to Vallox host %s", host) <NEW_LINE> reason = "cannot_connect" <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> _LOGGER.exception("Unexpected exception") <NEW_LINE> reason = "unknown" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.async_create_entry( title=name, data={ **data, CONF_NAME: name, }, ) <NEW_LINE> <DEDENT> return self.async_abort(reason=reason) <NEW_LINE> <DEDENT> async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> FlowResult: <NEW_LINE> <INDENT> integration = await async_get_integration(self.hass, DOMAIN) <NEW_LINE> if user_input is None: <NEW_LINE> <INDENT> return self.async_show_form( step_id="user", description_placeholders={ "integration_docs_url": integration.documentation }, data_schema=STEP_USER_DATA_SCHEMA, ) <NEW_LINE> <DEDENT> errors = {} <NEW_LINE> host = user_input[CONF_HOST] <NEW_LINE> self._async_abort_entries_match({CONF_HOST: host}) <NEW_LINE> try: <NEW_LINE> <INDENT> await validate_host(self.hass, host) <NEW_LINE> <DEDENT> except InvalidHost: <NEW_LINE> <INDENT> errors[CONF_HOST] = "invalid_host" <NEW_LINE> <DEDENT> except VALLOX_CONNECTION_EXCEPTIONS: <NEW_LINE> <INDENT> errors[CONF_HOST] = "cannot_connect" <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> _LOGGER.exception("Unexpected exception") <NEW_LINE> errors[CONF_HOST] = "unknown" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.async_create_entry( title=DEFAULT_NAME, data={ **user_input, CONF_NAME: DEFAULT_NAME, }, ) <NEW_LINE> <DEDENT> return self.async_show_form( step_id="user", description_placeholders={ "integration_docs_url": integration.documentation }, data_schema=STEP_USER_DATA_SCHEMA, errors=errors, )
Handle a config flow for the Vallox integration.
62598fa3baa26c4b54d4f13f
class User(db.Model): <NEW_LINE> <INDENT> __tablename__ = 'users' <NEW_LINE> username = db.Column(db.String(20), nullable=False, primary_key=True, unique=True) <NEW_LINE> password = db.Column(db.Text, nullable=False) <NEW_LINE> email = db.Column(db.String(50) , nullable=False , unique=True) <NEW_LINE> first_name = db.Column(db.String(30) , nullable=False) <NEW_LINE> last_name = db.Column(db.String(30) , nullable=False) <NEW_LINE> password_token = db.Column(db.Text , nullable=True) <NEW_LINE> feedbacks = db.relationship("Feedback" , cascade="all, delete" , passive_deletes=True , backref="user") <NEW_LINE> @property <NEW_LINE> def full_name(self): <NEW_LINE> <INDENT> return f'{self.first_name} {self.last_name}' <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def register(cls, username, pwd , email , first_name , last_name): <NEW_LINE> <INDENT> hashed = bcrypt.generate_password_hash(pwd) <NEW_LINE> hashed_utf8 = hashed.decode("utf8") <NEW_LINE> return cls(username=username, password=hashed_utf8 , email=email , first_name= first_name, last_name=last_name) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def authenticate(cls, username, pwd): <NEW_LINE> <INDENT> u = User.query.filter_by(username=username).first() <NEW_LINE> if u and bcrypt.check_password_hash(u.password, pwd): <NEW_LINE> <INDENT> return u <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def update_password(cls , token , pwd): <NEW_LINE> <INDENT> u = User.query.filter_by(password_token=token).first() <NEW_LINE> if u: <NEW_LINE> <INDENT> u.password = bcrypt.generate_password_hash(pwd) <NEW_LINE> u.password_token = None <NEW_LINE> db.session.commit() <NEW_LINE> return u <NEW_LINE> <DEDENT> return False
User.
62598fa33539df3088ecc143
class AddSmsSignRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.SignName = None <NEW_LINE> self.SignType = None <NEW_LINE> self.DocumentType = None <NEW_LINE> self.International = None <NEW_LINE> self.UsedMethod = None <NEW_LINE> self.ProofImage = None <NEW_LINE> self.CommissionImage = None <NEW_LINE> self.Remark = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.SignName = params.get("SignName") <NEW_LINE> self.SignType = params.get("SignType") <NEW_LINE> self.DocumentType = params.get("DocumentType") <NEW_LINE> self.International = params.get("International") <NEW_LINE> self.UsedMethod = params.get("UsedMethod") <NEW_LINE> self.ProofImage = params.get("ProofImage") <NEW_LINE> self.CommissionImage = params.get("CommissionImage") <NEW_LINE> self.Remark = params.get("Remark") <NEW_LINE> memeber_set = set(params.keys()) <NEW_LINE> for name, value in vars(self).items(): <NEW_LINE> <INDENT> if name in memeber_set: <NEW_LINE> <INDENT> memeber_set.remove(name) <NEW_LINE> <DEDENT> <DEDENT> if len(memeber_set) > 0: <NEW_LINE> <INDENT> warnings.warn("%s fileds are useless." % ",".join(memeber_set))
AddSmsSign请求参数结构体
62598fa3a17c0f6771d5c0c8
class MovieSearchResult(object): <NEW_LINE> <INDENT> def __init__(self, name, name_alt, year, url): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.name_alt = name_alt <NEW_LINE> self.url = url <NEW_LINE> self.year = year <NEW_LINE> <DEDENT> def get_movie(self): <NEW_LINE> <INDENT> return get_movie(self.url)
Třída reprezentující položku filmu z výsledků hledání na ČSFD. Obsahuje pouze základní informace dostupné ze stránky s výsledky a poskytuje metodu pro získání objektu obsahující kompletní informace ze stránky filmu.
62598fa3aad79263cf42e66e
class AdministradorNoModificaSuperUsuarios(permissions.BasePermission): <NEW_LINE> <INDENT> def has_object_permission(self, request, view, obj): <NEW_LINE> <INDENT> is_grupo_usuario_admin = request.user.grupo.name == "Administrador" <NEW_LINE> is_grupo_obj_superuser = (obj.grupo.name == "SuperUsuario" or obj.grupo.name == "Administrador") <NEW_LINE> if is_grupo_usuario_admin and is_grupo_obj_superuser: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True
This class implement the following permission: Only the SuperUsuario can modify, see and delete its information Esta clase implementa el siguiente permiso: Solo el SuperUsuario puede modificar, ver y eliminar su propia informacion
62598fa33617ad0b5ee05fe1
class Descriptor: <NEW_LINE> <INDENT> def __init__(self, descriptor: dict, file_name: str = ""): <NEW_LINE> <INDENT> self._descriptor = descriptor <NEW_LINE> self._set_file_name(file_name, self.table_name) <NEW_LINE> <DEDENT> @property <NEW_LINE> def table_name(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self._descriptor["datastore"]["tablename"] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise RuntimeError( "Error finding data in descriptor. Descriptor file may not be valid." ) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def table_schema(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self._descriptor["datastore"]["schema"] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise RuntimeError( "Error finding data in descriptor. Descriptor file may not be valid." ) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def api_schema(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self._descriptor["api"]["methods"][0] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise RuntimeError( "Error finding data in descriptor. Descriptor file may not be valid." ) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def data_resource_name(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self._descriptor["api"]["resource"] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise RuntimeError( "Error finding data in descriptor. Descriptor file may not be valid." ) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def restricted_fields(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self._descriptor["datastore"]["restricted_fields"] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def descriptor(self): <NEW_LINE> <INDENT> return self._descriptor <NEW_LINE> <DEDENT> @property <NEW_LINE> def file_name(self): <NEW_LINE> <INDENT> return self._file_name <NEW_LINE> <DEDENT> def get_checksum(self) -> str: <NEW_LINE> <INDENT> model_checksum = md5( json.dumps(self.table_schema, sort_keys=True).encode("utf-8") ).hexdigest() <NEW_LINE> return model_checksum <NEW_LINE> <DEDENT> def _set_file_name(self, file_name: str, table_name: str): <NEW_LINE> <INDENT> if file_name == "": <NEW_LINE> <INDENT> self._file_name = f"{table_name}.json" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._file_name = file_name
Stores all of the procedures for extracting data from descriptors.
62598fa3a79ad16197769eef
class T411Auth(AuthBase): <NEW_LINE> <INDENT> def __init__(self, token): <NEW_LINE> <INDENT> if isinstance(token, six.text_type): <NEW_LINE> <INDENT> self.token = token.encode('utf-8') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.token = token <NEW_LINE> <DEDENT> <DEDENT> def __call__(self, r): <NEW_LINE> <INDENT> r.headers[b'Authorization'] = self.token <NEW_LINE> return r
Attaches HTTP Authentication to the given Request object.
62598fa33d592f4c4edbad5c
class Function(node.Node('name', 'signatures')): <NEW_LINE> <INDENT> __slots__ = ()
A function or a method. Attributes: name: The name of this function. signatures: Possible list of parameter type combinations for this function.
62598fa38c0ade5d55dc35d7
class WebhookSaltAPIHandler(SaltAPIHandler): <NEW_LINE> <INDENT> def post(self, tag_suffix=None): <NEW_LINE> <INDENT> disable_auth = self.application.mod_opts.get("webhook_disable_auth") <NEW_LINE> if not disable_auth and not self._verify_auth(): <NEW_LINE> <INDENT> self.redirect("/login") <NEW_LINE> return <NEW_LINE> <DEDENT> tag = "salt/netapi/hook" <NEW_LINE> if tag_suffix: <NEW_LINE> <INDENT> tag += tag_suffix <NEW_LINE> <DEDENT> self.event = salt.utils.event.get_event( "master", self.application.opts["sock_dir"], self.application.opts["transport"], opts=self.application.opts, listen=False, ) <NEW_LINE> arguments = {} <NEW_LINE> for argname in self.request.query_arguments: <NEW_LINE> <INDENT> value = self.get_arguments(argname) <NEW_LINE> if len(value) == 1: <NEW_LINE> <INDENT> value = value[0] <NEW_LINE> <DEDENT> arguments[argname] = value <NEW_LINE> <DEDENT> ret = self.event.fire_event( { "post": self.request_payload, "get": arguments, "headers": dict(self.request.headers), }, tag, ) <NEW_LINE> self.write(self.serialize({"success": ret}))
A generic web hook entry point that fires an event on Salt's event bus External services can POST data to this URL to trigger an event in Salt. For example, Amazon SNS, Jenkins-CI or Travis-CI, or GitHub web hooks. .. note:: Be mindful of security Salt's Reactor can run any code. A Reactor SLS that responds to a hook event is responsible for validating that the event came from a trusted source and contains valid data. **This is a generic interface and securing it is up to you!** This URL requires authentication however not all external services can be configured to authenticate. For this reason authentication can be selectively disabled for this URL. Follow best practices -- always use SSL, pass a secret key, configure the firewall to only allow traffic from a known source, etc. The event data is taken from the request body. The :mailheader:`Content-Type` header is respected for the payload. The event tag is prefixed with ``salt/netapi/hook`` and the URL path is appended to the end. For example, a ``POST`` request sent to ``/hook/mycompany/myapp/mydata`` will produce a Salt event with the tag ``salt/netapi/hook/mycompany/myapp/mydata``. The following is an example ``.travis.yml`` file to send notifications to Salt of successful test runs: .. code-block:: yaml language: python script: python -m unittest tests after_success: - 'curl -sS http://saltapi-url.example.com:8000/hook/travis/build/success -d branch="${TRAVIS_BRANCH}" -d commit="${TRAVIS_COMMIT}"' .. seealso:: :ref:`Events <events>`, :ref:`Reactor <reactor>`
62598fa3d58c6744b42dc21b
class SMC100Test(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self) -> None: <NEW_LINE> <INDENT> addr = '/dev/ttyUSB0' <NEW_LINE> device_index = 1 <NEW_LINE> self.device = newport.SMC100(addr, device_index) <NEW_LINE> self.device.initialize() <NEW_LINE> <DEDENT> def tearDown(self) -> None: <NEW_LINE> <INDENT> self.device.close() <NEW_LINE> <DEDENT> def test_idn(self): <NEW_LINE> <INDENT> result = self.device.idn <NEW_LINE> self.assertIsInstance(result, str) <NEW_LINE> <DEDENT> def test_is_moving(self): <NEW_LINE> <INDENT> result = self.device.is_moving <NEW_LINE> self.assertIsInstance(result, bool) <NEW_LINE> <DEDENT> def test_error_and_controller_status(self): <NEW_LINE> <INDENT> result = self.device.error_and_controller_status() <NEW_LINE> self.assertIsInstance(result[0], str) <NEW_LINE> self.assertIsInstance(result[1], str) <NEW_LINE> <DEDENT> def test_get_last_command_error(self): <NEW_LINE> <INDENT> result = self.device.get_last_command_error() <NEW_LINE> self.assertIsInstance(result, str) <NEW_LINE> <DEDENT> def test_position(self): <NEW_LINE> <INDENT> result = self.device.position <NEW_LINE> self.assertIsInstance(result, float) <NEW_LINE> <DEDENT> def test_speed(self): <NEW_LINE> <INDENT> result = self.device.speed <NEW_LINE> self.assertIsInstance(result, float) <NEW_LINE> <DEDENT> def test_acceleration(self): <NEW_LINE> <INDENT> result = self.device.acceleration <NEW_LINE> self.assertIsInstance(result, float)
For testing the Newport SMC100 class.
62598fa332920d7e50bc5ee5
class BotCommand: <NEW_LINE> <INDENT> def __init__(self, dictionary=None): <NEW_LINE> <INDENT> if dictionary is None: <NEW_LINE> <INDENT> dictionary = {} <NEW_LINE> <DEDENT> self.dict = dictionary <NEW_LINE> self.command = dictionary["command"] if "command" in dictionary else None <NEW_LINE> self.description = dictionary["description"] if "description" in dictionary else None <NEW_LINE> for index, value in self.dict.items(): <NEW_LINE> <INDENT> if not hasattr(self, index): <NEW_LINE> <INDENT> setattr(self, index, helper.setBvar(value))
This object represents a bot command.[See on Telegram API](https://core.telegram.org/bots/api#botcommand) - - - - - **Fields**: - `command`: `string` - Text of the command; 1-32 characters. Can contain only lowercase English letters, digits and underscores. - `description`: `string` - Description of the command; 1-256 characters.
62598fa3cb5e8a47e493c0be
class Data(RESTApi): <NEW_LINE> <INDENT> def __init__(self, app, config, mount): <NEW_LINE> <INDENT> RESTApi.__init__(self, app, config, mount) <NEW_LINE> for k, v in app.appconfig.debug.iteritems(): <NEW_LINE> <INDENT> debug[k] = v <NEW_LINE> <DEDENT> if not getattr(app, 'contentproxy', None): <NEW_LINE> <INDENT> app.contentproxy = ContentProxy(app.appconfig) <NEW_LINE> <DEDENT> if not getattr(app, 'contentscraper', None): <NEW_LINE> <INDENT> app.contentscraper = ContentScraper(app.appconfig) <NEW_LINE> <DEDENT> self.proxy = app.contentproxy <NEW_LINE> self.scraper = app.contentscraper <NEW_LINE> self._add({ "caf": CAFData(app, self, config, mount), "phedex": PhEDEx(app, self, config, mount), "host": HostData(app, self, config, mount), "world-map": WorldMapShape(app, self, config, mount) })
Server object for REST data access API.
62598fa36aa9bd52df0d4d5a
class SEModule(nn.Module): <NEW_LINE> <INDENT> def __init__(self, in_ch, reduction=16, sigmoid=nn.Sigmoid(), bn=nn.BatchNorm2d, nolinear=nn.ReLU()): <NEW_LINE> <INDENT> super(SEModule, self).__init__() <NEW_LINE> self.avgpool = nn.AdaptiveAvgPool2d(1) <NEW_LINE> self.fc = nn.Sequential( Conv2d(in_ch, in_ch // reduction, ksize=1, stride=1, padding=0, bn=bn, nolinear=nolinear), Conv2d(in_ch // reduction, in_ch, ksize=1, stride=1, padding=0, bn=bn, nolinear=sigmoid) ) <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> net = self.avgpool(x) <NEW_LINE> net = self.fc(net) <NEW_LINE> return net
Implementation of semodule in SENet and MobileNetV3, there we use 1x1 conv replace the linear layer. SENet:"Squeeze-and-Excitation Networks"<https://arxiv.org/abs/1709.01507> MobileNetV3: "Searching for MobileNetV3" <https://arxiv.org/abs/1905.02244>
62598fa37b25080760ed733a
class AbsDatabaseSettings(AbsSettingsBase): <NEW_LINE> <INDENT> Year = AbsRange(1900, 2200) <NEW_LINE> Text = AbsRange(0, 1000) <NEW_LINE> Integer = AbsRange(0, 200 )
Class encapsulating all the absolute settings for the database
62598fa357b8e32f52508063
class DaoApplication(): <NEW_LINE> <INDENT> def getAll(): <NEW_LINE> <INDENT> return Application.all() <NEW_LINE> <DEDENT> getAll = staticmethod(getAll) <NEW_LINE> def getByVer(dllVer): <NEW_LINE> <INDENT> query = Application.gql("WHERE dllVer = :dllVer", dllVer=dllVer, parent=getConfig()) <NEW_LINE> appIter = query.run() <NEW_LINE> apps = [] <NEW_LINE> for app in appIter: <NEW_LINE> <INDENT> apps.append(app) <NEW_LINE> <DEDENT> return apps <NEW_LINE> <DEDENT> getByVer = staticmethod(getByVer) <NEW_LINE> def add(dllVer, name, appUrl, iconId): <NEW_LINE> <INDENT> dbApplication = Application(parent=getConfig(), dllVer=dllVer, name=name, appUrl=appUrl, iconId=iconId) <NEW_LINE> dbApplication.put() <NEW_LINE> <DEDENT> add = staticmethod(add) <NEW_LINE> def delete(application): <NEW_LINE> <INDENT> application.delete() <NEW_LINE> <DEDENT> delete = staticmethod(delete)
Application accessor.
62598fa307f4c71912baf2d3
class _CachedRelation: <NEW_LINE> <INDENT> def __init__(self, inner): <NEW_LINE> <INDENT> self.referenced_by = {} <NEW_LINE> self.inner = inner <NEW_LINE> <DEDENT> def __str__(self) -> str: <NEW_LINE> <INDENT> return ( '_CachedRelation(database={}, schema={}, identifier={}, inner={})' ).format(self.database, self.schema, self.identifier, self.inner) <NEW_LINE> <DEDENT> @property <NEW_LINE> def database(self) -> Optional[str]: <NEW_LINE> <INDENT> return lowercase(self.inner.database) <NEW_LINE> <DEDENT> @property <NEW_LINE> def schema(self) -> Optional[str]: <NEW_LINE> <INDENT> return lowercase(self.inner.schema) <NEW_LINE> <DEDENT> @property <NEW_LINE> def identifier(self) -> Optional[str]: <NEW_LINE> <INDENT> return lowercase(self.inner.identifier) <NEW_LINE> <DEDENT> def __copy__(self): <NEW_LINE> <INDENT> new = self.__class__(self.inner) <NEW_LINE> new.__dict__.update(self.__dict__) <NEW_LINE> return new <NEW_LINE> <DEDENT> def __deepcopy__(self, memo): <NEW_LINE> <INDENT> new = self.__class__(self.inner.incorporate()) <NEW_LINE> new.__dict__.update(self.__dict__) <NEW_LINE> new.referenced_by = deepcopy(self.referenced_by, memo) <NEW_LINE> <DEDENT> def is_referenced_by(self, key): <NEW_LINE> <INDENT> return key in self.referenced_by <NEW_LINE> <DEDENT> def key(self): <NEW_LINE> <INDENT> return _make_key(self) <NEW_LINE> <DEDENT> def add_reference(self, referrer: '_CachedRelation'): <NEW_LINE> <INDENT> self.referenced_by[referrer.key()] = referrer <NEW_LINE> <DEDENT> def collect_consequences(self): <NEW_LINE> <INDENT> consequences = {self.key()} <NEW_LINE> for relation in self.referenced_by.values(): <NEW_LINE> <INDENT> consequences.update(relation.collect_consequences()) <NEW_LINE> <DEDENT> return consequences <NEW_LINE> <DEDENT> def release_references(self, keys): <NEW_LINE> <INDENT> keys = set(self.referenced_by) & set(keys) <NEW_LINE> for key in keys: <NEW_LINE> <INDENT> self.referenced_by.pop(key) <NEW_LINE> <DEDENT> <DEDENT> def rename(self, new_relation): <NEW_LINE> <INDENT> self.inner = self.inner.incorporate( path={ 'database': new_relation.inner.database, 'schema': new_relation.inner.schema, 'identifier': new_relation.inner.identifier }, ) <NEW_LINE> <DEDENT> def rename_key(self, old_key, new_key): <NEW_LINE> <INDENT> if new_key in self.referenced_by: <NEW_LINE> <INDENT> dbt.exceptions.raise_cache_inconsistent( 'in rename of "{}" -> "{}", new name is in the cache already' .format(old_key, new_key) ) <NEW_LINE> <DEDENT> if old_key not in self.referenced_by: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> value = self.referenced_by.pop(old_key) <NEW_LINE> self.referenced_by[new_key] = value <NEW_LINE> <DEDENT> def dump_graph_entry(self): <NEW_LINE> <INDENT> return [dot_separated(r) for r in self.referenced_by]
Nothing about _CachedRelation is guaranteed to be thread-safe! :attr str schema: The schema of this relation. :attr str identifier: The identifier of this relation. :attr Dict[_ReferenceKey, _CachedRelation] referenced_by: The relations that refer to this relation. :attr BaseRelation inner: The underlying dbt relation.
62598fa34a966d76dd5eed72
@ddt.ddt <NEW_LINE> @attr('mongo') <NEW_LINE> class CrossStoreXMLRoundtrip(CourseComparisonTest, PartitionTestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(CrossStoreXMLRoundtrip, self).setUp() <NEW_LINE> self.export_dir = mkdtemp() <NEW_LINE> self.addCleanup(rmtree, self.export_dir, ignore_errors=True) <NEW_LINE> <DEDENT> @ddt.data(*itertools.product( MODULESTORE_SETUPS, MODULESTORE_SETUPS, CONTENTSTORE_SETUPS, CONTENTSTORE_SETUPS, COURSE_DATA_NAMES, )) <NEW_LINE> @ddt.unpack <NEW_LINE> def test_round_trip(self, source_builder, dest_builder, source_content_builder, dest_content_builder, course_data_name): <NEW_LINE> <INDENT> with source_content_builder.build() as source_content: <NEW_LINE> <INDENT> with source_builder.build(source_content) as source_store: <NEW_LINE> <INDENT> with dest_content_builder.build() as dest_content: <NEW_LINE> <INDENT> with dest_builder.build(dest_content) as dest_store: <NEW_LINE> <INDENT> source_course_key = source_store.make_course_key('a', 'course', 'course') <NEW_LINE> dest_course_key = dest_store.make_course_key('a', 'course', 'course') <NEW_LINE> import_from_xml( source_store, 'test_user', TEST_DATA_DIR, course_dirs=[course_data_name], static_content_store=source_content, target_course_id=source_course_key, create_new_course_if_not_present=True, ) <NEW_LINE> export_to_xml( source_store, source_content, source_course_key, self.export_dir, 'exported_source_course', ) <NEW_LINE> import_from_xml( dest_store, 'test_user', self.export_dir, course_dirs=['exported_source_course'], static_content_store=dest_content, target_course_id=dest_course_key, create_new_course_if_not_present=True, ) <NEW_LINE> self.exclude_field(None, 'wiki_slug') <NEW_LINE> self.exclude_field(None, 'xml_attributes') <NEW_LINE> self.exclude_field(None, 'parent') <NEW_LINE> self.ignore_asset_key('_id') <NEW_LINE> self.ignore_asset_key('uploadDate') <NEW_LINE> self.ignore_asset_key('content_son') <NEW_LINE> self.ignore_asset_key('thumbnail_location') <NEW_LINE> self.assertCoursesEqual( source_store, source_course_key, dest_store, dest_course_key, ) <NEW_LINE> self.assertAssetsEqual( source_content, source_course_key, dest_content, dest_course_key, )
This class exists to test XML import and export between different modulestore classes.
62598fa3cc0a2c111447ae9e
@implementer(IDisplay) <NEW_LINE> class DisplayCurses(Display): <NEW_LINE> <INDENT> def init(self): <NEW_LINE> <INDENT> super(DisplayCurses, self).init() <NEW_LINE> curses.initscr() <NEW_LINE> curses.curs_set(0) <NEW_LINE> self.display = curses.newwin(self.height + 3, self.width + 2, 0, 0) <NEW_LINE> self.initialized = True <NEW_LINE> self.draw_frame() <NEW_LINE> <DEDENT> def draw_frame(self): <NEW_LINE> <INDENT> self.display.addstr(0, 0, '+' + '-' * self.width + '+') <NEW_LINE> for pos_y in range(self.height): <NEW_LINE> <INDENT> self.display.addstr(pos_y + 1, 0, '|') <NEW_LINE> self.display.addstr(pos_y + 1, self.width + 1, '|') <NEW_LINE> <DEDENT> self.display.addstr(self.height + 1, 0, '+' + '-' * self.width + '+') <NEW_LINE> <DEDENT> def write(self, line): <NEW_LINE> <INDENT> if not self.initialized: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if not self.pos_y < self.height: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if not self.pos_x < self.width: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.display.addstr(self.pos_y + 1, self.pos_x + 1, line) <NEW_LINE> self.display.refresh()
Curses frame_buffer.
62598fa33eb6a72ae038a4d4
class TaskQueue(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.run_queue = queue.PriorityQueue() <NEW_LINE> self._shutdown_now = False <NEW_LINE> self._shutdown_when_finished = False <NEW_LINE> self.current_task = None <NEW_LINE> self._thread = threading.Thread(target=self.run, name='task_queue') <NEW_LINE> self._thread.daemon = True <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> self._thread.start() <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> while not self._shutdown_now: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.current_task = self.run_queue.get(timeout=0.5) <NEW_LINE> <DEDENT> except queue.Empty: <NEW_LINE> <INDENT> if self._shutdown_when_finished: <NEW_LINE> <INDENT> self._shutdown_now = True <NEW_LINE> <DEDENT> continue <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.current_task.execute() <NEW_LINE> <DEDENT> except TaskAbort as e: <NEW_LINE> <INDENT> log.debug('task %s aborted: %r' % (self.current_task.name, e)) <NEW_LINE> <DEDENT> except (ProgrammingError, OperationalError): <NEW_LINE> <INDENT> log.critical('Database error while running a task. Attempting to recover.') <NEW_LINE> self.current_task.manager.crash_report() <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> log.critical('BUG: Unhandled exception during task queue run loop.') <NEW_LINE> self.current_task.manager.crash_report() <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> self.run_queue.task_done() <NEW_LINE> self.current_task = None <NEW_LINE> <DEDENT> <DEDENT> remaining_jobs = self.run_queue.qsize() <NEW_LINE> if remaining_jobs: <NEW_LINE> <INDENT> log.warning('task queue shut down with %s tasks remaining in the queue to run.' % remaining_jobs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> log.debug('task queue shut down') <NEW_LINE> <DEDENT> <DEDENT> def is_alive(self): <NEW_LINE> <INDENT> return self._thread.is_alive() <NEW_LINE> <DEDENT> def put(self, task): <NEW_LINE> <INDENT> self.run_queue.put(task) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return self.run_queue.qsize() <NEW_LINE> <DEDENT> def shutdown(self, finish_queue=True): <NEW_LINE> <INDENT> log.debug('task queue shutdown requested') <NEW_LINE> if finish_queue: <NEW_LINE> <INDENT> self._shutdown_when_finished = True <NEW_LINE> if self.run_queue.qsize(): <NEW_LINE> <INDENT> log.verbose('There are %s tasks to execute. Shutdown will commence when they have completed.' % self.run_queue.qsize()) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self._shutdown_now = True <NEW_LINE> <DEDENT> <DEDENT> def wait(self): <NEW_LINE> <INDENT> if sys.version_info >= (3, 4): <NEW_LINE> <INDENT> self._thread.join() <NEW_LINE> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> while self._thread.is_alive(): <NEW_LINE> <INDENT> time.sleep(0.5) <NEW_LINE> <DEDENT> <DEDENT> except KeyboardInterrupt: <NEW_LINE> <INDENT> log.error('Got ctrl-c, shutting down after running task (if any) completes') <NEW_LINE> self.shutdown(finish_queue=False) <NEW_LINE> while self._thread.is_alive(): <NEW_LINE> <INDENT> time.sleep(0.5)
Task processing thread. Only executes one task at a time, if more are requested they are queued up and run in turn.
62598fa324f1403a926857fb
class MultiInOutClassificationLayer(chainer.Chain): <NEW_LINE> <INDENT> def __init__( self, n_classes: List[int]=[168, 11, 7], classification_layer: str="SimpleLinear", output_num: int=3 ) -> None: <NEW_LINE> <INDENT> super(MultiInOutClassificationLayer, self).__init__() <NEW_LINE> self.n_classes = n_classes <NEW_LINE> self.output_num = len(n_classes) <NEW_LINE> with self.init_scope(): <NEW_LINE> <INDENT> for i in range(self.output_num): <NEW_LINE> <INDENT> setattr( self, "cls{}".format(i + 1), CLASSIFIER_DICT[classification_layer](self.n_classes[i])) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __call__(self, xs: Tuple[chainer.Variable]) -> chainer.Variable: <NEW_LINE> <INDENT> ret_list = [ getattr(self, "cls{}".format(i + 1))(xs[i]) for i in range(self.output_num)] <NEW_LINE> return functions.concat(ret_list, axis=1) <NEW_LINE> <DEDENT> def inference(self, xs: Tuple[chainer.Variable]) -> chainer.Variable: <NEW_LINE> <INDENT> return self(xs)
Wrapper for Classification Layer, which output multiple Variables
62598fa363d6d428bbee2642
class SequentialNonceVerifier(nonce.NonceGenerator): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def get_name(cls): <NEW_LINE> <INDENT> return "SequentialNonce" <NEW_LINE> <DEDENT> def __init__(self, length): <NEW_LINE> <INDENT> self.__generator = SequentialNonceGenerator(length) <NEW_LINE> self.__initialized = False <NEW_LINE> <DEDENT> def verify(self, my_nonce): <NEW_LINE> <INDENT> int_nonce = int(my_nonce, base=16) <NEW_LINE> if not self.__initialized: <NEW_LINE> <INDENT> self.__generator.set_state(int_nonce) <NEW_LINE> self.__initialized = True <NEW_LINE> return True <NEW_LINE> <DEDENT> expected = self.__generator.get() <NEW_LINE> return my_nonce == expected <NEW_LINE> <DEDENT> def advance(self): <NEW_LINE> <INDENT> if not self.__initialized: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.__generator.generate()
Verifier for sequential nonces. It will always accept the first value it receives, and then expect it to increment from there.
62598fa3d53ae8145f91831d
class I(CurrentSource): <NEW_LINE> <INDENT> def __init__(self, Ival): <NEW_LINE> <INDENT> self.args = (Ival, ) <NEW_LINE> self._Isc = Isuper(Ival)
Current source. If the expression contains s treat as s-domain current otherwise time domain. A constant I is considered DC with an s-domain current I / s.
62598fa3925a0f43d25e7ece
class IComposition(form.Schema): <NEW_LINE> <INDENT> form.model("models/composition.xml")
Composable page
62598fa37047854f4633f268