code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class Client(object): <NEW_LINE> <INDENT> def __init__(self, client=None): <NEW_LINE> <INDENT> self.swagger_types = { 'client': 'str' } <NEW_LINE> self.attribute_map = { 'client': 'client' } <NEW_LINE> self._client = client <NEW_LINE> <DEDENT> @property <NEW_LINE> def client(self): <NEW_LINE> <INDENT> return self._client <NEW_LINE> <DEDENT> @client.setter <NEW_LINE> def client(self, client): <NEW_LINE> <INDENT> self._client = client <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
625990743317a56b869bf1db
class CustomCFG: <NEW_LINE> <INDENT> def __init__(self, pg_db_mod): <NEW_LINE> <INDENT> dsn = pg_db_mod.dsn() <NEW_LINE> self.db_name = dsn['database'] <NEW_LINE> self.db_user = dsn['user'] <NEW_LINE> self.db_pass = None <NEW_LINE> self.db_host = dsn['host'] <NEW_LINE> self.db_port = dsn['port'] <NEW_LINE> self.db_ssl_mode = 'disable' <NEW_LINE> self.db_ssl_root_cert_path = '/dev/null'
Custom config class to override DB config with
625990747c178a314d78e881
class RDose(RPackage): <NEW_LINE> <INDENT> homepage = "https://bioconductor.org/packages/DOSE" <NEW_LINE> git = "https://git.bioconductor.org/packages/DOSE.git" <NEW_LINE> version('3.16.0', commit='a534a4f2ef1e54e8b92079cf1bbedb5042fd90cd') <NEW_LINE> version('3.10.2', commit='5ea51a2e2a04b4f3cc974cecb4537e14efd6a7e3') <NEW_LINE> version('3.8.2', commit='4d3d1ca710aa7e4288a412c8d52b054b86a57639') <NEW_LINE> version('3.6.1', commit='f2967f0482cea39222bfd15767d0f4a5994f241b') <NEW_LINE> version('3.4.0', commit='dabb70de1a0f91d1767601e871f2f1c16d29a612') <NEW_LINE> version('3.2.0', commit='71f563fc39d02dfdf65184c94e0890a63b96b86b') <NEW_LINE> depends_on('[email protected]:', type=('build', 'run')) <NEW_LINE> depends_on('[email protected]:', when='@3.6.1:', type=('build', 'run')) <NEW_LINE> depends_on('[email protected]:', when='@3.16.0:', type=('build', 'run')) <NEW_LINE> depends_on('r-annotationdbi', type=('build', 'run')) <NEW_LINE> depends_on('r-biocparallel', type=('build', 'run')) <NEW_LINE> depends_on('r-do-db', type=('build', 'run')) <NEW_LINE> depends_on('r-fgsea', type=('build', 'run')) <NEW_LINE> depends_on('r-ggplot2', type=('build', 'run')) <NEW_LINE> depends_on('[email protected]:', type=('build', 'run')) <NEW_LINE> depends_on('r-qvalue', type=('build', 'run')) <NEW_LINE> depends_on('r-reshape2', type=('build', 'run')) <NEW_LINE> depends_on('r-s4vectors', when='@:3.10.2', type=('build', 'run')) <NEW_LINE> depends_on('r-scales', when='@3.2.0:3.4.0', type=('build', 'run')) <NEW_LINE> depends_on('r-rvcheck', when='@3.4.0', type=('build', 'run')) <NEW_LINE> depends_on('r-igraph', when='@3.2.0:3.4.0', type=('build', 'run'))
Disease Ontology Semantic and Enrichment analysis This package implements five methods proposed by Resnik, Schlicker, Jiang, Lin and Wang respectively for measuring semantic similarities among DO terms and gene products. Enrichment analyses including hypergeometric model and gene set enrichment analysis are also implemented for discovering disease associations of high-throughput biological data.
6259907463b5f9789fe86a91
class NonlinearBoundaryValueSolver: <NEW_LINE> <INDENT> def __init__(self, problem): <NEW_LINE> <INDENT> logger.debug('Beginning NLBVP instantiation') <NEW_LINE> self.problem = problem <NEW_LINE> self.domain = domain = problem.domain <NEW_LINE> self.iteration = 0 <NEW_LINE> self.pencils = pencil.build_pencils(domain) <NEW_LINE> pencil.build_matrices(self.pencils, problem, ['L']) <NEW_LINE> namespace = problem.namespace <NEW_LINE> vars = [namespace[var] for var in problem.variables] <NEW_LINE> perts = [namespace['δ'+var] for var in problem.variables] <NEW_LINE> self.state = FieldSystem.from_fields(vars) <NEW_LINE> self.perturbations = FieldSystem.from_fields(perts) <NEW_LINE> for field in self.state.fields + self.perturbations.fields: <NEW_LINE> <INDENT> field.set_scales(1) <NEW_LINE> <DEDENT> self.evaluator = Evaluator(domain, namespace) <NEW_LINE> Fe_handler = self.evaluator.add_system_handler(iter=1, group='F') <NEW_LINE> Fb_handler = self.evaluator.add_system_handler(iter=1, group='F') <NEW_LINE> for eqn in problem.eqs: <NEW_LINE> <INDENT> Fe_handler.add_task(eqn['F-L']) <NEW_LINE> <DEDENT> for bc in problem.bcs: <NEW_LINE> <INDENT> Fb_handler.add_task(bc['F-L']) <NEW_LINE> <DEDENT> self.Fe = Fe_handler.build_system() <NEW_LINE> self.Fb = Fb_handler.build_system() <NEW_LINE> logger.debug('Finished NLBVP instantiation') <NEW_LINE> <DEDENT> def newton_iteration(self, damping=1): <NEW_LINE> <INDENT> self.evaluator.evaluate_group('F', iteration=self.iteration) <NEW_LINE> pencil.build_matrices(self.pencils, self.problem, ['dF']) <NEW_LINE> for p in self.pencils: <NEW_LINE> <INDENT> pFe = self.Fe.get_pencil(p) <NEW_LINE> pFb = self.Fb.get_pencil(p) <NEW_LINE> A = p.L_exp - p.dF_exp <NEW_LINE> b = p.G_eq * pFe + p.G_bc * pFb <NEW_LINE> x = linalg.spsolve(A, b, use_umfpack=USE_UMFPACK, permc_spec=PERMC_SPEC) <NEW_LINE> if p.dirichlet: <NEW_LINE> <INDENT> x = p.JD * x <NEW_LINE> <DEDENT> self.perturbations.set_pencil(p, x) <NEW_LINE> <DEDENT> self.perturbations.scatter() <NEW_LINE> self.state.gather() <NEW_LINE> self.state.data += damping*self.perturbations.data <NEW_LINE> self.state.scatter() <NEW_LINE> self.iteration += 1
Nonlinear boundary value problem solver. Parameters ---------- problem : problem object Problem describing system of differential equations and constraints Attributes ---------- state : system object System containing solution fields (after solve method is called)
6259907492d797404e3897f1
class SkiaBuildbotPageSet(page_set_module.PageSet): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(SkiaBuildbotPageSet, self).__init__( user_agent_type='tablet', credentials_path = 'data/credentials.json', archive_data_file='data/skia_cuteoverload_nexus10.json') <NEW_LINE> urls_list = [ 'http://cuteoverload.com/', ] <NEW_LINE> for url in urls_list: <NEW_LINE> <INDENT> self.AddPage(SkiaBuildbotDesktopPage(url, self))
Pages designed to represent the median, not highly optimized web
625990745fdd1c0f98e5f8aa
class CategoryRelation(models.Model): <NEW_LINE> <INDENT> category = models.ForeignKey(Category, verbose_name=_('category'), on_delete=models.CASCADE) <NEW_LINE> content_type = models.ForeignKey( ContentType, on_delete=models.CASCADE, limit_choices_to=CATEGORY_RELATION_LIMITS, verbose_name=_('content type')) <NEW_LINE> object_id = models.PositiveIntegerField(verbose_name=_('object id')) <NEW_LINE> content_object = GenericForeignKey('content_type', 'object_id') <NEW_LINE> relation_type = models.CharField( verbose_name=_('relation type'), max_length=200, blank=True, null=True, help_text=_("A generic text field to tag a relation, like 'leadphoto'.")) <NEW_LINE> objects = CategoryRelationManager() <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return "CategoryRelation"
Related category item
62599074a17c0f6771d5d842
class FileModel(QFileSystemModel): <NEW_LINE> <INDENT> RE_UN_LoadSignal = pyqtSignal(object) <NEW_LINE> AutoStartSignal = pyqtSignal(object) <NEW_LINE> def __init__(self , manager=None , *a, **kw): <NEW_LINE> <INDENT> super(FileModel,self).__init__(*a,**kw ) <NEW_LINE> self.manager = manager <NEW_LINE> <DEDENT> def columnCount(self, index): <NEW_LINE> <INDENT> return 6 <NEW_LINE> <DEDENT> def headerData(self, section, Orientation, role=Qt.DisplayRole): <NEW_LINE> <INDENT> if Orientation==1: <NEW_LINE> <INDENT> if section == PluginFileCol: <NEW_LINE> <INDENT> return "文件名" <NEW_LINE> <DEDENT> elif section == MTime: <NEW_LINE> <INDENT> return "修改时间" <NEW_LINE> <DEDENT> elif section == CTime: <NEW_LINE> <INDENT> return "创建时间" <NEW_LINE> <DEDENT> elif section == AutoStartCol: <NEW_LINE> <INDENT> return "允许自启动" <NEW_LINE> <DEDENT> <DEDENT> return super(FileModel,self).headerData(section, Orientation, role) <NEW_LINE> <DEDENT> def flags(self, index): <NEW_LINE> <INDENT> column = index.column() <NEW_LINE> if column==PluginFileCol: <NEW_LINE> <INDENT> flag = super(FileModel, self).flags(index) <NEW_LINE> return flag | Qt.ItemIsEnabled | Qt.ItemIsUserCheckable | Qt.ItemIsSelectable <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsUserCheckable <NEW_LINE> <DEDENT> <DEDENT> def data(self, index , role = Qt.DisplayRole): <NEW_LINE> <INDENT> if not index.isValid() : <NEW_LINE> <INDENT> return QVariant() <NEW_LINE> <DEDENT> column = index.column() <NEW_LINE> if role == Qt.CheckStateRole: <NEW_LINE> <INDENT> if column == PluginFileCol: <NEW_LINE> <INDENT> mod = index.data()[:-3] <NEW_LINE> return (Qt.Checked if self.manager.pluginsInfo["StartModule"][mod]["active"] else Qt.Unchecked) <NEW_LINE> <DEDENT> elif column == AutoStartCol: <NEW_LINE> <INDENT> mod = self.index(index.row(), PluginFileCol, self.manager.index).data()[:-3] <NEW_LINE> return (Qt.Checked if self.manager.jsonPlugin[mod]["Allow"] else Qt.Unchecked) <NEW_LINE> <DEDENT> <DEDENT> if role == Qt.DisplayRole: <NEW_LINE> <INDENT> if column == CTime: <NEW_LINE> <INDENT> mod = self.index(index.row(), PluginFileCol, self.manager.index).data()[:-3] <NEW_LINE> return self.manager.jsonPlugin[mod]["CreateTime"] <NEW_LINE> <DEDENT> elif column == AutoStartCol: <NEW_LINE> <INDENT> mod = self.index(index.row(), PluginFileCol, self.manager.index).data()[:-3] <NEW_LINE> return str(self.manager.jsonPlugin[mod]["Allow"] ) <NEW_LINE> <DEDENT> <DEDENT> return super(FileModel,self).data(index , role) <NEW_LINE> <DEDENT> def setData(self, index, value, role = Qt.DisplayRole): <NEW_LINE> <INDENT> if not index.isValid() : <NEW_LINE> <INDENT> return QVariant() <NEW_LINE> <DEDENT> if role == Qt.CheckStateRole: <NEW_LINE> <INDENT> mod = self.index(index.row(), PluginFileCol, self.manager.index).data()[:-3] <NEW_LINE> if index.column() == PluginFileCol: <NEW_LINE> <INDENT> self.RE_UN_LoadSignal.emit((mod, index)) <NEW_LINE> <DEDENT> elif index.column() == AutoStartCol: <NEW_LINE> <INDENT> self.AutoStartSignal.emit(mod) <NEW_LINE> <DEDENT> <DEDENT> return super(FileModel,self).setData(index , value, role)
继承QFileSystemModel.
625990748e7ae83300eea9be
class Layer(object): <NEW_LINE> <INDENT> def __init__(self, incoming, name=None): <NEW_LINE> <INDENT> if isinstance(incoming, tuple): <NEW_LINE> <INDENT> self.input_shape = incoming <NEW_LINE> self.input_layer = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.input_shape = incoming.output_shape <NEW_LINE> self.input_layer = incoming <NEW_LINE> <DEDENT> self.name = name <NEW_LINE> self.params = OrderedDict() <NEW_LINE> if any(d is not None and d <= 0 for d in self.input_shape): <NEW_LINE> <INDENT> raise ValueError(( "Cannot create Layer with a non-positive input_shape " "dimension. input_shape=%r, self.name=%r") % ( self.input_shape, self.name)) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def output_shape(self): <NEW_LINE> <INDENT> return self.get_output_shape_for(self.input_shape) <NEW_LINE> <DEDENT> def get_params(self, **tags): <NEW_LINE> <INDENT> result = list(self.params.keys()) <NEW_LINE> only = set(tag for tag, value in tags.items() if value) <NEW_LINE> if only: <NEW_LINE> <INDENT> result = [param for param in result if not (only - self.params[param])] <NEW_LINE> <DEDENT> exclude = set(tag for tag, value in tags.items() if not value) <NEW_LINE> if exclude: <NEW_LINE> <INDENT> result = [param for param in result if not (self.params[param] & exclude)] <NEW_LINE> <DEDENT> return utils.collect_shared_vars(result) <NEW_LINE> <DEDENT> def get_output_shape_for(self, input_shape): <NEW_LINE> <INDENT> return input_shape <NEW_LINE> <DEDENT> def get_output_for(self, input, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def add_param(self, spec, shape, name=None, **tags): <NEW_LINE> <INDENT> if name is not None: <NEW_LINE> <INDENT> if self.name is not None: <NEW_LINE> <INDENT> name = "%s.%s" % (self.name, name) <NEW_LINE> <DEDENT> <DEDENT> param = utils.create_param(spec, shape, name) <NEW_LINE> tags['trainable'] = tags.get('trainable', True) <NEW_LINE> tags['regularizable'] = tags.get('regularizable', True) <NEW_LINE> self.params[param] = set(tag for tag, value in tags.items() if value) <NEW_LINE> return param
The :class:`Layer` class represents a single layer of a neural network. It should be subclassed when implementing new types of layers. Because each layer can keep track of the layer(s) feeding into it, a network's output :class:`Layer` instance can double as a handle to the full network. Parameters ---------- incoming : a :class:`Layer` instance or a tuple The layer feeding into this layer, or the expected input shape. name : a string or None An optional name to attach to this layer.
62599074091ae35668706565
class Vector2d: <NEW_LINE> <INDENT> type_code = 'd' <NEW_LINE> def __init__(self, x, y): <NEW_LINE> <INDENT> self.x = float(x) <NEW_LINE> self.y = float(y) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return (i for i in (self.x, self.y)) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> class_name = type(self).__name__ <NEW_LINE> return '{}({!r}, {!r})'.format(class_name, *self) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(tuple(self)) <NEW_LINE> <DEDENT> def __bytes__(self): <NEW_LINE> <INDENT> return (bytes([ord(self.type_code)]) + bytes(array(self.type_code, self))) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return tuple(self) == tuple(other) <NEW_LINE> <DEDENT> def __abs__(self): <NEW_LINE> <INDENT> return math.hypot(self.x, self.y) <NEW_LINE> <DEDENT> def __bool__(self): <NEW_LINE> <INDENT> return bool(abs(self))
A class to emulate a Python numeric type, in this case a 2d vector
62599074283ffb24f3cf51d7
class Point(TimeStamp): <NEW_LINE> <INDENT> services = [ u"break", u"hold" ] <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> print("Point.__init__() called.") <NEW_LINE> self.offence = 0 <NEW_LINE> self.pull = None <NEW_LINE> self.sequences = [] <NEW_LINE> super(Point, self).__init__(**kwargs) <NEW_LINE> <DEDENT> def current_lines(self): <NEW_LINE> <INDENT> return self.point_lines[self.line_set] <NEW_LINE> <DEDENT> def update_lines(self,lines): <NEW_LINE> <INDENT> self.point_lines.append(lines) <NEW_LINE> self.line_set+=1
Point is a length of sequences between goals.
6259907432920d7e50bc7974
class Tweet_Generator: <NEW_LINE> <INDENT> def __init__(self, markov, starters): <NEW_LINE> <INDENT> self.markov = markov <NEW_LINE> self.starters = starters <NEW_LINE> <DEDENT> def pick_word_from(self): <NEW_LINE> <INDENT> accumulator = 0 <NEW_LINE> seperators = [] <NEW_LINE> words = self.markov.keys() <NEW_LINE> for word, weight in self.markov.items(): <NEW_LINE> <INDENT> accumulator += weight <NEW_LINE> seperators.append(accumulator) <NEW_LINE> <DEDENT> rand_num = random.randint(0, accumulator) <NEW_LINE> for i, s in enumerate(seperators): <NEW_LINE> <INDENT> if rand_num <= s: <NEW_LINE> <INDENT> return words[i] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def generate_sentence(self): <NEW_LINE> <INDENT> sentence_list = [] <NEW_LINE> word_pair = random.choice(self.starters) <NEW_LINE> sentence_list.append(word_pair[0]) <NEW_LINE> sentence_list.append(word_pair[1]) <NEW_LINE> while self.markov[word_pair] != '###': <NEW_LINE> <INDENT> word = self.pick_word_from() <NEW_LINE> sentence_list.append(word) <NEW_LINE> word_pair = (sentence_list[-2], sentence_list[-1]) <NEW_LINE> <DEDENT> return ' '.join(sentence_list)
generates tweets using a pickled markov chain file and sentence starters
6259907497e22403b383c830
class NearestNeighbor(Approach): <NEW_LINE> <INDENT> name = 'Nearest Neighbor Approach' <NEW_LINE> def guess(self, data, *_): <NEW_LINE> <INDENT> return data[0].values
Returns the values of the closest given sample data.
6259907491f36d47f2231b25
class PredictorFactory(object): <NEW_LINE> <INDENT> def __init__(self, sess, model, towers): <NEW_LINE> <INDENT> self.sess = sess <NEW_LINE> self.model = model <NEW_LINE> self.towers = towers <NEW_LINE> self.tower_built = False <NEW_LINE> <DEDENT> def get_predictor(self, input_names, output_names, tower): <NEW_LINE> <INDENT> if not self.tower_built: <NEW_LINE> <INDENT> self._build_predict_tower() <NEW_LINE> <DEDENT> tower = self.towers[tower % len(self.towers)] <NEW_LINE> raw_input_vars = get_tensors_by_names(input_names) <NEW_LINE> output_names = ['{}{}/'.format(PREDICT_TOWER, tower) + n for n in output_names] <NEW_LINE> output_vars = get_tensors_by_names(output_names) <NEW_LINE> return OnlinePredictor(self.sess, raw_input_vars, output_vars) <NEW_LINE> <DEDENT> def _build_predict_tower(self): <NEW_LINE> <INDENT> tf.get_variable_scope().reuse_variables() <NEW_LINE> with tf.name_scope(None), freeze_collection(SUMMARY_BACKUP_KEYS): <NEW_LINE> <INDENT> fn = lambda _: self.model.build_graph(self.model.get_input_vars()) <NEW_LINE> build_multi_tower_prediction_graph(fn, self.towers) <NEW_LINE> <DEDENT> self.tower_built = True
Make predictors for a trainer
625990741b99ca40022901cc
class UserFriendTestCase(APITestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> User.objects.create_user(username="test1",password="test",email="[email protected]") <NEW_LINE> User.objects.create_user(username="test2",password="test",email="[email protected]") <NEW_LINE> <DEDENT> def test_add_friend(self): <NEW_LINE> <INDENT> url = reverse('friendship-list') <NEW_LINE> data = {'to_friend':"test1"} <NEW_LINE> client = APIClient() <NEW_LINE> client.login(username = "test2", password = "test") <NEW_LINE> response = client.post(url, data, format = 'json') <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_201_CREATED) <NEW_LINE> self.assertDictContainsSubset(data, response.data) <NEW_LINE> response = client.get(url,format = 'json') <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_200_OK) <NEW_LINE> self.assertEqual(len(response.data),1) <NEW_LINE> self.assertEqual(response.data[0]['to_friend'],"test1") <NEW_LINE> data = {'to_friend':"test2"} <NEW_LINE> response = client.post(url,data,format='json') <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
test user-friend interaction
625990748e7ae83300eea9bf
class Pinnacle(CrawlSpider): <NEW_LINE> <INDENT> name = 'pinnacle' <NEW_LINE> allowed_domains = ["www.pinnacle.com"] <NEW_LINE> start_urls = ["https://www.pinnacle.com/en/"] <NEW_LINE> rules = ( Rule(LxmlLinkExtractor(allow="odds/match/e-sports/", allow_domains=allowed_domains, restrict_css="ul li.level-2", unique=True), callback='parse_item'), ) <NEW_LINE> def load_page(self, url, sleeptime): <NEW_LINE> <INDENT> driver = webdriver.Firefox() <NEW_LINE> driver.get(url) <NEW_LINE> time.sleep(sleeptime) <NEW_LINE> source = Selector(text=driver.page_source) <NEW_LINE> driver.close() <NEW_LINE> return source <NEW_LINE> <DEDENT> def parse_item(self, response): <NEW_LINE> <INDENT> sleeptime = 2 <NEW_LINE> game_name = response.xpath('//header//div[@class="breadcrumbs"]/a[3]/text()').extract_first() <NEW_LINE> if game_name == "New Markets": <NEW_LINE> <INDENT> game_name = response.xpath('//h1[@class="sport-title"]/text()').extract_first() <NEW_LINE> game_name = game_name.split(" ")[1] <NEW_LINE> <DEDENT> source = self.load_page(response.url, sleeptime) <NEW_LINE> events_table = source.xpath('//div[@ng-repeat="date in currentPeriod.dates"]') <NEW_LINE> for table in events_table: <NEW_LINE> <INDENT> item = Event() <NEW_LINE> rows = table.xpath('.//table[@class="odds-data"]//tbody') <NEW_LINE> date_string = table.xpath('.//div[@class="toolbar"]//span[2]/text()').extract_first() <NEW_LINE> for row in rows: <NEW_LINE> <INDENT> time_string = row.xpath('.//tr[1]//td[@class="game-time ng-scope"]//span/text()').extract_first() <NEW_LINE> site_date_string = date_string + time_string <NEW_LINE> player1 = row.xpath('.//tr[1]//td[@class="game-name name"]//span/text()').extract_first() <NEW_LINE> odds1 = row.xpath('.//tr[1]//td[@class="oddTip game-moneyline"]//span/text()').extract_first() <NEW_LINE> try: <NEW_LINE> <INDENT> odds1 = float(odds1.strip()) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> player2 = row.xpath('.//tr[2]//td[@class="game-name name"]//span/text()').extract_first() <NEW_LINE> odds2 = row.xpath('.//tr[2]//td[@class="oddTip game-moneyline"]//span/text()').extract_first() <NEW_LINE> try: <NEW_LINE> <INDENT> odds2 = float(odds2.strip()) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> item['game'] = game_name <NEW_LINE> item['date'] = site_date_string <NEW_LINE> item['player1'] = player1 <NEW_LINE> item['odds1'] = odds1 <NEW_LINE> item['player2'] = player2 <NEW_LINE> item['odds2'] = odds2 <NEW_LINE> yield item
Spider for extracting links, following them and parsing data from response. Note: we using here a generic scrapy spider "CrawlSpider" (instead of "scrapy.Spider") and set of rules to extract only "required" urls.
625990745fc7496912d48f00
class Translation(object): <NEW_LINE> <INDENT> def __init__(self, translation_output): <NEW_LINE> <INDENT> self.translation_output = translation_output <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _from_dict(cls, _dict): <NEW_LINE> <INDENT> args = {} <NEW_LINE> if 'translation' in _dict or 'translation_output' in _dict: <NEW_LINE> <INDENT> args['translation_output'] = _dict.get('translation') or _dict.get( 'translation_output') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError( 'Required property \'translation\' not present in Translation JSON' ) <NEW_LINE> <DEDENT> return cls(**args) <NEW_LINE> <DEDENT> def _to_dict(self): <NEW_LINE> <INDENT> _dict = {} <NEW_LINE> if hasattr( self, 'translation_output') and self.translation_output is not None: <NEW_LINE> <INDENT> _dict['translation'] = self.translation_output <NEW_LINE> <DEDENT> return _dict <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return json.dumps(self._to_dict(), indent=2) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, self.__class__): <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
Translation. :attr str translation_output: Translation output in UTF-8.
625990747d43ff24874280aa
class GISServerManager: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.vampire = VampireDefaults.VampireDefaults() <NEW_LINE> return <NEW_LINE> <DEDENT> def upload_to_GIS_server(self, product, input_file, input_dir, input_pattern, start_date, end_date, vp): <NEW_LINE> <INDENT> gisserver.upload_to_GIS_server(product, input_file, input_dir, input_pattern, start_date, end_date, vp)
Base Class for managing uploading of products to GIS server
625990744f88993c371f11b7
class Assignment(base.Assignment): <NEW_LINE> <INDENT> implements(IGalleryPortlet) <NEW_LINE> def __init__(self, path='/', count=5): <NEW_LINE> <INDENT> self.count = count <NEW_LINE> self.path = path <NEW_LINE> <DEDENT> @property <NEW_LINE> def title(self): <NEW_LINE> <INDENT> return "Gallery Portlet" <NEW_LINE> <DEDENT> def getGallery(self, context): <NEW_LINE> <INDENT> catalog = getToolByName(context, 'portal_catalog') <NEW_LINE> result = catalog(portal_type='Image Gallery', path={ 'query': self.path, 'depth': 0, }) <NEW_LINE> if len(result) == 1: <NEW_LINE> <INDENT> return result[0].getObject() <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def getImages(self, context): <NEW_LINE> <INDENT> catalog = getToolByName(context, 'portal_catalog') <NEW_LINE> results = catalog(portal_type='Image', path={ 'query': self.path, 'depth': 1, }) <NEW_LINE> count = self.count <NEW_LINE> if count > len(results): <NEW_LINE> <INDENT> count = len(results) <NEW_LINE> <DEDENT> return sample([result.getObject() for result in results], count)
Portlet assignment. This is what is actually managed through the portlets UI and associated with columns.
62599074442bda511e95d9ee
class User(BaseModel): <NEW_LINE> <INDENT> email = "" <NEW_LINE> password = "" <NEW_LINE> first_name = "" <NEW_LINE> last_name = ""
class user
625990744527f215b58eb637
class ResultMixin(object): <NEW_LINE> <INDENT> @property <NEW_LINE> def username(self): <NEW_LINE> <INDENT> netloc = self.netloc <NEW_LINE> if "@" in netloc: <NEW_LINE> <INDENT> userinfo = netloc.rsplit("@", 1)[0] <NEW_LINE> if ":" in userinfo: <NEW_LINE> <INDENT> userinfo = userinfo.split(":", 1)[0] <NEW_LINE> <DEDENT> return userinfo <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> @property <NEW_LINE> def password(self): <NEW_LINE> <INDENT> netloc = self.netloc <NEW_LINE> if "@" in netloc: <NEW_LINE> <INDENT> userinfo = netloc.rsplit("@", 1)[0] <NEW_LINE> if ":" in userinfo: <NEW_LINE> <INDENT> return userinfo.split(":", 1)[1] <NEW_LINE> <DEDENT> <DEDENT> return None <NEW_LINE> <DEDENT> @property <NEW_LINE> def hostname(self): <NEW_LINE> <INDENT> netloc = self.netloc.split('@')[-1] <NEW_LINE> if '[' in netloc and ']' in netloc: <NEW_LINE> <INDENT> return netloc.split(']')[0][1:].lower() <NEW_LINE> <DEDENT> elif ':' in netloc: <NEW_LINE> <INDENT> return netloc.split(':')[0].lower() <NEW_LINE> <DEDENT> elif netloc == '': <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return netloc.lower() <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def port(self): <NEW_LINE> <INDENT> netloc = self.netloc.split('@')[-1].split(']')[-1] <NEW_LINE> if ':' in netloc: <NEW_LINE> <INDENT> port = netloc.split(':')[1] <NEW_LINE> if port: <NEW_LINE> <INDENT> port = int(port, 10) <NEW_LINE> if (0 <= port <= 65535): <NEW_LINE> <INDENT> return port <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return None
Shared methods for the parsed result objects.
625990747d847024c075dd08
class WebUtilsTest(unittest.TestCase): <NEW_LINE> <INDENT> def test_cors(self): <NEW_LINE> <INDENT> app = flask.Flask(__name__) <NEW_LINE> app.testing = True <NEW_LINE> @app.route('/xxx') <NEW_LINE> @webutils.cors(origin='*', content_type='application/json') <NEW_LINE> def handler_unused(): <NEW_LINE> <INDENT> return flask.jsonify({'apps': 1}) <NEW_LINE> <DEDENT> resp = app.test_client().get('/xxx') <NEW_LINE> self.assertEqual(resp.mimetype, 'application/json') <NEW_LINE> self.assertEqual({'apps': 1}, flask.json.loads(resp.data)) <NEW_LINE> self.assertIn('Access-Control-Allow-Origin', resp.headers) <NEW_LINE> self.assertEqual('*', resp.headers['Access-Control-Allow-Origin']) <NEW_LINE> <DEDENT> def test_wants_json_resp(self): <NEW_LINE> <INDENT> app = flask.Flask(__name__) <NEW_LINE> app.testing = True <NEW_LINE> with app.test_request_context(headers=[('Accept', 'application/json, ' 'text/plain')]): <NEW_LINE> <INDENT> self.assertTrue(webutils.wants_json_resp(flask.request)) <NEW_LINE> <DEDENT> with app.test_request_context(headers=[('Accept', 'text/html; q=1.0, ' 'text/*; q=0.8, image/gif; ' 'q=0.6, image/jpeg;')]): <NEW_LINE> <INDENT> self.assertFalse(webutils.wants_json_resp(flask.request)) <NEW_LINE> <DEDENT> <DEDENT> def test_namespace(self): <NEW_LINE> <INDENT> m_api = mock.Mock() <NEW_LINE> def noop(*args, **kwargs): <NEW_LINE> <INDENT> return args <NEW_LINE> <DEDENT> m_api.namespace = noop <NEW_LINE> (ns,) = webutils.namespace(m_api, 'treadmill.rest.api.state', 'foo') <NEW_LINE> self.assertEqual(ns, 'state')
Tests for teadmill.webutils.
6259907456b00c62f0fb41fe
class ForkedClient(): <NEW_LINE> <INDENT> def __init__(self, ip, port): <NEW_LINE> <INDENT> self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) <NEW_LINE> self.sock.connect((ip, port)) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> current_process_id = os.getpid() <NEW_LINE> print('PID %s Sending echo message to the server : "%s"' % (str(current_process_id), ECHO_MSG)) <NEW_LINE> sent_data_length = self.sock.send(ECHO_MSG.encode("utf-8")) <NEW_LINE> print("Sent: %d characters so far..." % sent_data_length) <NEW_LINE> response = self.sock.recv(BUF_SIZE) <NEW_LINE> print("PID %s received: %s" % (str(current_process_id), response.decode("utf-8")[5:])) <NEW_LINE> <DEDENT> def shutdown(self): <NEW_LINE> <INDENT> self.sock.close()
A client for the forking server
625990743317a56b869bf1dc
class UserTheme(Theme): <NEW_LINE> <INDENT> REQUIRED_CONFIG_KEYS = ['docclass', 'wrapperclass'] <NEW_LINE> OPTIONAL_CONFIG_KEYS = ['papersize', 'pointsize', 'toplevel_sectioning'] <NEW_LINE> def __init__(self, name: str, filename: str) -> None: <NEW_LINE> <INDENT> super().__init__(name) <NEW_LINE> self.config = configparser.RawConfigParser() <NEW_LINE> self.config.read(path.join(filename)) <NEW_LINE> for key in self.REQUIRED_CONFIG_KEYS: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> value = self.config.get('theme', key) <NEW_LINE> setattr(self, key, value) <NEW_LINE> <DEDENT> except configparser.NoSectionError: <NEW_LINE> <INDENT> raise ThemeError(__('%r doesn\'t have "theme" setting') % filename) <NEW_LINE> <DEDENT> except configparser.NoOptionError as exc: <NEW_LINE> <INDENT> raise ThemeError(__('%r doesn\'t have "%s" setting') % (filename, exc.args[0])) <NEW_LINE> <DEDENT> <DEDENT> for key in self.OPTIONAL_CONFIG_KEYS: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> value = self.config.get('theme', key) <NEW_LINE> setattr(self, key, value) <NEW_LINE> <DEDENT> except configparser.NoOptionError: <NEW_LINE> <INDENT> pass
A user defined LaTeX theme.
625990749c8ee82313040e1e
class TestFieldEActivesessionWeekdaystart(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testFieldEActivesessionWeekdaystart(self): <NEW_LINE> <INDENT> pass
FieldEActivesessionWeekdaystart unit test stubs
62599074379a373c97d9a950
class TestResponseContainerUserGroupModel(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testResponseContainerUserGroupModel(self): <NEW_LINE> <INDENT> pass
ResponseContainerUserGroupModel unit test stubs
6259907456ac1b37e6303979
class com_Item: <NEW_LINE> <INDENT> def __init__(self, weight = 0.0, volume = 0.0, use_function = None, value = None): <NEW_LINE> <INDENT> self.weight = weight <NEW_LINE> self.volume = volume <NEW_LINE> self.value = value <NEW_LINE> self.use_function = use_function <NEW_LINE> <DEDENT> def pick_up(self, actor): <NEW_LINE> <INDENT> if actor.container: <NEW_LINE> <INDENT> if actor.container.volume + self.volume > actor.container.max_volume: <NEW_LINE> <INDENT> game_message("Not enough room to pick up") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> game_message('Picking up') <NEW_LINE> actor.container.inventory.append(self.owner) <NEW_LINE> self.owner.animation_destroy() <NEW_LINE> GAME.current_objects.remove(self.owner) <NEW_LINE> self.current_container = actor.container <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def drop(self, new_x, new_y): <NEW_LINE> <INDENT> GAME.current_objects.append(self.owner) <NEW_LINE> self.owner.animation_init() <NEW_LINE> self.current_container.inventory.remove(self.owner) <NEW_LINE> self.owner.x = new_x <NEW_LINE> self.owner.y = new_y <NEW_LINE> game_message("Item Dropped!") <NEW_LINE> <DEDENT> def use(self): <NEW_LINE> <INDENT> if self.owner.equipment: <NEW_LINE> <INDENT> self.owner.equipment.toggle_equip() <NEW_LINE> return <NEW_LINE> <DEDENT> if self.use_function: <NEW_LINE> <INDENT> result = self.use_function(self.current_container.owner, self.value) <NEW_LINE> if result is not None: <NEW_LINE> <INDENT> print("use_function failed") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.current_container.inventory.remove(self.owner)
Items are components that can be picked up and used. Attributes: weight (arg, float): how much does the item weigh volume (arg, float): how much space does the item take up
625990748e7ae83300eea9c0
class ConnectivityPass(Pass): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(ConnectivityPass, self).__init__(core, connectivity) <NEW_LINE> self.edgeless_top = normpath('continuity') <NEW_LINE> self.edgeless_block_dir = self.src_block_dir.replace(core, continuity) <NEW_LINE> self.block_subpath = self.dst_block_dir[len(self.dst_top) + 1:] <NEW_LINE> self.template_top = os.path.join(self.repack_dir, 'ctm_templates') <NEW_LINE> <DEDENT> def find_change(self, change_name): <NEW_LINE> <INDENT> return ConnectedTextureChange(change_name, self)
The pass for the Connectivity (CTM) pass. Each continuity texture requires both edged and edgeless blocks. The edgless blocks are taken from the previously-generated Continuity pack.
62599074627d3e7fe0e087b7
class plan_t: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.title = None; <NEW_LINE> self.wpts = []; <NEW_LINE> <DEDENT> def append(self, wpt): <NEW_LINE> <INDENT> self.wpts.append(wpt);
plan_t is a flight plan.
62599074fff4ab517ebcf145
class IPatternsSettingsRenderer(Interface): <NEW_LINE> <INDENT> pass
Interface for the adapter that renders the settings for patterns
625990741b99ca40022901cd
class JobModel(SubModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> model = [ ("user", "user", str, ""), ("file", ("file", "display"), str, ""), ("path", ("file", "path"), str, ""), ("size", ("file", "size"), int, 0), ("estTime", ("estimatedPrintTime"), float, 0.0), ("fl0", ("filament", "tool0", "length"), float, 0.0), ("fl1", ("filament", "tool1", "length"), float, 0.0), ] <NEW_LINE> super().__init__(model)
A Job Model.
625990745fc7496912d48f01
class Monsoon(_DevlibContinuousEnergyMeter): <NEW_LINE> <INDENT> def __init__(self, target, conf, res_dir): <NEW_LINE> <INDENT> super(Monsoon, self).__init__(target, res_dir) <NEW_LINE> self._instrument = devlib.MonsoonInstrument(self._target, **conf['conf']) <NEW_LINE> self._instrument.reset()
Monsoon Solutions energy monitor
625990743539df3088ecdbc6
class TestAnonymousSurvey(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> question = "What language did you first learn to speak?" <NEW_LINE> self.my_survey = AnonymousSurvey(question) <NEW_LINE> self.responses = ['English', 'Spanish', 'Mandarin'] <NEW_LINE> <DEDENT> def test_store_single_response(self): <NEW_LINE> <INDENT> self.my_survey.store_response(self.responses[0]) <NEW_LINE> self.assertIn(self.responses[0], self.my_survey.response) <NEW_LINE> <DEDENT> def test_store_three_response(self): <NEW_LINE> <INDENT> for response in self.responses: <NEW_LINE> <INDENT> self.my_survey.store_response(response) <NEW_LINE> <DEDENT> for response in self.responses: <NEW_LINE> <INDENT> self.assertIn(response, self.my_survey.response)
Tests for class AnonymousSurvey
62599074aad79263cf4300e7
class FLS(Enum): <NEW_LINE> <INDENT> FLS_2 = 2 <NEW_LINE> FLS_4 = 4 <NEW_LINE> FLS_8 = 8 <NEW_LINE> FLS_16 = 16
Allowed parameters' values for FLS. Accelerometer's full scale.
625990744f6381625f19a142
class Student(models.Model): <NEW_LINE> <INDENT> customer = models.ForeignKey('CustomerInfo',on_delete=None) <NEW_LINE> class_grade = models.ManyToManyField('ClassList')
学员表
6259907456b00c62f0fb4200
class ModernaFragment5(ModernaFragment): <NEW_LINE> <INDENT> def __init__(self, struc, anchor5=None, new_sequence=None, sup_r5=LIR_SUPERPOSITION5, build_rule=ALL_FROM_MODEL, keep=keep_nothing, strict=True): <NEW_LINE> <INDENT> ModernaFragment.__init__(self, struc, new_sequence, keep, strict) <NEW_LINE> self.anchor5 = AnchorResidue(anchor5, list(self.struc)[0], sup_r5, build_rule) <NEW_LINE> <DEDENT> @property <NEW_LINE> def anchor_residues(self): <NEW_LINE> <INDENT> return [self.anchor5] <NEW_LINE> <DEDENT> @property <NEW_LINE> def nonanchor_residues(self): <NEW_LINE> <INDENT> return [r for r in self.struc][1:] <NEW_LINE> <DEDENT> def get_resi_to_remove(self, struc): <NEW_LINE> <INDENT> return [self.anchor5.fixed_id] + struc.find_residues_in_range(self.anchor5.fixed_id) <NEW_LINE> <DEDENT> def fix_backbone(self): <NEW_LINE> <INDENT> self.struc.fix_backbone_after_resi(self.struc[self.anchor5.fixed_id])
Fragment connected to the model by one residue on its 5' end.
62599074dd821e528d6da61a
class Bayes(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def predict(self,predict_ex): <NEW_LINE> <INDENT> probs = [] <NEW_LINE> probs.append(self.get_probability_per_class(predict_ex, ut.YES)*self.get_probability_for_class(ut.YES)) <NEW_LINE> probs.append(self.get_probability_per_class(predict_ex, ut.NO)*self.get_probability_for_class(ut.NO)) <NEW_LINE> return self.argmax(probs) <NEW_LINE> <DEDENT> def get_probability_per_class(self, predict_ex, tag): <NEW_LINE> <INDENT> multiply = 1 <NEW_LINE> for feature in ut.FEATURES_LIST: <NEW_LINE> <INDENT> multiply *= self.get_probability_for_feature_per_class(feature, tag, predict_ex[feature]) <NEW_LINE> <DEDENT> return multiply <NEW_LINE> <DEDENT> def get_probability_for_feature_per_class(self,feature, tag, feature_val): <NEW_LINE> <INDENT> examples_from_this_tag = ut.EXAMPLES_DICT[tag] <NEW_LINE> count = 0 <NEW_LINE> for example_dict in examples_from_this_tag: <NEW_LINE> <INDENT> if example_dict[feature] == feature_val: <NEW_LINE> <INDENT> count +=1 <NEW_LINE> <DEDENT> <DEDENT> numerator = count + 1 <NEW_LINE> denominator = len(examples_from_this_tag) + len(ut.FEATURES_VALS_DICT[feature]) <NEW_LINE> return float(numerator)/float(denominator) <NEW_LINE> <DEDENT> def argmax(self,probs): <NEW_LINE> <INDENT> if probs[0]==probs[1]: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> if probs[0]>probs[1]: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return ut.YES if probs[0] >= probs[1] else ut.NO <NEW_LINE> <DEDENT> def get_probability_for_class(self,tag): <NEW_LINE> <INDENT> total_examples_num = len(ut.EXAMPLES_LIST) <NEW_LINE> number_of_examples_of_this_tag = len(ut.EXAMPLES_DICT[tag]) <NEW_LINE> return float(number_of_examples_of_this_tag)/float(total_examples_num) <NEW_LINE> <DEDENT> def train(self): <NEW_LINE> <INDENT> y_list = [] <NEW_LINE> y_hat_list = [] <NEW_LINE> for ex_dict in ut.EXAMPLES_LIST: <NEW_LINE> <INDENT> y_list.append(ex_dict[1]) <NEW_LINE> y_hat_list.append(self.predict(ex_dict[0])) <NEW_LINE> <DEDENT> acc = ut.compute_accuracy(y_hat_list, y_list) <NEW_LINE> return acc <NEW_LINE> <DEDENT> def test(self): <NEW_LINE> <INDENT> y_list = [] <NEW_LINE> y_hat_list = [] <NEW_LINE> for ex_dict in ut.TEST_LIST: <NEW_LINE> <INDENT> y_list.append(ex_dict[1]) <NEW_LINE> y_hat_list.append(self.predict(ex_dict[0])) <NEW_LINE> <DEDENT> acc = ut.compute_accuracy(y_hat_list, y_list) <NEW_LINE> return y_hat_list,acc
constructor.
62599074e1aae11d1e7cf4a6
class TestMetricUnit(unittest.TestCase): <NEW_LINE> <INDENT> def test_has_same_unit_with(self): <NEW_LINE> <INDENT> unit1 = MetricUnit('kg m/s^2') <NEW_LINE> unit2 = MetricUnit('m s^-2 kg') <NEW_LINE> self.assertEqual(unit1, unit2) <NEW_LINE> <DEDENT> def test_to_SI_base(self): <NEW_LINE> <INDENT> unit = MetricUnit('N') <NEW_LINE> self.assertEqual(unit.to_SI_base(), MetricUnit('kg m/s^2')) <NEW_LINE> unit = MetricUnit('cm/s') <NEW_LINE> self.assertEqual( str(unit.to_SI_base()), '1.0e-02 m/s') <NEW_LINE> self.assertEqual( str(MetricUnit('J s/N').to_SI_base()), 'm s') <NEW_LINE> <DEDENT> def test_is_dimensionless(self): <NEW_LINE> <INDENT> unit = MetricUnit('N/(kg m/s^2)') <NEW_LINE> self.assertTrue(unit.is_dimensionless()) <NEW_LINE> <DEDENT> def test_is_equivalent_to(self): <NEW_LINE> <INDENT> unit = MetricUnit('N') <NEW_LINE> self.assertTrue(unit.is_equivalent_to('kg m/s^2')) <NEW_LINE> <DEDENT> def test_to(self): <NEW_LINE> <INDENT> self.assertEqual(str(MetricUnit('kg^2 m/s^2').to('N')), 'N kg') <NEW_LINE> <DEDENT> def test_to_only(self): <NEW_LINE> <INDENT> unit = MetricUnit('N') <NEW_LINE> self.assertEqual(str(unit.to_only('kg', 'm', 's')), 'kg m/s^2') <NEW_LINE> self.assertEqual(unit.to_only('kg', 'm'), None) <NEW_LINE> <DEDENT> def test_to_prefix(self): <NEW_LINE> <INDENT> self.assertEqual( str(MetricUnit('kg km^2 / s^2').to_prefix('cm')), '1.0e+10 kg cm^2/s^2') <NEW_LINE> self.assertEqual( str(MetricUnit('kg m/s^2').to_prefix('g', 'cm')), '1.0e+05 g cm/s^2') <NEW_LINE> <DEDENT> def power(self): <NEW_LINE> <INDENT> self.assertEqual( str(MetricUnit('kg').power(3), 'kg^3') )
A test case for MetricUnit class.
62599074be8e80087fbc09c2
class TestTitle: <NEW_LINE> <INDENT> def test_title_returns_str(self): <NEW_LINE> <INDENT> assert isinstance(filters.title('foo bar'), str) <NEW_LINE> <DEDENT> def test_title_word(self): <NEW_LINE> <INDENT> assert filters.title('foo bar') == 'Foo bar' <NEW_LINE> <DEDENT> def test_title_capitalize(self): <NEW_LINE> <INDENT> assert filters.title('foo bar', capitalize=True) == 'Foo Bar' <NEW_LINE> <DEDENT> def test_title_capitalize_sentence(self): <NEW_LINE> <INDENT> res = filters.title('the quick brown fox... ah forget it', capitalize=True) <NEW_LINE> expected = 'The Quick Brown Fox... Ah Forget It' <NEW_LINE> assert res == expected <NEW_LINE> <DEDENT> def test_title_none(self): <NEW_LINE> <INDENT> assert filters.questionize_label(None) == ''
All tests for title function.
62599074ad47b63b2c5a917e
class UpdateEditChannelMessage(TLObject): <NEW_LINE> <INDENT> __slots__: List[str] = ["message", "pts", "pts_count"] <NEW_LINE> ID = 0x1b3f4df7 <NEW_LINE> QUALNAME = "types.UpdateEditChannelMessage" <NEW_LINE> def __init__(self, *, message: "raw.base.Message", pts: int, pts_count: int) -> None: <NEW_LINE> <INDENT> self.message = message <NEW_LINE> self.pts = pts <NEW_LINE> self.pts_count = pts_count <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def read(data: BytesIO, *args: Any) -> "UpdateEditChannelMessage": <NEW_LINE> <INDENT> message = TLObject.read(data) <NEW_LINE> pts = Int.read(data) <NEW_LINE> pts_count = Int.read(data) <NEW_LINE> return UpdateEditChannelMessage(message=message, pts=pts, pts_count=pts_count) <NEW_LINE> <DEDENT> def write(self) -> bytes: <NEW_LINE> <INDENT> data = BytesIO() <NEW_LINE> data.write(Int(self.ID, False)) <NEW_LINE> data.write(self.message.write()) <NEW_LINE> data.write(Int(self.pts)) <NEW_LINE> data.write(Int(self.pts_count)) <NEW_LINE> return data.getvalue()
This object is a constructor of the base type :obj:`~pyrogram.raw.base.Update`. Details: - Layer: ``122`` - ID: ``0x1b3f4df7`` Parameters: message: :obj:`Message <pyrogram.raw.base.Message>` pts: ``int`` ``32-bit`` pts_count: ``int`` ``32-bit``
625990744a966d76dd5f081b
class CTCTrainer(Trainer): <NEW_LINE> <INDENT> def compute_loss(self, targets, logits, logit_seq_length, target_seq_length): <NEW_LINE> <INDENT> batch_size = int(target_seq_length.get_shape()[0]) <NEW_LINE> indices = tf.concat(0, [tf.concat(1, [tf.tile([s], target_seq_length[s]) , tf.range(target_seq_length[s])]) for s in range(len(batch_size))]) <NEW_LINE> values = tf.reshape(seq_convertors.seq2nonseq(logits, logit_seq_length), [-1]) <NEW_LINE> shape = [batch_size, len(targets)] <NEW_LINE> sparse_targets = tf.SparseTensor(indices, values, shape) <NEW_LINE> tf.nn.ctc_loss(tf.pack(logits), sparse_targets, logit_seq_length)
A trainer that minimises the CTC loss, the output sequences
62599074aad79263cf4300e8
class InstanceGroupsScopedList(_messages.Message): <NEW_LINE> <INDENT> class WarningValue(_messages.Message): <NEW_LINE> <INDENT> class CodeValueValuesEnum(_messages.Enum): <NEW_LINE> <INDENT> CLEANUP_FAILED = 0 <NEW_LINE> DEPRECATED_RESOURCE_USED = 1 <NEW_LINE> DISK_SIZE_LARGER_THAN_IMAGE_SIZE = 2 <NEW_LINE> FIELD_VALUE_OVERRIDEN = 3 <NEW_LINE> INJECTED_KERNELS_DEPRECATED = 4 <NEW_LINE> NEXT_HOP_ADDRESS_NOT_ASSIGNED = 5 <NEW_LINE> NEXT_HOP_CANNOT_IP_FORWARD = 6 <NEW_LINE> NEXT_HOP_INSTANCE_NOT_FOUND = 7 <NEW_LINE> NEXT_HOP_INSTANCE_NOT_ON_NETWORK = 8 <NEW_LINE> NEXT_HOP_NOT_RUNNING = 9 <NEW_LINE> NOT_CRITICAL_ERROR = 10 <NEW_LINE> NO_RESULTS_ON_PAGE = 11 <NEW_LINE> REQUIRED_TOS_AGREEMENT = 12 <NEW_LINE> RESOURCE_IN_USE_BY_OTHER_RESOURCE_WARNING = 13 <NEW_LINE> RESOURCE_NOT_DELETED = 14 <NEW_LINE> SINGLE_INSTANCE_PROPERTY_TEMPLATE = 15 <NEW_LINE> UNREACHABLE = 16 <NEW_LINE> <DEDENT> class DataValueListEntry(_messages.Message): <NEW_LINE> <INDENT> key = _messages.StringField(1) <NEW_LINE> value = _messages.StringField(2) <NEW_LINE> <DEDENT> code = _messages.EnumField('CodeValueValuesEnum', 1) <NEW_LINE> data = _messages.MessageField('DataValueListEntry', 2, repeated=True) <NEW_LINE> message = _messages.StringField(3) <NEW_LINE> <DEDENT> instanceGroups = _messages.MessageField('InstanceGroup', 1, repeated=True) <NEW_LINE> warning = _messages.MessageField('WarningValue', 2)
A InstanceGroupsScopedList object. Messages: WarningValue: [Output Only] An informational warning that replaces the list of instance groups when the list is empty. Fields: instanceGroups: [Output Only] The list of instance groups that are contained in this scope. warning: [Output Only] An informational warning that replaces the list of instance groups when the list is empty.
6259907401c39578d7f143cd
class PigOperator(BaseOperator): <NEW_LINE> <INDENT> template_fields = ('pig',) <NEW_LINE> template_ext = ('.pig', '.piglatin',) <NEW_LINE> ui_color = '#f0e4ec' <NEW_LINE> @apply_defaults <NEW_LINE> def __init__( self, pig: str, pig_cli_conn_id: str = 'pig_cli_default', pigparams_jinja_translate: bool = False, pig_opts: Optional[str] = None, *args, **kwargs) -> None: <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> self.pigparams_jinja_translate = pigparams_jinja_translate <NEW_LINE> self.pig = pig <NEW_LINE> self.pig_cli_conn_id = pig_cli_conn_id <NEW_LINE> self.pig_opts = pig_opts <NEW_LINE> <DEDENT> def get_hook(self): <NEW_LINE> <INDENT> return PigCliHook(pig_cli_conn_id=self.pig_cli_conn_id) <NEW_LINE> <DEDENT> def prepare_template(self): <NEW_LINE> <INDENT> if self.pigparams_jinja_translate: <NEW_LINE> <INDENT> self.pig = re.sub( r"(\$([a-zA-Z_][a-zA-Z0-9_]*))", r"{{ \g<2> }}", self.pig) <NEW_LINE> <DEDENT> <DEDENT> def execute(self, context): <NEW_LINE> <INDENT> self.log.info('Executing: %s', self.pig) <NEW_LINE> self.hook = self.get_hook() <NEW_LINE> self.hook.run_cli(pig=self.pig, pig_opts=self.pig_opts) <NEW_LINE> <DEDENT> def on_kill(self): <NEW_LINE> <INDENT> self.hook.kill()
Executes pig script. :param pig: the pig latin script to be executed. (templated) :type pig: str :param pig_cli_conn_id: reference to the Hive database :type pig_cli_conn_id: str :param pigparams_jinja_translate: when True, pig params-type templating ${var} gets translated into jinja-type templating {{ var }}. Note that you may want to use this along with the ``DAG(user_defined_macros=myargs)`` parameter. View the DAG object documentation for more details. :type pigparams_jinja_translate: bool :param pig_opts: pig options, such as: -x tez, -useHCatalog, ... :type pig_opts: str
625990741b99ca40022901ce
class Pessoa: <NEW_LINE> <INDENT> def __init__(self, nome: str, idade: int): <NEW_LINE> <INDENT> self.nome = nome <NEW_LINE> self.dade = idade
- Classe para representar os dados de uma **Pessoa**
62599074009cb60464d02e6c
class IdentifierType(db.Model): <NEW_LINE> <INDENT> id = db.Column( db.Integer, primary_key=True ) <NEW_LINE> name = db.Column( db.String, nullable=False, unique=True, index=True ) <NEW_LINE> description = db.Column( db.String, nullable=False ) <NEW_LINE> url = db.Column( db.String, nullable=False ) <NEW_LINE> example_value = db.Column( db.String, nullable=False ) <NEW_LINE> example_url = db.Column( db.String, nullable=False ) <NEW_LINE> claimant_id = db.Column( db.Integer, db.ForeignKey('claimant.id') ) <NEW_LINE> subject = db.relationship( 'Claim', backref='subject_type', primaryjoin="Claim.subject_type_id == IdentifierType.id", lazy='dynamic' ) <NEW_LINE> object = db.relationship( 'Claim', backref='object_type', primaryjoin="Claim.object_type_id == IdentifierType.id", lazy='dynamic' ) <NEW_LINE> eqid = db.relationship( 'EquivalentIdentifier', backref='type', primaryjoin="EquivalentIdentifier.type_id == IdentifierType.id", lazy='dynamic' ) <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return '<IdentifierType {}>'.format(self.name)
Represents an identifier type. An Identifier Type is a persistent identifier type that can be used in claims by claimants.
62599074f548e778e596cec0
class BaseSchema(base_schema.ObjType, MappingSchema): <NEW_LINE> <INDENT> on = SchemaNode(Bool(), missing=drop) <NEW_LINE> output_zero_step = SchemaNode(Bool()) <NEW_LINE> output_last_step = SchemaNode(Bool()) <NEW_LINE> output_timestep = SchemaNode(extend_colander.TimeDelta(), missing=drop) <NEW_LINE> output_start_time = SchemaNode(extend_colander.LocalDateTime(), validator=validators.convertible_to_seconds, missing=drop)
Base schema for all outputters - they all contain the following
625990741f5feb6acb164526
class DjangoBookWriter(IWriter): <NEW_LINE> <INDENT> def __init__(self, exporter, _, **keywords): <NEW_LINE> <INDENT> self.importer = exporter <NEW_LINE> self._keywords = keywords <NEW_LINE> <DEDENT> def create_sheet(self, sheet_name): <NEW_LINE> <INDENT> sheet_writer = None <NEW_LINE> model = self.importer.get(sheet_name) <NEW_LINE> if model: <NEW_LINE> <INDENT> sheet_writer = DjangoModelWriter( self.importer, model, batch_size=self._keywords.get("batch_size", None), bulk_save=self._keywords.get("bulk_save", True), ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception( "Sheet: %s does not match any given models." % sheet_name + "Please be aware of case sensitivity." ) <NEW_LINE> <DEDENT> return sheet_writer <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> pass
write data into django models
6259907423849d37ff8529e9
class PrimeNumbers(unittest.TestCase): <NEW_LINE> <INDENT> def test_case(self): <NEW_LINE> <INDENT> generator = primes.prime_numbers() <NEW_LINE> first_ten_primes = [next(generator) for x in range(10)] <NEW_LINE> canonical_values = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] <NEW_LINE> self.assertEqual(first_ten_primes, canonical_values)
tests for Utilities.primes.prime_numbers
625990745fdd1c0f98e5f8b0
class CurvedRefraction(RayTransferMatrix): <NEW_LINE> <INDENT> def __init__(self, R, n1, n2): <NEW_LINE> <INDENT> R, n1 , n2 = sympify((R, n1, n2)) <NEW_LINE> RayTransferMatrix.__init__(self, 1, 0, (n1-n2)/R/n2, n1/n2)
Ray Transfer Matrix for refraction on curved interface. Parameters ========== R: radius of curvature (positive for concave), n1: refractive index of one medium n2: refractive index of other medium See Also ======== RayTransferMatrix Examples ======== >>> from sympy.physics.gaussopt import CurvedRefraction >>> from sympy import symbols >>> R, n1, n2 = symbols('R n1 n2') >>> CurvedRefraction(R, n1, n2) [ 1, 0] [(n1 - n2)/(R*n2), n1/n2]
62599074379a373c97d9a954
class IContentNavigation(IPortletDataProvider): <NEW_LINE> <INDENT> pass
Memberships Portlet
625990747047854f46340ceb
class WaterbutlerLink(Link): <NEW_LINE> <INDENT> def __init__(self, must_be_file=None, must_be_folder=None, **kwargs): <NEW_LINE> <INDENT> self.kwargs = kwargs <NEW_LINE> self.must_be_file = must_be_file <NEW_LINE> self.must_be_folder = must_be_folder <NEW_LINE> <DEDENT> def resolve_url(self, obj, request): <NEW_LINE> <INDENT> if self.must_be_folder is True and not obj.path.endswith('/'): <NEW_LINE> <INDENT> raise SkipField <NEW_LINE> <DEDENT> if self.must_be_file is True and obj.path.endswith('/'): <NEW_LINE> <INDENT> raise SkipField <NEW_LINE> <DEDENT> url = website_utils.waterbutler_api_url_for(obj.node._id, obj.provider, obj.path, **self.kwargs) <NEW_LINE> if not url: <NEW_LINE> <INDENT> raise SkipField <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return url
Link object to use in conjunction with Links field. Builds a Waterbutler URL for files.
62599074a05bb46b3848bdc4
@implementer_if_needed(INativeString, IFromUnicode, IFromBytes) <NEW_LINE> class NativeString(Text if PY3 else Bytes): <NEW_LINE> <INDENT> _type = str <NEW_LINE> if PY3: <NEW_LINE> <INDENT> def fromBytes(self, value): <NEW_LINE> <INDENT> value = value.decode('utf-8') <NEW_LINE> self.validate(value) <NEW_LINE> return value
A native string is always the type `str`. In addition to :class:`~zope.schema.interfaces.INativeString`, this implements :class:`~zope.schema.interfaces.IFromUnicode` and :class:`~zope.schema.interfaces.IFromBytes`. .. versionchanged:: 4.9.0 This is now a distinct type instead of an alias for either `Text` or `Bytes`, depending on the platform.
625990742ae34c7f260aca17
class GetGroupByName(IcontrolRestCommand): <NEW_LINE> <INDENT> def __init__(self, group_name, *args, **kwargs): <NEW_LINE> <INDENT> super(GetGroupByName, self).__init__(*args, **kwargs) <NEW_LINE> self.group_name = group_name <NEW_LINE> <DEDENT> def setup(self): <NEW_LINE> <INDENT> group = None <NEW_LINE> groupsresp = self.api.get(DeviceGroup.URI)['items'] <NEW_LINE> for item in groupsresp: <NEW_LINE> <INDENT> if item['groupName'] == self.group_name: <NEW_LINE> <INDENT> group = item <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> return group
Get Device Groups by Group Name Type: GET @param group_name: group name @type group_name: string @return: the api resp or None if there is no such group @rtype: attr dict json or None
62599074be8e80087fbc09c4
class SellarDis1(om.ExplicitComponent): <NEW_LINE> <INDENT> def setup(self): <NEW_LINE> <INDENT> self.add_input('z', val=np.zeros(2)) <NEW_LINE> self.add_input('x', val=0.) <NEW_LINE> self.add_input('y2', val=1.0) <NEW_LINE> self.add_output('y1', val=1.0) <NEW_LINE> <DEDENT> def setup_partials(self): <NEW_LINE> <INDENT> self.declare_partials('*', '*', method='fd') <NEW_LINE> <DEDENT> def compute(self, inputs, outputs): <NEW_LINE> <INDENT> z1 = inputs['z'][0] <NEW_LINE> z2 = inputs['z'][1] <NEW_LINE> x1 = inputs['x'] <NEW_LINE> y2 = inputs['y2'] <NEW_LINE> outputs['y1'] = z1**2 + z2 + x1 - 0.2*y2
Component containing Discipline 1 -- no derivatives version.
62599074ad47b63b2c5a9180
class Policies(_ObjectWidgetBar): <NEW_LINE> <INDENT> pass
Widget bar of Policy objects.
6259907432920d7e50bc797a
class ElementoHardwareForm(ModelForm): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = ElementoHardware
docstring for ElementoHardware
62599074283ffb24f3cf51dd
class OneTimeUseType_(ConditionAbstractType_): <NEW_LINE> <INDENT> c_tag = 'OneTimeUseType' <NEW_LINE> c_namespace = NAMESPACE <NEW_LINE> c_children = ConditionAbstractType_.c_children.copy() <NEW_LINE> c_attributes = ConditionAbstractType_.c_attributes.copy() <NEW_LINE> c_child_order = ConditionAbstractType_.c_child_order[:] <NEW_LINE> c_cardinality = ConditionAbstractType_.c_cardinality.copy()
The urn:oasis:names:tc:SAML:2.0:assertion:OneTimeUseType element
6259907421bff66bcd72459b
class TestV1beta1HTTPIngressPath(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testV1beta1HTTPIngressPath(self): <NEW_LINE> <INDENT> pass
V1beta1HTTPIngressPath unit test stubs
62599074009cb60464d02e6e
class BinaryVectorFactory: <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def generate_random_vector(dimension): <NEW_LINE> <INDENT> randvec = BinaryVector(dimension) <NEW_LINE> randvec.set_random_vector() <NEW_LINE> return randvec <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def generate_zero_vector(dimension): <NEW_LINE> <INDENT> zerovec = BinaryVector(dimension) <NEW_LINE> return zerovec <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def generate_vector(incoming_packedbits): <NEW_LINE> <INDENT> binaryvec = BinaryVector(len(incoming_packedbits)*8,incoming_vector=incoming_packedbits) <NEW_LINE> return binaryvec
BinaryVectorFactory creates three sorts of BinaryVector objects: (1) Zero vectors (binary vectors with no bits set) (2) Random vectors (binary vectors with half the bits set to 1 at random) (3) Vectors with a preset bitarray (e.g. read from disk)
625990747d43ff24874280ad
class TestNdarrayIntrinsic(TestCase): <NEW_LINE> <INDENT> def test_to_fixed_tuple(self): <NEW_LINE> <INDENT> const = 3 <NEW_LINE> @njit <NEW_LINE> def foo(array): <NEW_LINE> <INDENT> a = to_fixed_tuple(array, length=1) <NEW_LINE> b = to_fixed_tuple(array, 2) <NEW_LINE> c = to_fixed_tuple(array, const) <NEW_LINE> d = to_fixed_tuple(array, 0) <NEW_LINE> return a, b, c, d <NEW_LINE> <DEDENT> np.random.seed(123) <NEW_LINE> for _ in range(10): <NEW_LINE> <INDENT> arr = np.random.random(3) <NEW_LINE> a, b, c, d = foo(arr) <NEW_LINE> self.assertEqual(a, tuple(arr[:1])) <NEW_LINE> self.assertEqual(b, tuple(arr[:2])) <NEW_LINE> self.assertEqual(c, tuple(arr[:3])) <NEW_LINE> self.assertEqual(d, ()) <NEW_LINE> <DEDENT> with self.assertRaises(TypingError) as raises: <NEW_LINE> <INDENT> foo(np.random.random((1, 2))) <NEW_LINE> <DEDENT> self.assertIn("Not supported on array.ndim=2", str(raises.exception)) <NEW_LINE> @njit <NEW_LINE> def tuple_with_length(array, length): <NEW_LINE> <INDENT> return to_fixed_tuple(array, length) <NEW_LINE> <DEDENT> with self.assertRaises(TypingError) as raises: <NEW_LINE> <INDENT> tuple_with_length(np.random.random(3), 1) <NEW_LINE> <DEDENT> expectmsg = "*length* argument must be a constant" <NEW_LINE> self.assertIn(expectmsg, str(raises.exception)) <NEW_LINE> <DEDENT> def test_issue_3586_variant1(self): <NEW_LINE> <INDENT> @njit <NEW_LINE> def func(): <NEW_LINE> <INDENT> S = empty_inferred((10,)) <NEW_LINE> a = 1.1 <NEW_LINE> for i in range(len(S)): <NEW_LINE> <INDENT> S[i] = a + 2 <NEW_LINE> <DEDENT> return S <NEW_LINE> <DEDENT> got = func() <NEW_LINE> expect = np.asarray([3.1] * 10) <NEW_LINE> np.testing.assert_array_equal(got, expect) <NEW_LINE> <DEDENT> def test_issue_3586_variant2(self): <NEW_LINE> <INDENT> @njit <NEW_LINE> def func(): <NEW_LINE> <INDENT> S = empty_inferred((10,)) <NEW_LINE> a = 1.1 <NEW_LINE> for i in range(S.size): <NEW_LINE> <INDENT> S[i] = a + 2 <NEW_LINE> <DEDENT> return S <NEW_LINE> <DEDENT> got = func() <NEW_LINE> expect = np.asarray([3.1] * 10) <NEW_LINE> np.testing.assert_array_equal(got, expect)
Tests for numba.unsafe.ndarray
625990744c3428357761bbe9
class UserProfileInline(admin.StackedInline): <NEW_LINE> <INDENT> model = UserProfile <NEW_LINE> can_delete = False
O seu perfil será editado como forma in-line
625990744f88993c371f11ba
@admin.register(Voice) <NEW_LINE> class VoiceAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> save_on_top = True <NEW_LINE> save_as = True
Голоса
625990747d847024c075dd0e
class JobReference(_messages.Message): <NEW_LINE> <INDENT> jobId = _messages.StringField(1) <NEW_LINE> projectId = _messages.StringField(2)
Encapsulates the full scoping used to reference a job. Fields: jobId: Optional. The job ID, which must be unique within the project. The job ID is generated by the server upon job submission or provided by the user as a means to perform retries without creating duplicate jobs. The ID must contain only letters (a-z, A-Z), numbers (0-9), underscores (_), or hyphens (-). The maximum length is 100 characters. projectId: Required. The ID of the Google Cloud Platform project that the job belongs to.
625990741f5feb6acb164528
class MainViewTestCase(pushit.ClickAppTestCase): <NEW_LINE> <INDENT> def test_initial_label(self): <NEW_LINE> <INDENT> app = self.launch_application() <NEW_LINE> label = app.main_view.select_single(objectName='label') <NEW_LINE> self.assertThat(label.text, Equals('Hello..')) <NEW_LINE> <DEDENT> def test_click_button_should_update_label(self): <NEW_LINE> <INDENT> app = self.launch_application() <NEW_LINE> button = app.main_view.select_single(objectName='button') <NEW_LINE> app.pointing_device.click_object(button) <NEW_LINE> label = app.main_view.select_single(objectName='label') <NEW_LINE> self.assertThat(label.text, Eventually(Equals('..world!')))
Generic tests for the Hello World
6259907463b5f9789fe86a99
class FailureHoldingErrorHolderTests(ErrorHolderTestsMixin, TestTestHolder): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.description = "description" <NEW_LINE> try: <NEW_LINE> <INDENT> raise self.exceptionForTests <NEW_LINE> <DEDENT> except ZeroDivisionError: <NEW_LINE> <INDENT> self.error = failure.Failure() <NEW_LINE> <DEDENT> self.holder = runner.ErrorHolder(self.description, self.error) <NEW_LINE> self.result = self.TestResultStub()
Tests for L{runner.ErrorHolder} behaving similarly to L{runner.TestHolder} when constructed with a L{Failure} representing its error.
62599074bf627c535bcb2e01
class AddressViewSet(CreateModelMixin, UpdateModelMixin, GenericViewSet): <NEW_LINE> <INDENT> serializer_class = UserAddressSerializer <NEW_LINE> permission_classes = [IsAuthenticated] <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> return self.request.user.addresses.filter(is_deleted=False) <NEW_LINE> <DEDENT> def list(self, request, *args, **kwargs): <NEW_LINE> <INDENT> queryset = self.get_queryset() <NEW_LINE> serializer = self.get_serializer(queryset, many=True) <NEW_LINE> user = self.request.user <NEW_LINE> return Response({ 'user_id': user.id, 'default_address_id': user.default_address_id, 'limit': constants.USER_ADDRESS_COUNTS_LIMIT, 'addresses': serializer.data, }) <NEW_LINE> <DEDENT> def create(self, request, *args, **kwargs): <NEW_LINE> <INDENT> count = self.request.user.addresses.filter(is_deleted=False).count() <NEW_LINE> if count > constants.USER_ADDRESS_COUNTS_LIMIT: <NEW_LINE> <INDENT> return Response({"message": "地址数量超过上限"}, status=status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> return super().create(request, *args, **kwargs) <NEW_LINE> <DEDENT> def destroy(self, request, *args, **kwargs): <NEW_LINE> <INDENT> address = self.get_object() <NEW_LINE> address.is_deleted = True <NEW_LINE> address.save() <NEW_LINE> return Response(status=status.HTTP_204_NO_CONTENT) <NEW_LINE> <DEDENT> @action(methods=['put'], detail=True) <NEW_LINE> def status(self, request, pk=None): <NEW_LINE> <INDENT> address = self.get_object() <NEW_LINE> request.user.default_address = address <NEW_LINE> request.user.save() <NEW_LINE> return Response({"message": "OK"}, status=status.HTTP_200_OK) <NEW_LINE> <DEDENT> @action(methods=['put'], detail=True) <NEW_LINE> def title(self, request, pk=None): <NEW_LINE> <INDENT> address = self.get_object() <NEW_LINE> serializer = AddressTitleSerializer(address, data=request.data) <NEW_LINE> serializer.is_valid(raise_exception=True) <NEW_LINE> serializer.save() <NEW_LINE> return Response(serializer.data)
用户地址新增和修改
6259907423849d37ff8529eb
class UserLogin(Resource): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def post(cls): <NEW_LINE> <INDENT> data = _user_parser.parse_args() <NEW_LINE> user = UserModel.get_user_by_username(data["username"]) <NEW_LINE> if user and safe_str_cmp(user.password, data["password"]): <NEW_LINE> <INDENT> access_token = create_access_token(identity=user.id, fresh=True) <NEW_LINE> refresh_token = create_refresh_token(identity=user.id) <NEW_LINE> return { "access_token": access_token, "refresh_token": refresh_token }, 200 <NEW_LINE> <DEDENT> return {"msg": "invalid credentials"}, 401
Resource for loging a user. This is basically what JWT did before in section 10.
62599074435de62698e9d73c
class KnownValues(unittest.TestCase): <NEW_LINE> <INDENT> known_values_rules = ( (['red', 'white', 'blue', '', '', ''], True, 2), (['white', 'yellow', 'blue', '', '', ''], False, 1), (['', 'white', 'yellow', '', 'red', ''], True, 4), (['', '', '', 'yellow', 'yellow', 'blue'], False, 4), (['', 'red', 'red', 'white', '', ''], True, 3), (['blue', 'blue', 'red', '', '', ''], False, 1), (['', '', 'red', '', 'yellow', 'blue'], True, 5), (['red', '', 'red', '', 'yellow', 'blue'], True, 2), (['', 'white', '', 'yellow', 'blue', 'yellow'], True, 1), (['red', '', 'red', '', 'yellow', 'blue'], False, 0), (['', 'white', '', 'yellow', 'yellow', 'red'], True, 5), (['white', '', '', 'red', 'yellow', 'red'], False, 3), (['red', '', 'red', 'blue', 'yellow', 'black'], True, 4), (['blue', 'white', '', 'yellow', 'yellow', 'red'], False, 0), (['', 'red', 'red', 'white', 'yellow', 'blue'], False, 2), (['red', '', 'red', 'blue', 'yellow', 'black'], False, 0), (['white', 'blue', 'red', 'black', '', 'black'], False, 0), (['white', 'blue', 'red', 'black', 'blue', 'black'], True, 2), (['black', 'white', 'black', 'yellow', 'white', 'red'], False, 3), (['white', 'yellow', 'blue', 'yellow', 'white', 'black'], True, 5), (['red', 'black', 'red', 'blue', 'white', 'yellow'], True, 3), (['white', 'blue', 'red', 'black', 'blue', 'black'], False, 3), ) <NEW_LINE> def test_get_correct_wire_known_values(self): <NEW_LINE> <INDENT> for sequence, boolpar, number in self.known_values_rules: <NEW_LINE> <INDENT> ktane_model = Model() <NEW_LINE> ktane_model.serial_number_contains_vowel = boolpar <NEW_LINE> wires_module = WiresModule(ktane_model) <NEW_LINE> wires_module.wires_sequence = sequence <NEW_LINE> result = wires_module.get_correct_wire() <NEW_LINE> self.assertEqual(number, result)
known sequences - colors or missing wire, and boolean parameter first wire has number 0
62599074ad47b63b2c5a9182
class UUIDField(models.CharField): <NEW_LINE> <INDENT> description = _("UUID") <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> kwargs['max_length'] = 36 <NEW_LINE> kwargs['unique'] = True <NEW_LINE> kwargs['blank'] = True <NEW_LINE> models.CharField.__init__(self, **kwargs) <NEW_LINE> <DEDENT> def pre_save(self, model_instance, add): <NEW_LINE> <INDENT> if not getattr(model_instance, self.attname): <NEW_LINE> <INDENT> value = str(uuid()) <NEW_LINE> setattr(model_instance, self.attname, value) <NEW_LINE> return value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return super(UUIDField, self).pre_save(model_instance, add)
Unique identifier, which is automatically generated.
6259907499cbb53fe683281f
class _ShardCheckAndSetCallable(object): <NEW_LINE> <INDENT> def __init__(self, engine, get_updates_fn): <NEW_LINE> <INDENT> self.engine = engine <NEW_LINE> self.get_updates_fn = get_updates_fn <NEW_LINE> <DEDENT> def __call__(self, *args, **kwargs): <NEW_LINE> <INDENT> return self._ShardCheckAndSet(*args, **kwargs) <NEW_LINE> <DEDENT> def _ShardCheckAndSet(self, shard, keys, vkeys, values): <NEW_LINE> <INDENT> op = CompoundOperation() <NEW_LINE> greenlets = [ gevent.spawn( self._ShardCheckAndSetBatch, shard, keys[i:i+CAS_BATCH_SIZE], vkeys[i:i+CAS_BATCH_SIZE], values[i:i+CAS_BATCH_SIZE]) for i in xrange(0, len(keys), CAS_BATCH_SIZE)] <NEW_LINE> gevent.joinall(greenlets) <NEW_LINE> [op.AddOp(g.get()) for g in greenlets] <NEW_LINE> op.response_value = [] <NEW_LINE> for sub_op in op.sub_operations: <NEW_LINE> <INDENT> if sub_op.success: <NEW_LINE> <INDENT> op.response_value.extend(sub_op.response_value) <NEW_LINE> <DEDENT> <DEDENT> return op <NEW_LINE> <DEDENT> def _ShardCheckAndSetBatch(self, shard, keys, vkeys, values): <NEW_LINE> <INDENT> retries = 0 <NEW_LINE> while True: <NEW_LINE> <INDENT> pipe = shard.pipeline(True) <NEW_LINE> try: <NEW_LINE> <INDENT> pipe.watch(*vkeys) <NEW_LINE> sub_pipe = pipe.pipeline(False) <NEW_LINE> map(sub_pipe.get, vkeys) <NEW_LINE> values = sub_pipe.execute() <NEW_LINE> put_kv_tuples = [] <NEW_LINE> for i, (key, value) in enumerate(itertools.izip(keys, values)): <NEW_LINE> <INDENT> put_kv_tuples.extend(self.get_updates_fn(key, value)) <NEW_LINE> if i % 1000 == 0: <NEW_LINE> <INDENT> gevent.sleep(0) <NEW_LINE> <DEDENT> <DEDENT> pipe.multi() <NEW_LINE> for key, value in put_kv_tuples: <NEW_LINE> <INDENT> vbucket = self.engine._GetVbucket(key) <NEW_LINE> vkey = self.engine._MakeVkey(key, vbucket) <NEW_LINE> pipe.set(vkey, value) <NEW_LINE> <DEDENT> response = pipe.execute() <NEW_LINE> <DEDENT> except redis.WatchError: <NEW_LINE> <INDENT> gevent.sleep(0.1 * retries + 0.1 * random.random()) <NEW_LINE> retries += 1 <NEW_LINE> if retries > MAX_TRANSACTION_RETRIES: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> continue <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> pipe.reset() <NEW_LINE> <DEDENT> op = Operation(success=True, response_value=response, retries=retries) <NEW_LINE> break <NEW_LINE> <DEDENT> return op
Callable class to implement the per-shard logic for BatchCheckAnsMultiSet. This is implemented as a class instead of a closure to reduce memory use and avoid leaks.
62599074091ae3566870656d
class Configuration(object): <NEW_LINE> <INDENT> def __init__(self, filename): <NEW_LINE> <INDENT> self.eSpacing = gR.eSpacing <NEW_LINE> self.rSpacing = gR.rSpacing <NEW_LINE> self.emitterParams = 12 <NEW_LINE> self.loadConfig(filename) <NEW_LINE> <DEDENT> def createEmitterConfig(self, config): <NEW_LINE> <INDENT> ml = [config[i:i+self.emitterParams] for i in range(0, len(config), self.emitterParams)] <NEW_LINE> ml = [map(list, zip(*row)) for row in ml] <NEW_LINE> ml2 = [] <NEW_LINE> for row in ml: <NEW_LINE> <INDENT> newRow = [] <NEW_LINE> for emi in row: <NEW_LINE> <INDENT> if not '' in emi: <NEW_LINE> <INDENT> newRow.append(emi) <NEW_LINE> <DEDENT> <DEDENT> if len(newRow) > 0: <NEW_LINE> <INDENT> ml2.append(newRow) <NEW_LINE> <DEDENT> <DEDENT> return ml2 <NEW_LINE> <DEDENT> def readConfig(self, filename): <NEW_LINE> <INDENT> configFile = open(filename) <NEW_LINE> configReader = csv.reader(configFile) <NEW_LINE> configArray = list() <NEW_LINE> for row in configReader: <NEW_LINE> <INDENT> configArray.append(row) <NEW_LINE> <DEDENT> return configArray <NEW_LINE> <DEDENT> def getEmitterConfig (self): <NEW_LINE> <INDENT> return self.emitterConfig <NEW_LINE> <DEDENT> def getDefaultAngle(self, x, y): <NEW_LINE> <INDENT> return self.emitterConfig[x][y][5] <NEW_LINE> <DEDENT> def getESpacing(self): <NEW_LINE> <INDENT> return self.eSpacing <NEW_LINE> <DEDENT> def getRSpacing(self): <NEW_LINE> <INDENT> return self.rSpacing <NEW_LINE> <DEDENT> def updateDefaultAngle(self, arrLoc, newDefAng): <NEW_LINE> <INDENT> self.emitterConfig[int(arrLoc[0])][int(arrLoc[1])][5] = newDefAng <NEW_LINE> <DEDENT> def writeConfig(self, filename): <NEW_LINE> <INDENT> outputList = [] <NEW_LINE> for h, row in enumerate(self.emitterConfig): <NEW_LINE> <INDENT> for i in range(self.emitterParams): <NEW_LINE> <INDENT> outputList.append([]) <NEW_LINE> <DEDENT> for emitter in row: <NEW_LINE> <INDENT> for i, param in enumerate(emitter): <NEW_LINE> <INDENT> outputList[h*self.emitterParams+i].append(param) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> with open(filename, 'wb') as csvfile: <NEW_LINE> <INDENT> spamwriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) <NEW_LINE> for row in outputList: <NEW_LINE> <INDENT> spamwriter.writerow(row) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def loadConfig(self, filename): <NEW_LINE> <INDENT> self.config = self.readConfig(filename) <NEW_LINE> self.emitterConfig = self.createEmitterConfig(self.config)
classdocs
625990745166f23b2e244d0a
class PinnedLocation(models.Model): <NEW_LINE> <INDENT> name = models.CharField('場所名', max_length=255) <NEW_LINE> lat = models.FloatField('緯度') <NEW_LINE> lng = models.FloatField('経度') <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name
場所
62599074627d3e7fe0e087bd
class Node(NetworkObject): <NEW_LINE> <INDENT> def __init__( self, **kwargs): <NEW_LINE> <INDENT> super(Node, self).__init__(**kwargs) <NEW_LINE> self.relations['hasInboundPort'] = self.get_has_inbound_port <NEW_LINE> self._has_inbound_port_ports = OrderedDict() <NEW_LINE> self.relations['hasOutboundPort'] = self.get_has_outbound_port <NEW_LINE> self._has_outbound_port_ports = OrderedDict() <NEW_LINE> self.relations['hasService'] = self.get_has_service <NEW_LINE> self._has_service_switching_services = OrderedDict() <NEW_LINE> self.relations['implementedBy'] = self.get_implemented_by <NEW_LINE> self._implemented_by_nodes = OrderedDict() <NEW_LINE> <DEDENT> def has_inbound_port(self, port): <NEW_LINE> <INDENT> if port.__class__ not in ( Port, PortGroup, ): <NEW_LINE> <INDENT> raise RelationHasInboundPortError() <NEW_LINE> <DEDENT> return port.identifier in self._has_inbound_port_ports <NEW_LINE> <DEDENT> def add_has_inbound_port(self, port): <NEW_LINE> <INDENT> if port.__class__ not in ( Port, PortGroup, ): <NEW_LINE> <INDENT> raise RelationHasInboundPortError() <NEW_LINE> <DEDENT> self._has_inbound_port_ports[port.identifier] = port <NEW_LINE> <DEDENT> def get_has_inbound_port(self): <NEW_LINE> <INDENT> return copy(self._has_inbound_port_ports) <NEW_LINE> <DEDENT> def has_outbound_port(self, port): <NEW_LINE> <INDENT> if port.__class__ not in ( Port, PortGroup, ): <NEW_LINE> <INDENT> raise RelationHasOutboundPortError() <NEW_LINE> <DEDENT> return port.identifier in self._has_outbound_port_ports <NEW_LINE> <DEDENT> def add_has_outbound_port(self, port): <NEW_LINE> <INDENT> if port.__class__ not in ( Port, PortGroup, ): <NEW_LINE> <INDENT> raise RelationHasOutboundPortError() <NEW_LINE> <DEDENT> self._has_outbound_port_ports[port.identifier] = port <NEW_LINE> <DEDENT> def get_has_outbound_port(self): <NEW_LINE> <INDENT> return copy(self._has_outbound_port_ports) <NEW_LINE> <DEDENT> def has_service(self, switching_service): <NEW_LINE> <INDENT> if switching_service.__class__ not in ( SwitchingService, ): <NEW_LINE> <INDENT> raise RelationHasServiceError() <NEW_LINE> <DEDENT> return switching_service.identifier in self._has_service_switching_services <NEW_LINE> <DEDENT> def add_has_service(self, switching_service): <NEW_LINE> <INDENT> if switching_service.__class__ not in ( SwitchingService, ): <NEW_LINE> <INDENT> raise RelationHasServiceError() <NEW_LINE> <DEDENT> self._has_service_switching_services[switching_service.identifier] = switching_service <NEW_LINE> <DEDENT> def get_has_service(self): <NEW_LINE> <INDENT> return copy(self._has_service_switching_services) <NEW_LINE> <DEDENT> def implemented_by(self, node): <NEW_LINE> <INDENT> if node.__class__ not in ( Node, ): <NEW_LINE> <INDENT> raise RelationImplementedByError() <NEW_LINE> <DEDENT> return node.identifier in self._implemented_by_nodes <NEW_LINE> <DEDENT> def add_implemented_by(self, node): <NEW_LINE> <INDENT> if node.__class__ not in ( Node, ): <NEW_LINE> <INDENT> raise RelationImplementedByError() <NEW_LINE> <DEDENT> self._implemented_by_nodes[node.identifier] = node <NEW_LINE> <DEDENT> def get_implemented_by(self): <NEW_LINE> <INDENT> return copy(self._implemented_by_nodes)
A Node object represents a device in a network. Physical or virtual devices can be represented by instances of this class.
625990745fcc89381b266df3
class ItemListDirective(Directive): <NEW_LINE> <INDENT> optional_arguments = 1 <NEW_LINE> final_argument_whitespace = True <NEW_LINE> option_spec = {'class': directives.class_option, 'filter': directives.unchanged} <NEW_LINE> has_content = False <NEW_LINE> def run(self): <NEW_LINE> <INDENT> item_list_node = item_list('') <NEW_LINE> if len(self.arguments) > 0: <NEW_LINE> <INDENT> item_list_node['title'] = self.arguments[0] <NEW_LINE> <DEDENT> if 'filter' in self.options: <NEW_LINE> <INDENT> item_list_node['filter'] = self.options['filter'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> item_list_node['filter'] = '' <NEW_LINE> <DEDENT> return [item_list_node]
Directive to generate a list of items. Syntax:: .. item-list:: title :filter: regexp
625990741b99ca40022901d0
class SingleHelperSelectWidget(ModelSelect2Widget): <NEW_LINE> <INDENT> model = Helper <NEW_LINE> search_fields = [ 'firstname__icontains', 'surname__icontains', ] <NEW_LINE> def label_from_instance(self, obj): <NEW_LINE> <INDENT> return obj.full_name
Select2 widget for a single helper. The search looks at the first and last name.
62599074009cb60464d02e70
class Request(object): <NEW_LINE> <INDENT> def __init__(self, opener): <NEW_LINE> <INDENT> self.routes = None <NEW_LINE> self.opener = opener <NEW_LINE> <DEDENT> def feed(self, routes): <NEW_LINE> <INDENT> self.routes = routes <NEW_LINE> for name, urls in routes: <NEW_LINE> <INDENT> methodName = "request_%s" % name <NEW_LINE> if hasattr(self, methodName): <NEW_LINE> <INDENT> method = getattr(self, methodName) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> method = getattr(self, "unknown_request") <NEW_LINE> <DEDENT> if not isinstance(urls, list): <NEW_LINE> <INDENT> urls = [urls] <NEW_LINE> <DEDENT> for url in urls: <NEW_LINE> <INDENT> logging.info("Begin request %s" % name) <NEW_LINE> method(url) <NEW_LINE> logging.info("Done request %s" % name) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def unknown_request(self, route): <NEW_LINE> <INDENT> usock, content = self.open(route) <NEW_LINE> print(content) <NEW_LINE> return usock <NEW_LINE> <DEDENT> def request_nodeAnswerCommentBoxV2(self, route): <NEW_LINE> <INDENT> return <NEW_LINE> params = json.dumps({'answer_id': '9812424', 'load_all': False}) <NEW_LINE> params = urllib.urlencode({'': params}) <NEW_LINE> url = "%s?params%s" % (route, params) <NEW_LINE> usock = self.opener.open(url) <NEW_LINE> result = htmltool.handle_uscok(usock) <NEW_LINE> print(result) <NEW_LINE> usock.close() <NEW_LINE> <DEDENT> def open(self, route): <NEW_LINE> <INDENT> usock = self.opener.open(route) <NEW_LINE> return (usock, htmltool.handle_uscok(usock)) <NEW_LINE> <DEDENT> def request_people(self, route): <NEW_LINE> <INDENT> result = self.open(route) <NEW_LINE> print(result[1]) <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> pass
docstring for Claws
625990743d592f4c4edbc7f7
class KthSmallestTest(unittest.TestCase): <NEW_LINE> <INDENT> @given(lists(integers(), min_size=1, max_size=1000, unique=True)) <NEW_LINE> @given(integers(min_value=0, max_value=100)) <NEW_LINE> def test_index_error(self, lst, k_shift): <NEW_LINE> <INDENT> self.assertRaises(IndexError, kth_smallest, lst, -1 - k_shift) <NEW_LINE> self.assertRaises(IndexError, kth_smallest, lst, len(lst) + k_shift) <NEW_LINE> <DEDENT> @given(integers(min_value=-5, max_value=100)) <NEW_LINE> def test_index_error_edge(self, k): <NEW_LINE> <INDENT> self.assertRaises(IndexError, kth_smallest, [], k) <NEW_LINE> <DEDENT> @given(lists(integers(), min_size=1, max_size=1000, unique=True)) <NEW_LINE> @given(integers()) <NEW_LINE> def test_mutation(self, lst, k_mod): <NEW_LINE> <INDENT> new_lst = list(lst) <NEW_LINE> new_k = k_mod % len(lst) <NEW_LINE> kth_smallest(new_lst, new_k) <NEW_LINE> self.assertEqual(lst, new_lst)
Test function <kth_smallest()>
625990744f88993c371f11bb
class Category(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=100) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = '分类' <NEW_LINE> verbose_name_plural = verbose_name <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.name
分类表
625990747b180e01f3e49cff
class Config: <NEW_LINE> <INDENT> def __init__(self, filename, filename_default='default.cfg.json'): <NEW_LINE> <INDENT> self.filename = filename_default <NEW_LINE> self.load() <NEW_LINE> self.filename = filename <NEW_LINE> <DEDENT> def load(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(self.filename, 'r') as file: <NEW_LINE> <INDENT> content_raw = file.read() <NEW_LINE> if DEBUG: <NEW_LINE> <INDENT> log("\nDump raw:") <NEW_LINE> log(content_raw) <NEW_LINE> <DEDENT> content = json.loads(content_raw) <NEW_LINE> if DEBUG: <NEW_LINE> <INDENT> log("\nDump parsed:") <NEW_LINE> log(content) <NEW_LINE> <DEDENT> self.keys = [] <NEW_LINE> for k, v in content.items(): <NEW_LINE> <INDENT> self.keys.append(k) <NEW_LINE> self.__dict__[k.lower()] = v <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except FileNotFoundError as e: <NEW_LINE> <INDENT> log(f"ERROR: file {self.filename} not found") <NEW_LINE> log(f"load() failed. {e}") <NEW_LINE> <DEDENT> <DEDENT> def save(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(self.filename, 'w') as file: <NEW_LINE> <INDENT> d = dict() <NEW_LINE> for k in self.keys: <NEW_LINE> <INDENT> v = self.__dict__[k] <NEW_LINE> if isinstance(v, np.ndarray): <NEW_LINE> <INDENT> d.update({k: v.tolist()}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> d.update({k: v}) <NEW_LINE> <DEDENT> <DEDENT> raw = json.dumps(d, indent=4) <NEW_LINE> file.write(raw) <NEW_LINE> <DEDENT> if DEBUG: <NEW_LINE> <INDENT> log(f"Saved to file {self.filename}") <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> log(f"ERROR: Save to file {self.filename} failed.") <NEW_LINE> log(f"{e}")
Wrapper for a config file. Loads values from default config file. Access via point operator: >>> c: Config = Config("save.cfg.json") >>> c.delta_t_max 50000000.0 Values can also be set using the same operator >>> c.delta_t_max = 200.0 Save the config to the file with the filename provided in the constructor >>> #c.save()
62599074460517430c432cf3
class MonthJournal(models.Model): <NEW_LINE> <INDENT> student = models.ForeignKey( 'Student', verbose_name=_(u'Student'), blank=False, unique_for_month='date' ) <NEW_LINE> date = models.DateField( verbose_name=_(u'Date'), blank=False ) <NEW_LINE> scope = locals() <NEW_LINE> for field_number in range(1, 32): <NEW_LINE> <INDENT> scope['present_day'+str(field_number)] = models.BooleanField( verbose_name=_(u'Day #')+str(field_number), default=False ) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = _(u'Month Journal') <NEW_LINE> verbose_name_plural = _(u'Months Journals') <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return u'%s: %d, %d' % (self.student.last_name, self.date.month, self.date.year)
Student Monthly Journal
6259907467a9b606de54773f
class _McFileCollectionQuery(Generic[MCFILE]): <NEW_LINE> <INDENT> def __init__( self, collections_type: Type[_McFileCollection[MCPACK, MCFILE]], collections: Sequence[_McFileCollection[MCPACK, MCFILE]]): <NEW_LINE> <INDENT> self.collections = collections <NEW_LINE> self.collections_type = collections_type <NEW_LINE> <DEDENT> def __getitem__(self, key: Union[str, slice]) -> MCFILE: <NEW_LINE> <INDENT> return self.collections_type._get_item_from_combined_collections( self.collections, key) <NEW_LINE> <DEDENT> def __iter__(self) -> Iterator[MCFILE]: <NEW_LINE> <INDENT> for key in self.keys(): <NEW_LINE> <INDENT> yield self[:key:0] <NEW_LINE> <DEDENT> <DEDENT> def keys(self) -> Tuple[str, ...]: <NEW_LINE> <INDENT> result: List[str] = [] <NEW_LINE> for collection in self.collections: <NEW_LINE> <INDENT> result.extend(collection.keys()) <NEW_LINE> <DEDENT> return tuple(set(result))
Groups multiple file collections (from multiple packs). Used by :class:`Project` to provide methods for finding :class:`McFile` in groups of :class:`McFileCollection` objects that belong to that project.
625990745fdd1c0f98e5f8b3
class Node: <NEW_LINE> <INDENT> def __init__(self, move = None, parent = None, state = None): <NEW_LINE> <INDENT> self.move = move <NEW_LINE> self.parentNode = parent <NEW_LINE> self.childNodes = [] <NEW_LINE> self.wins = 0 <NEW_LINE> self.visits = 0 <NEW_LINE> self.untriedMoves = state.GetMoves() <NEW_LINE> self.playerJustMoved = state.playerJustMoved <NEW_LINE> <DEDENT> def UCTSelectChild(self): <NEW_LINE> <INDENT> e = 0.5 <NEW_LINE> r = random.random() <NEW_LINE> if(r > e): <NEW_LINE> <INDENT> s = sorted(self.childNodes, key = lambda c: c.wins/float(c.visits))[-1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> s = random.choice(self.childNodes) <NEW_LINE> <DEDENT> return s <NEW_LINE> <DEDENT> def AddChild(self, m, s): <NEW_LINE> <INDENT> n = Node(move = m, parent = self, state = s) <NEW_LINE> self.untriedMoves.remove(m) <NEW_LINE> self.childNodes.append(n) <NEW_LINE> return n <NEW_LINE> <DEDENT> def Update(self, result): <NEW_LINE> <INDENT> self.visits += 1 <NEW_LINE> self.wins += result <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "[M:" + str(self.move) + " W/V:" + str(self.wins) + "/" + str(self.visits) + " W/V" + str(self.wins/float(self.visits)) + "U:" + str(self.untriedMoves) + "]" <NEW_LINE> <DEDENT> def TreeToString(self, indent): <NEW_LINE> <INDENT> s = self.IndentString(indent) + str(self) <NEW_LINE> for c in self.childNodes: <NEW_LINE> <INDENT> s += c.TreeToString(indent+1) <NEW_LINE> <DEDENT> return s <NEW_LINE> <DEDENT> def IndentString(self,indent): <NEW_LINE> <INDENT> s = "\n" <NEW_LINE> for i in range (1,indent+1): <NEW_LINE> <INDENT> s += "| " <NEW_LINE> <DEDENT> return s <NEW_LINE> <DEDENT> def ChildrenToString(self): <NEW_LINE> <INDENT> s = "" <NEW_LINE> for c in self.childNodes: <NEW_LINE> <INDENT> s += str(c) + "\n" <NEW_LINE> <DEDENT> return s
A node in the game tree. Note wins is always from the viewpoint of playerJustMoved. Crashes if state not specified.
62599074435de62698e9d73e
class AzureDigitalTwinsAPIConfiguration(AzureConfiguration): <NEW_LINE> <INDENT> def __init__( self, credentials, base_url=None): <NEW_LINE> <INDENT> if credentials is None: <NEW_LINE> <INDENT> raise ValueError("Parameter 'credentials' must not be None.") <NEW_LINE> <DEDENT> if not base_url: <NEW_LINE> <INDENT> base_url = 'https://digitaltwins-name.digitaltwins.azure.net' <NEW_LINE> <DEDENT> super(AzureDigitalTwinsAPIConfiguration, self).__init__(base_url) <NEW_LINE> self.add_user_agent('ADTDataPlane/{}'.format(VERSION)) <NEW_LINE> self.add_user_agent('Azure-SDK-For-Python') <NEW_LINE> self.credentials = credentials
Configuration for AzureDigitalTwinsAPI Note that all parameters used to create this instance are saved as instance attributes. :param credentials: Credentials needed for the client to connect to Azure. :type credentials: :mod:`A msrestazure Credentials object<msrestazure.azure_active_directory>` :param str base_url: Service URL
6259907499cbb53fe6832821
class ExtractSuperClassesByName(object): <NEW_LINE> <INDENT> def VisitTypeDeclUnit(self, module): <NEW_LINE> <INDENT> result = {base_class: superclasses for base_class, superclasses in module.classes} <NEW_LINE> for submodule in module.modules: <NEW_LINE> <INDENT> result.update( {self.old_node.name + "." + name: superclasses for name, superclasses in submodule.items()}) <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def VisitClass(self, cls): <NEW_LINE> <INDENT> return (cls.name, [parent.name for parent in cls.parents])
Visitor for extracting all superclasses (i.e., the class hierarchy). This returns a mapping by name, e.g. { "bool": ["int"], "int": ["object"], ... }.
625990744a966d76dd5f0820
class TestFileFilterApi(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.api = isi_sdk_9_1_0.api.file_filter_api.FileFilterApi() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_get_file_filter_settings(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_update_file_filter_settings(self): <NEW_LINE> <INDENT> pass
FileFilterApi unit test stubs
62599074be7bc26dc9252af1
class TestRegenerateReproducibilityData(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.tempdir = tempfile.mkdtemp() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> shutil.rmtree(self.tempdir) <NEW_LINE> <DEDENT> def test_write_data_with_explicit_filename(self): <NEW_LINE> <INDENT> filename = os.path.join(self.tempdir, 'fingerprints.json') <NEW_LINE> self.assertFalse(os.path.exists(filename)) <NEW_LINE> with args_in_sys_argv([filename]): <NEW_LINE> <INDENT> regenerate_data_main() <NEW_LINE> <DEDENT> self.assertTrue(os.path.exists(filename)) <NEW_LINE> with open(filename) as f: <NEW_LINE> <INDENT> contents = json.load(f) <NEW_LINE> <DEDENT> self.assertIsInstance(contents, dict) <NEW_LINE> self.assertIn('generators', contents)
Yes, this is a test for a test utility.
625990741b99ca40022901d1
class Post(db.Model): <NEW_LINE> <INDENT> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> title = db.Column(db.String(100), nullable=False) <NEW_LINE> date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) <NEW_LINE> content = db.Column(db.Text, nullable=False) <NEW_LINE> user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return f"Post('{self.title}', '{self.date_posted}')"
- modelul de postare - contine campurile de completare a unei postari
62599074fff4ab517ebcf14d
class EnvvarCollector(object): <NEW_LINE> <INDENT> def __init__(self, envvars_map=None, envvars_to_remove=None): <NEW_LINE> <INDENT> self.map = envvars_map or {} <NEW_LINE> self.to_remove = envvars_to_remove or set() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_str(cls, envvars_str): <NEW_LINE> <INDENT> if not envvars_str: <NEW_LINE> <INDENT> return cls() <NEW_LINE> <DEDENT> envvars = envvars_str.split(',') <NEW_LINE> envvars_map, envvars_to_remove = commonops.create_envvars_list( envvars, as_option_settings=False) <NEW_LINE> return cls(envvars_map, envvars_to_remove) <NEW_LINE> <DEDENT> def merge(self, higher_priority_env): <NEW_LINE> <INDENT> envvars_map = utils.merge_dicts(low_priority=self.map, high_priority=higher_priority_env.map) <NEW_LINE> to_remove = self.to_remove | higher_priority_env.to_remove <NEW_LINE> return EnvvarCollector(envvars_map, to_remove) <NEW_LINE> <DEDENT> def filtered(self): <NEW_LINE> <INDENT> filtered_envvars = {k: v for k, v in six.iteritems(self.map) if k not in self.to_remove} <NEW_LINE> return EnvvarCollector(filtered_envvars)
Immutable class for grouping environment variables to add and remove.
6259907499cbb53fe6832822
class Session(Envelope): <NEW_LINE> <INDENT> def __init__( self, state: str = None, encryption_options: List[str] = None, encryption: str = None, compression_options: List[str] = None, compression: str = None, scheme: str = None, scheme_options: List[str] = None, authentication=None, reason: Reason = None, **kwargs ) -> None: <NEW_LINE> <INDENT> super().__init__(**kwargs) <NEW_LINE> self.state = state <NEW_LINE> self.encryption_options = encryption_options <NEW_LINE> self.encryption = encryption <NEW_LINE> self.compression_options = compression_options <NEW_LINE> self.compression = compression <NEW_LINE> self.scheme = scheme <NEW_LINE> self.scheme_options = scheme_options <NEW_LINE> self.authentication = authentication <NEW_LINE> self.reason = reason
Session representation.
6259907499fddb7c1ca63a70
class StudentSerializer(QueryFieldsMixin, serializers.ModelSerializer): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = Student <NEW_LINE> fields = ('id', 'name', 'surname', 'zip', 'country', 'email', 'courses') <NEW_LINE> read_only_fields = ('id', 'courses')
Serializer of Student model
625990744e4d562566373d3f
class TestIoK8sApimachineryPkgApisMetaV1LabelSelectorRequirement(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testIoK8sApimachineryPkgApisMetaV1LabelSelectorRequirement(self): <NEW_LINE> <INDENT> pass
IoK8sApimachineryPkgApisMetaV1LabelSelectorRequirement unit test stubs
62599074baa26c4b54d50be6
class VariantResourceHelper(VariantResource): <NEW_LINE> <INDENT> class _Metas(AttributeForwardMeta, LazyAttributeMeta): pass <NEW_LINE> __metaclass__ = _Metas <NEW_LINE> schema = variant_schema <NEW_LINE> keys = schema_keys(package_schema) - set(["requires", "variants"]) <NEW_LINE> def _uri(self): <NEW_LINE> <INDENT> index = self.index <NEW_LINE> idxstr = '' if index is None else str(index) <NEW_LINE> return "%s[%s]" % (self.parent.uri, idxstr) <NEW_LINE> <DEDENT> def _subpath(self): <NEW_LINE> <INDENT> if self.index is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> reqs = self.parent.variants[self.index] <NEW_LINE> <DEDENT> except (IndexError, TypeError): <NEW_LINE> <INDENT> raise ResourceError( "Unexpected error - variant %s cannot be found in its " "parent package %s" % (self.uri, self.parent.uri)) <NEW_LINE> <DEDENT> dirs = [x.safe_str() for x in reqs] <NEW_LINE> subpath = os.path.join(*dirs) if dirs else '' <NEW_LINE> return subpath <NEW_LINE> <DEDENT> <DEDENT> def _root(self): <NEW_LINE> <INDENT> if self.base is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> elif self.index is None: <NEW_LINE> <INDENT> return self.base <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> root = os.path.join(self.base, self.subpath) if self.subpath else self.base <NEW_LINE> return root <NEW_LINE> <DEDENT> <DEDENT> @cached_property <NEW_LINE> def requires(self): <NEW_LINE> <INDENT> reqs = self.parent.requires or [] <NEW_LINE> index = self.index <NEW_LINE> if index is not None: <NEW_LINE> <INDENT> reqs = reqs + (self.parent.variants[index] or []) <NEW_LINE> <DEDENT> return reqs <NEW_LINE> <DEDENT> @property <NEW_LINE> def wrapped(self): <NEW_LINE> <INDENT> return self.parent <NEW_LINE> <DEDENT> def _load(self): <NEW_LINE> <INDENT> return None
Helper class for implementing variants that inherit properties from their parent package. Since a variant overlaps so much with a package, here we use the forwarding metaclass to forward our parent package's attributes onto ourself (with some exceptions - eg 'variants', 'requires'). This is a common enough pattern that it's supplied here for other repository plugins to use.
625990749c8ee82313040e23
class DatabaseStatusError(Exception): <NEW_LINE> <INDENT> pass
General error thrown when the database is... Not Good.
62599074be8e80087fbc09ca
class TaskScheduleType(DeclEnum): <NEW_LINE> <INDENT> interval = 'int', _('Interval'), 10 <NEW_LINE> crontab = 'cron', _('Crontab'), 20
Celery beat task schedule type.
625990742c8b7c6e89bd5120
class DecodeView(QWidget): <NEW_LINE> <INDENT> def __init__(self, clipboard, options): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.clipboard = clipboard <NEW_LINE> self.options = options <NEW_LINE> self.buildDecodeView() <NEW_LINE> <DEDENT> def decode_handler(self): <NEW_LINE> <INDENT> if self.readFromClipboard.isChecked(): <NEW_LINE> <INDENT> self.outputBox.setText(Controller.handle_decoding(self.clipboard.text(), self.options.get_matrix_building_rule())) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.outputBox.setText(Controller.handle_decoding(self.inputBox.toPlainText(), self.options.get_matrix_building_rule())) <NEW_LINE> <DEDENT> <DEDENT> def mode_switcher(self): <NEW_LINE> <INDENT> if self.readFromClipboard.isChecked(): <NEW_LINE> <INDENT> self.inputBox.hide() <NEW_LINE> self.inputLabel.setText("Reading from clipboard") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.inputBox.show() <NEW_LINE> self.inputLabel.setText("Enter cyphered text to decode:") <NEW_LINE> <DEDENT> <DEDENT> def makeInputTextBox(self, base): <NEW_LINE> <INDENT> self.inputBox = QTextEdit() <NEW_LINE> return base.addWidget(self.inputBox,1,0,1,2) <NEW_LINE> <DEDENT> def makeDecodeControls(self, base): <NEW_LINE> <INDENT> self.readFromClipboard = QCheckBox('Read from clipboard') <NEW_LINE> self.readFromClipboard.stateChanged.connect(self.mode_switcher) <NEW_LINE> decodeButton = QPushButton('Decode') <NEW_LINE> decodeButton.clicked.connect(self.decode_handler) <NEW_LINE> base.addWidget(decodeButton) <NEW_LINE> base.addWidget(self.readFromClipboard) <NEW_LINE> <DEDENT> def makeOutputTextBox(self, base): <NEW_LINE> <INDENT> self.outputBox = QTextEdit() <NEW_LINE> self.outputBox.setReadOnly(True) <NEW_LINE> base.addWidget(self.outputBox) <NEW_LINE> <DEDENT> def buildDecodeView(self): <NEW_LINE> <INDENT> base = QGridLayout(self) <NEW_LINE> self.inputLabel = QLabel("Enter cyphered text to decode:") <NEW_LINE> base.addWidget(self.inputLabel, 0, 0, 1, 2) <NEW_LINE> self.makeInputTextBox(base) <NEW_LINE> self.makeDecodeControls(base) <NEW_LINE> base.addWidget(QLabel("Text:"), 3, 0) <NEW_LINE> self.makeOutputTextBox(base)
Class that builds decode view
625990744a966d76dd5f0822
class RandomPool: <NEW_LINE> <INDENT> def __init__(self, numbytes = 160, cipher=None, hash=None, file=None): <NEW_LINE> <INDENT> warnings.warn("This application uses RandomPool, which is BROKEN in older releases. See http://www.pycrypto.org/randpool-broken", RandomPool_DeprecationWarning) <NEW_LINE> self.__rng = Crypto.Random.new() <NEW_LINE> self.bytes = numbytes <NEW_LINE> self.bits = self.bytes * 8 <NEW_LINE> self.entropy = self.bits <NEW_LINE> <DEDENT> def get_bytes(self, N): <NEW_LINE> <INDENT> return self.__rng.read(N) <NEW_LINE> <DEDENT> def _updateEntropyEstimate(self, nbits): <NEW_LINE> <INDENT> self.entropy += nbits <NEW_LINE> if self.entropy < 0: <NEW_LINE> <INDENT> self.entropy = 0 <NEW_LINE> <DEDENT> elif self.entropy > self.bits: <NEW_LINE> <INDENT> self.entropy = self.bits <NEW_LINE> <DEDENT> <DEDENT> def _randomize(self, N=0, devname="/dev/urandom"): <NEW_LINE> <INDENT> self.__rng.flush() <NEW_LINE> <DEDENT> def randomize(self, N=0): <NEW_LINE> <INDENT> self.__rng.flush() <NEW_LINE> <DEDENT> def stir(self, s=''): <NEW_LINE> <INDENT> self.__rng.flush() <NEW_LINE> <DEDENT> def stir_n(self, N=3): <NEW_LINE> <INDENT> self.__rng.flush() <NEW_LINE> <DEDENT> def add_event(self, s=''): <NEW_LINE> <INDENT> self.__rng.flush() <NEW_LINE> <DEDENT> def getBytes(self, N): <NEW_LINE> <INDENT> return self.get_bytes(N) <NEW_LINE> <DEDENT> def addEvent(self, event, s=""): <NEW_LINE> <INDENT> return self.add_event()
Deprecated. Use Random.new() instead. See http://www.pycrypto.org/randpool-broken
625990748e7ae83300eea9ca
class Cloneable: <NEW_LINE> <INDENT> def clone(self): <NEW_LINE> <INDENT> raise NotImplementedError()
This (empty) interface must be implemented by all classes that wish to support cloning. The implementation of clone() in :class:`Object` checks if the object being cloned implements this interface and throws :class:`NotImplementedError` if it does not.
625990742c8b7c6e89bd5121
class maintest(pyshell.CLIEngine): <NEW_LINE> <INDENT> modes = { "1" : "pyshell.util", "2" : "IPython.core.debugger", "3" : "IPython.core.ultratb", } <NEW_LINE> defaultcfg = False <NEW_LINE> def after_configure(self): <NEW_LINE> <INDENT> self.parser.add_argument('mode',choices=self.modes.values()+self.modes.keys()) <NEW_LINE> <DEDENT> def do(self): <NEW_LINE> <INDENT> mode = self.opts.mode <NEW_LINE> if mode in self.modes.keys(): <NEW_LINE> <INDENT> mode = self.modes[mode] <NEW_LINE> <DEDENT> print("Mode: '%s'" % mode) <NEW_LINE> import sys <NEW_LINE> print("Original Value of __file__: %r" % sys.modules['__main__'].__file__) <NEW_LINE> _main = sys.modules['__main__'] <NEW_LINE> if mode == "pyshell.util": <NEW_LINE> <INDENT> import pyshell.util <NEW_LINE> pyshell.util.ipydb() <NEW_LINE> <DEDENT> elif mode == "IPython.core.debugger": <NEW_LINE> <INDENT> import IPython.core.debugger <NEW_LINE> IPython.core.debugger.Pdb() <NEW_LINE> <DEDENT> elif mode == "IPython.core.ultratb": <NEW_LINE> <INDENT> import IPython.core.ultratb <NEW_LINE> sys.excepthook = IPython.core.ultratb.FormattedTB(mode='Verbose',color_scheme='Linux', call_pdb=1) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> print("New Value of __file__: %r" % sys.modules['__main__'].__file__) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> print("__file__ no longer exists:") <NEW_LINE> print(dir(sys.modules['__main__'])) <NEW_LINE> print(sys.modules['__main__'].__doc__) <NEW_LINE> <DEDENT> sys.modules['__main__'] = _main <NEW_LINE> try: <NEW_LINE> <INDENT> print("Restored Value of __file__: %r" % sys.modules['__main__'].__file__) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> print("__file__ no longer exists:") <NEW_LINE> print(dir(sys.modules['__main__'])) <NEW_LINE> print(sys.modules['__main__'].__doc__)
Test for the main module file variables
62599074adb09d7d5dc0bea3
class VersionsSchema(VersionsSchemaBase, FieldPermissionsMixin): <NEW_LINE> <INDENT> field_load_permissions = {} <NEW_LINE> field_dump_permissions = { "is_latest_draft": "edit", }
Version schema with field-level permissions.
62599074167d2b6e312b822d
class Parser: <NEW_LINE> <INDENT> def __init__(self, tokens: t.List[str]): <NEW_LINE> <INDENT> self.reverse_polish_tokens = [] <NEW_LINE> self.tokens = iter(tokens + ["##NONE##"]) <NEW_LINE> self.current_token = next(self.tokens) <NEW_LINE> <DEDENT> def parse(self): <NEW_LINE> <INDENT> self._exp() <NEW_LINE> return self.reverse_polish_tokens <NEW_LINE> <DEDENT> def _exp(self): <NEW_LINE> <INDENT> self._term() <NEW_LINE> if self.current_token == "|": <NEW_LINE> <INDENT> t = self.current_token <NEW_LINE> self.current_token = next(self.tokens) <NEW_LINE> self._exp() <NEW_LINE> self.reverse_polish_tokens.append(t) <NEW_LINE> <DEDENT> <DEDENT> def _term(self): <NEW_LINE> <INDENT> self._factor() <NEW_LINE> if self.current_token == "&": <NEW_LINE> <INDENT> t = self.current_token <NEW_LINE> self.current_token = next(self.tokens) <NEW_LINE> self._term() <NEW_LINE> self.reverse_polish_tokens.append(t) <NEW_LINE> <DEDENT> <DEDENT> def _factor(self): <NEW_LINE> <INDENT> self._primary() <NEW_LINE> if self.current_token in "?*+": <NEW_LINE> <INDENT> self.reverse_polish_tokens.append(self.current_token) <NEW_LINE> self.current_token = next(self.tokens) <NEW_LINE> <DEDENT> <DEDENT> def _primary(self): <NEW_LINE> <INDENT> if self.current_token == "(": <NEW_LINE> <INDENT> self.current_token = next(self.tokens) <NEW_LINE> self._exp() <NEW_LINE> if self.current_token == ")": <NEW_LINE> <INDENT> self.current_token = next(self.tokens) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> err = f"Expected ')', got '{self.current_token}'" <NEW_LINE> raise ValueError(err) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if not WORD_POS_TAGS_RE.match(self.current_token): <NEW_LINE> <INDENT> err = f"Expected pos_tag or word, got '{self.current_token}'" <NEW_LINE> raise ValueError(err) <NEW_LINE> <DEDENT> self.reverse_polish_tokens.append(self.current_token) <NEW_LINE> self.current_token = next(self.tokens)
Use for transforming input tokens into reverse polish form
6259907416aa5153ce401e13
class Edge: <NEW_LINE> <INDENT> def __init__(self, v1, v2, w=None): <NEW_LINE> <INDENT> self.edge = (v1, v2) <NEW_LINE> self.weight = w
Connects two vertices with optional weight.
625990744c3428357761bbef