code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class TestUpdateOnSalesChannel(TestRequest): <NEW_LINE> <INDENT> request_class = range.UpdateRangeOnSalesChannel <NEW_LINE> RESPONSE = [] <NEW_LINE> RANGE_ID = "4355752" <NEW_LINE> REQUEST_TYPE = "select" <NEW_LINE> ACT = "update" <NEW_LINE> VALUE = "Test Value" <NEW_LINE> OPTION_ID = "32129" <NEW_LINE> CHANNEL_IDS = ["3541", "3557"] <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> super().setUp() <NEW_LINE> self.register(json=self.RESPONSE) <NEW_LINE> self.mock_request( range_id=self.RANGE_ID, request_type=self.REQUEST_TYPE, act=self.ACT, value=self.VALUE, option_id=self.OPTION_ID, channel_ids=self.CHANNEL_IDS, ) <NEW_LINE> <DEDENT> def test_UpdateRangeOnSalesChannel_request_sends_range_ID(self): <NEW_LINE> <INDENT> self.assertDataSent("rangeid", self.RANGE_ID) <NEW_LINE> <DEDENT> def test_UpdateRangeOnSalesChannel_request_sends_request_type(self): <NEW_LINE> <INDENT> self.assertDataSent("type", self.REQUEST_TYPE) <NEW_LINE> <DEDENT> def test_UpdateRangeOnSalesChannel_request_sends_act(self): <NEW_LINE> <INDENT> self.assertDataSent("act", self.ACT) <NEW_LINE> <DEDENT> def test_UpdateRangeOnSalesChannel_request_sends_value(self): <NEW_LINE> <INDENT> self.assertDataSent("val", self.VALUE) <NEW_LINE> <DEDENT> def test_UpdateRangeOnSalesChannel_request_sends_option_ID(self): <NEW_LINE> <INDENT> self.assertDataSent("optid", self.OPTION_ID) <NEW_LINE> <DEDENT> def test_UpdateRangeOnSalesChannel_request_sends_channel_IDs(self): <NEW_LINE> <INDENT> self.assertDataSent("chans", self.CHANNEL_IDS) <NEW_LINE> <DEDENT> def test_UpdateRangeOnSalesChannel_request_sends_brand_ID(self): <NEW_LINE> <INDENT> self.assertDataSent("brandid", 341) <NEW_LINE> <DEDENT> def test_UpdateRangeOnSalesChannel_raises_for_non_200(self): <NEW_LINE> <INDENT> self.register(json=self.RESPONSE, status_code=500) <NEW_LINE> with self.assertRaises(exceptions.CloudCommerceResponseError): <NEW_LINE> <INDENT> self.mock_request( range_id=self.RANGE_ID, request_type=self.REQUEST_TYPE, act=self.ACT, value=self.VALUE, option_id=self.OPTION_ID, channel_ids=self.CHANNEL_IDS, )
Test the UpdateRangeOnSalesChannel request.
6259900a462c4b4f79dbc5bc
class Value(TimeStampedModel): <NEW_LINE> <INDENT> val = models.CharField(blank=False, max_length=100, unique=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return "{val}".format(val=self.val)
Represent values of all cases and fieldgroups.
6259900a21a7993f00c66b33
class Feature(object): <NEW_LINE> <INDENT> def __init__(self, ogr_feature): <NEW_LINE> <INDENT> if isinstance(ogr_feature, Feature): <NEW_LINE> <INDENT> ogr_feature = ogr_feature._source <NEW_LINE> <DEDENT> assert isinstance(ogr_feature, ogr.Feature), "%s is not a ogr.Feature" % (ogr_feature,) <NEW_LINE> self.__dict__['_source'] = ogr_feature <NEW_LINE> <DEDENT> @property <NEW_LINE> def geometry(self): <NEW_LINE> <INDENT> return self._source.GetGeometryRef() <NEW_LINE> <DEDENT> def __getitem__(self, name): <NEW_LINE> <INDENT> return self.__getattr__(name) <NEW_LINE> <DEDENT> def __setitem__(self, name, value): <NEW_LINE> <INDENT> return self.__setattr__(name, value) <NEW_LINE> <DEDENT> def __getattr__(self, name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.__dict__[name] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self._source.GetField(name) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise KeyError(name) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __setattr__(self, name, value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self._source.SetField(name, value) <NEW_LINE> <DEDENT> except RuntimeError: <NEW_LINE> <INDENT> return object.__setattr__(self, name, value) <NEW_LINE> <DEDENT> <DEDENT> def ExportToJson(self): <NEW_LINE> <INDENT> return self._source.ExportToJson()
a simple wrapper that makes OGR Features objects pythonic
6259900a0a366e3fb87dd5aa
class TestRequests(CodeHandler): <NEW_LINE> <INDENT> @unittest.expectedFailure <NEW_LINE> @unittest.skipIf(requests is None, 'Install ``requests`` if you would like' + ' to test ``requests`` + future compatibility (issue #19)') <NEW_LINE> def test_requests(self): <NEW_LINE> <INDENT> with open(self.tempdir + 'test_imports_future_stdlib.py', 'w') as f: <NEW_LINE> <INDENT> f.write('from future import standard_library') <NEW_LINE> <DEDENT> sys.path.insert(0, self.tempdir) <NEW_LINE> print('Importing test_imports_future_stdlib ...') <NEW_LINE> try: <NEW_LINE> <INDENT> import test_imports_future_stdlib <NEW_LINE> standard_library.remove_hooks() <NEW_LINE> import requests <NEW_LINE> r = requests.get('http://google.com') <NEW_LINE> self.assertTrue(True) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> raise e <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('Succeeded!') <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> sys.path.remove(self.tempdir)
This class tests whether the requests module conflicts with the standard library import hooks, as in issue #19.
6259900a56b00c62f0fb3478
class InputSerialGnss(InputModule): <NEW_LINE> <INDENT> def __init__(self, data_hub, port, baud_rate): <NEW_LINE> <INDENT> super().__init__(data_hub=data_hub) <NEW_LINE> self._logger = logging.getLogger('InputSerialGnss') <NEW_LINE> self._logger.info('Initializing') <NEW_LINE> self._port = port <NEW_LINE> self._baud_rate = baud_rate <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> setproctitle.setproctitle("flightbox_input_serial_gnss") <NEW_LINE> self._logger.info('Running') <NEW_LINE> s = None <NEW_LINE> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> time.sleep(5) <NEW_LINE> s = serial.Serial(self._port, self._baud_rate) <NEW_LINE> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> line = s.readline().decode().strip() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> self._logger.debug('Data received: {!r}'.format(line)) <NEW_LINE> data_hub_item = DataHubItem('nmea', line) <NEW_LINE> self._data_hub.put(data_hub_item) <NEW_LINE> <DEDENT> <DEDENT> except(KeyboardInterrupt, SystemExit): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> self._logger.warning('Could not attach to serial port {} with baud rate {:d}'.format(self._port, self._baud_rate)) <NEW_LINE> pass <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> if s: <NEW_LINE> <INDENT> s.close() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self._data_hub.close() <NEW_LINE> self._logger.info('Terminating')
Input module that connects to serial GNSS device to get NMEA position data.
6259900a507cdc57c63a5958
class BodyDetectResult(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Confidence = None <NEW_LINE> self.BodyRect = None <NEW_LINE> self.BodyAttributeInfo = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.Confidence = params.get("Confidence") <NEW_LINE> if params.get("BodyRect") is not None: <NEW_LINE> <INDENT> self.BodyRect = BodyRect() <NEW_LINE> self.BodyRect._deserialize(params.get("BodyRect")) <NEW_LINE> <DEDENT> if params.get("BodyAttributeInfo") is not None: <NEW_LINE> <INDENT> self.BodyAttributeInfo = BodyAttributeInfo() <NEW_LINE> self.BodyAttributeInfo._deserialize(params.get("BodyAttributeInfo"))
图中检测出来的人体框。
6259900a15fb5d323ce7f8fb
class SinFriction(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __call__(self, X): <NEW_LINE> <INDENT> return torch.sin(X[:, 0:1])
The friction function is sin function only with the frist dimension.
6259900a0a366e3fb87dd5ac
class EncoderRNN(nn.Module): <NEW_LINE> <INDENT> def __init__( self, hidden_size=22, n_layers=1, num_labels=4, model_dim=22, dropout=0, bidirectional=True ): <NEW_LINE> <INDENT> super(EncoderRNN, self).__init__() <NEW_LINE> self.n_layers = n_layers <NEW_LINE> self.num_labels = num_labels <NEW_LINE> self.hidden_size = hidden_size <NEW_LINE> self.bidirectional = bidirectional <NEW_LINE> self.model_dim = model_dim <NEW_LINE> self.drop_out = nn.Dropout( dropout) <NEW_LINE> self.softmax = nn.Softmax(dim=-1) <NEW_LINE> self.classifier = nn.Linear(self.model_dim, self.num_labels) <NEW_LINE> self.gru = nn.GRU(hidden_size, hidden_size, n_layers, dropout=(0 if n_layers == 1 else dropout), bidirectional=bidirectional) <NEW_LINE> <DEDENT> def forward( self, x, ): <NEW_LINE> <INDENT> x = x.squeeze() <NEW_LINE> x = x.permute(2, 0, 1) <NEW_LINE> outputs, _ = self.gru(x) <NEW_LINE> if self.bidirectional: <NEW_LINE> <INDENT> outputs = outputs[:, :, :self.hidden_size] + outputs[:, :, self.hidden_size:] <NEW_LINE> <DEDENT> return outputs.transpose(0, 1)
:Args: hidden_size: number of the positions n_layers: number of the rnn layers
6259900a925a0f43d25e8bfa
class RockpaperscissorsTest(PluginTest): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.test = self.load_plugin(rockpaperscissors) <NEW_LINE> <DEDENT> def test_1_r_vs_p(self): <NEW_LINE> <INDENT> umove = "r" <NEW_LINE> jmove = "p" <NEW_LINE> result = self.test.game(umove, jmove) <NEW_LINE> self.assertEqual(result, "L") <NEW_LINE> <DEDENT> def test_2_r_vs_s(self): <NEW_LINE> <INDENT> umove = "r" <NEW_LINE> jmove = "s" <NEW_LINE> result = self.test.game(umove, jmove) <NEW_LINE> self.assertEqual(result, "W") <NEW_LINE> <DEDENT> def test_3_r_vs_r(self): <NEW_LINE> <INDENT> umove = "r" <NEW_LINE> jmove = "r" <NEW_LINE> result = self.test.game(umove, jmove) <NEW_LINE> self.assertEqual(result, "T") <NEW_LINE> <DEDENT> def test_4_p_vs_r(self): <NEW_LINE> <INDENT> umove = "p" <NEW_LINE> jmove = "r" <NEW_LINE> result = self.test.game(umove, jmove) <NEW_LINE> self.assertEqual(result, "W") <NEW_LINE> <DEDENT> def test_5_p_vs_s(self): <NEW_LINE> <INDENT> umove = "p" <NEW_LINE> jmove = "s" <NEW_LINE> result = self.test.game(umove, jmove) <NEW_LINE> self.assertEqual(result, "L") <NEW_LINE> <DEDENT> def test_6_p_vs_p(self): <NEW_LINE> <INDENT> umove = "p" <NEW_LINE> jmove = "p" <NEW_LINE> result = self.test.game(umove, jmove) <NEW_LINE> self.assertEqual(result, "T") <NEW_LINE> <DEDENT> def test_7_s_vs_p(self): <NEW_LINE> <INDENT> umove = "s" <NEW_LINE> jmove = "p" <NEW_LINE> result = self.test.game(umove, jmove) <NEW_LINE> self.assertEqual(result, "W") <NEW_LINE> <DEDENT> def test_8_s_vs_r(self): <NEW_LINE> <INDENT> umove = "s" <NEW_LINE> jmove = "r" <NEW_LINE> result = self.test.game(umove, jmove) <NEW_LINE> self.assertEqual(result, "L") <NEW_LINE> <DEDENT> def test_9_s_vs_s(self): <NEW_LINE> <INDENT> umove = "s" <NEW_LINE> jmove = "s" <NEW_LINE> result = self.test.game(umove, jmove) <NEW_LINE> self.assertEqual(result, "T") <NEW_LINE> <DEDENT> if __name__ == '__main__': <NEW_LINE> <INDENT> unittest.main()
This class is testing the rockpaperscissors plugin
6259900a0a366e3fb87dd5ae
class LogForwardingProfileMatchList(VersionedPanObject): <NEW_LINE> <INDENT> ROOT = Root.VSYS <NEW_LINE> SUFFIX = ENTRY <NEW_LINE> CHILDTYPES = ( "objects.LogForwardingProfileMatchListAction", ) <NEW_LINE> def _setup(self): <NEW_LINE> <INDENT> self._xpaths.add_profile(value='/match-list') <NEW_LINE> params = [] <NEW_LINE> params.append(VersionedParamPath( 'description', path='action-desc')) <NEW_LINE> params.append(VersionedParamPath( 'log_type', path='log-type', values=['traffic', 'threat', 'wildfire', 'url', 'data', 'gtp', 'tunnel', 'auth'])) <NEW_LINE> params[-1].add_profile( '8.1.0', path='log-type', values=['traffic', 'threat', 'wildfire', 'url', 'data', 'gtp', 'tunnel', 'auth', 'sctp']) <NEW_LINE> params.append(VersionedParamPath( 'filter', path='filter')) <NEW_LINE> params.append(VersionedParamPath( 'send_to_panorama', vartype='yesno', path='send-to-panorama')) <NEW_LINE> params.append(VersionedParamPath( 'snmp_profiles', vartype='member', path='send-snmptrap')) <NEW_LINE> params.append(VersionedParamPath( 'email_profiles', vartype='member', path='send-email')) <NEW_LINE> params.append(VersionedParamPath( 'syslog_profiles', vartype='member', path='send-syslog')) <NEW_LINE> params.append(VersionedParamPath( 'http_profiles', vartype='member', path='send-http')) <NEW_LINE> self._params = tuple(params)
A log forwarding profile match list entry. Note: This is valid for PAN-OS 8.0+ Args: name (str): The name description (str): Description log_type (str): Log type. Valid values are traffic, threat, wildfire, url, data, gtp, tunnel, auth, or sctp (PAN-OS 8.1+). filter (str): The filter. send_to_panorama (bool): Send to panorama or not snmp_profiles (str/list): List of SnmpServerProfiles. email_profiles (str/list): List of EmailServerProfiles. syslog_profiles (str/list): List of SyslogServerProfiles. http_profiles (str/list): List of HttpServerProfiles.
6259900a21a7993f00c66b39
class ExitTests(StashTestCase): <NEW_LINE> <INDENT> def test_help(self): <NEW_LINE> <INDENT> output = self.run_command("exit --help", exitcode=0) <NEW_LINE> self.assertIn("-h", output) <NEW_LINE> self.assertIn("--help", output) <NEW_LINE> self.assertIn("status", output) <NEW_LINE> self.assertIn("exit", output) <NEW_LINE> <DEDENT> def test_exit_default(self): <NEW_LINE> <INDENT> output = self.run_command("exit", exitcode=0).replace("\n", "") <NEW_LINE> self.assertEqual(output, "") <NEW_LINE> <DEDENT> def test_exit_0(self): <NEW_LINE> <INDENT> output = self.run_command("exit 0", exitcode=0).replace("\n", "") <NEW_LINE> self.assertEqual(output, "") <NEW_LINE> <DEDENT> def test_exit_1(self): <NEW_LINE> <INDENT> output = self.run_command("exit 1", exitcode=1).replace("\n", "") <NEW_LINE> self.assertEqual(output, "") <NEW_LINE> <DEDENT> def test_exit_0_to_255(self): <NEW_LINE> <INDENT> for i in range(256): <NEW_LINE> <INDENT> output = self.run_command("exit " + str(i), exitcode=i).replace("\n", "") <NEW_LINE> self.assertEqual(output, "")
Tests for the 'exit' command.
6259900a0a366e3fb87dd5b2
class PoliticalSpot(MildModeratedModel): <NEW_LINE> <INDENT> document = models.ForeignKey(PoliticalBuy, verbose_name="Political Buy") <NEW_LINE> airing_start_date = models.DateField(blank=True, null=True) <NEW_LINE> airing_end_date = models.DateField(blank=True, null=True) <NEW_LINE> airing_days = wf_fields.WeekdayField(blank=True) <NEW_LINE> timeslot_begin = models.TimeField(blank=True, null=True) <NEW_LINE> timeslot_end = models.TimeField(blank=True, null=True) <NEW_LINE> show_name = models.CharField(blank=True, max_length=100) <NEW_LINE> broadcast_length = timedelta.TimedeltaField(blank=True, null=True, help_text="The easiest way to enter time is as <em>XX minutes, YY seconds</em> or <em>YY seconds</em>.") <NEW_LINE> num_spots = models.IntegerField(blank=True, null=True, verbose_name="Number of Spots") <NEW_LINE> rate = models.DecimalField(blank=True, null=True, max_digits=9, decimal_places=2, help_text="Dollar cost for each spot") <NEW_LINE> preemptable = models.NullBooleanField(default=None, blank=True, null=True) <NEW_LINE> def documentcloud_doc(): <NEW_LINE> <INDENT> doc = "The documentcloud_doc property." <NEW_LINE> def fget(self): <NEW_LINE> <INDENT> if self.document: <NEW_LINE> <INDENT> return self.document.documentcloud_doc <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> return locals() <NEW_LINE> <DEDENT> documentcloud_doc = property(**documentcloud_doc()) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> name_string = u'PoliticalSpot' <NEW_LINE> if self.document and self.document.advertiser: <NEW_LINE> <INDENT> name_string = u'{0}'.format(self.document.advertiser) <NEW_LINE> <DEDENT> if self.show_name: <NEW_LINE> <INDENT> name_string = u'{0}: "{1}"'.format(name_string, self.show_name) <NEW_LINE> <DEDENT> if self.airing_start_date: <NEW_LINE> <INDENT> name_string = u'{0} ({1} to {2})'.format(name_string, self.airing_start_date, self.airing_end_date) <NEW_LINE> <DEDENT> return name_string
Information particular to a political ad spot (e.g., a candidate ad)
6259900abf627c535bcb206f
class Bot8(Bot,metaclass=Bot8Meta): <NEW_LINE> <INDENT> def response(self,name,evaluation,history,slot_ctrs,current_budget, initial_budget): <NEW_LINE> <INDENT> step = len(history) <NEW_LINE> if step == 0: <NEW_LINE> <INDENT> return evaluation <NEW_LINE> <DEDENT> if evaluation > 6: <NEW_LINE> <INDENT> return Bot4().response(name,evaluation,history,slot_ctrs,current_budget, initial_budget) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Bot5().response(name,evaluation,history,slot_ctrs,current_budget, initial_budget) <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "Bot8" <NEW_LINE> <DEDENT> def strategy(self): <NEW_LINE> <INDENT> return "Combination of the above bots based on the current badget or the advertiser value for the current query"
Combination of the above bots based on the current badget or the advertiser value for the current query
6259900a627d3e7fe0e07a5c
class CachedProject(object): <NEW_LINE> <INDENT> def __init__(self, cache, loader, m): <NEW_LINE> <INDENT> self.m = m <NEW_LINE> self.inst_dir = loader.get_project_install_dir(m) <NEW_LINE> self.project_hash = loader.get_project_hash(m) <NEW_LINE> self.ctx = loader.ctx_gen.get_context(m.name) <NEW_LINE> self.loader = loader <NEW_LINE> self.cache = cache <NEW_LINE> self.cache_file_name = "-".join( ( m.name, self.ctx.get("os"), self.ctx.get("distro") or "none", self.ctx.get("distro_vers") or "none", self.project_hash, "buildcache.tgz", ) ) <NEW_LINE> <DEDENT> def is_cacheable(self): <NEW_LINE> <INDENT> return self.cache and self.m.shipit_project is None <NEW_LINE> <DEDENT> def was_cached(self): <NEW_LINE> <INDENT> cached_marker = os.path.join(self.inst_dir, ".getdeps-cached-build") <NEW_LINE> return os.path.exists(cached_marker) <NEW_LINE> <DEDENT> def download(self): <NEW_LINE> <INDENT> if self.is_cacheable() and not os.path.exists(self.inst_dir): <NEW_LINE> <INDENT> print("check cache for %s" % self.cache_file_name) <NEW_LINE> dl_dir = os.path.join(self.loader.build_opts.scratch_dir, "downloads") <NEW_LINE> if not os.path.exists(dl_dir): <NEW_LINE> <INDENT> os.makedirs(dl_dir) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> target_file_name = os.path.join(dl_dir, self.cache_file_name) <NEW_LINE> if self.cache.download_to_file(self.cache_file_name, target_file_name): <NEW_LINE> <INDENT> tf = tarfile.open(target_file_name, "r") <NEW_LINE> print( "Extracting %s -> %s..." % (self.cache_file_name, self.inst_dir) ) <NEW_LINE> tf.extractall(self.inst_dir) <NEW_LINE> cached_marker = os.path.join(self.inst_dir, ".getdeps-cached-build") <NEW_LINE> with open(cached_marker, "w") as f: <NEW_LINE> <INDENT> f.write("\n") <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> <DEDENT> except Exception as exc: <NEW_LINE> <INDENT> print("%s" % str(exc)) <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> def upload(self): <NEW_LINE> <INDENT> if self.is_cacheable(): <NEW_LINE> <INDENT> tempdir = tempfile.mkdtemp() <NEW_LINE> tarfilename = os.path.join(tempdir, self.cache_file_name) <NEW_LINE> print("Archiving for cache: %s..." % tarfilename) <NEW_LINE> tf = tarfile.open(tarfilename, "w:gz") <NEW_LINE> tf.add(self.inst_dir, arcname=".") <NEW_LINE> tf.close() <NEW_LINE> try: <NEW_LINE> <INDENT> self.cache.upload_from_file(self.cache_file_name, tarfilename) <NEW_LINE> <DEDENT> except Exception as exc: <NEW_LINE> <INDENT> print( "Failed to upload to cache (%s), continue anyway" % str(exc), file=sys.stderr, ) <NEW_LINE> <DEDENT> shutil.rmtree(tempdir)
A helper that allows calling the cache logic for a project from both the build and the fetch code
6259900a3cc13d1c6d46630b
class LearnerNotFoundError(BaseError): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> course_id = kwargs.pop('course_id') <NEW_LINE> username = kwargs.pop('username') <NEW_LINE> super(LearnerNotFoundError, self).__init__(*args, **kwargs) <NEW_LINE> self.message = self.message_template.format(username=username, course_id=course_id) <NEW_LINE> <DEDENT> @property <NEW_LINE> def message_template(self): <NEW_LINE> <INDENT> return 'Learner {username} not found for course {course_id}.'
Raise learner not found for a course.
6259900a507cdc57c63a5962
class d: <NEW_LINE> <INDENT> pass
integrates field with respect to withRespectTo. arguments must be 1 dimensional numpy arrays. assumes elements in these arrays represent points on a continuous mathmatical function. returns result as an array. c is the constant of integration and defaults to zero
6259900a462c4b4f79dbc5cb
class Aq_Species (Species): <NEW_LINE> <INDENT> def __init__(self, name): <NEW_LINE> <INDENT> Species.__init__(self, name) <NEW_LINE> self.f_act_coef = 'Davis' <NEW_LINE> <DEDENT> def set_charge(self, charge): <NEW_LINE> <INDENT> self.charge = charge <NEW_LINE> <DEDENT> def set_gfw(self, molar_weight): <NEW_LINE> <INDENT> self.gfw = molar_weight <NEW_LINE> <DEDENT> def set_ionsizeparameter(self, a): <NEW_LINE> <INDENT> self.ionsizepar = a*1e-8 <NEW_LINE> <DEDENT> def set_deviationionsizeparameter(self, b): <NEW_LINE> <INDENT> self.devionsizepar = b <NEW_LINE> <DEDENT> def Set_f_activity_coefficient (self, String_name_func): <NEW_LINE> <INDENT> self.f_act_coef = String_name_func <NEW_LINE> <DEDENT> def it_is_charge(self, boolean): <NEW_LINE> <INDENT> self.charge_element = boolean <NEW_LINE> <DEDENT> def log_coefficient_activity(self, ionic_strength, c=0, A=0, B = 0, a = 0, b = 0, z = 0): <NEW_LINE> <INDENT> if hasattr(self, 'charge'): <NEW_LINE> <INDENT> z = self.charge <NEW_LINE> <DEDENT> if hasattr(self, 'ionsizepar'): <NEW_LINE> <INDENT> a = self.ionsizepar <NEW_LINE> <DEDENT> if hasattr(self, 'devionsizepar'): <NEW_LINE> <INDENT> b = self.devionsizepar <NEW_LINE> <DEDENT> log_act_coef = afm.f_log_list(self.f_act_coef, ionic_strength, c, A, B, a, b, z) <NEW_LINE> return log_act_coef <NEW_LINE> <DEDENT> def dgamma_dionicstrength(self, actcoeff, ionic_strength, z=0, A=0): <NEW_LINE> <INDENT> if hasattr(self, 'charge'): <NEW_LINE> <INDENT> z = self.charge <NEW_LINE> <DEDENT> return afm.dgamma_dionicstrength(self.f_act_coef, actcoeff, ionic_strength, z, A)
properties: f_act_coef e.g. Type of function for calculating the activity coefficient charge e.g. Value of charge for instance H+ is 1, Mg+2 is 2, Cl- is -1, ... gfw e.g. The gram formula weight for the species 1 gram of X equal to 1 mol of X ionsizepar e.g. Parameter that can be needed for calculating the ionic strenght devionsizepar e.g. Parameter that can be needed for calculating the ionic strenght charge_element e.g. Special properties that indicates that the species in consideration is charge, so what in PhreeQc would be E. methods: set_charge(charge) set_gfw(molar_weight) set_ionsizeparameter(a) set_deviationionsizeparameter(b) Set_f_activity_coefficient (String_name_func) it_is_charge(boolean) log_coefficient_activity( ionic_strength, c=0, A=0, B = 0, a = 0, b = 0, z = 0) dgamma_dionicstrength(actcoeff, ionic_strength, z=0, A=0)
6259900a0a366e3fb87dd5b6
class TestTypes(object): <NEW_LINE> <INDENT> def check_type(self, result, expected, msg): <NEW_LINE> <INDENT> eq_(set(result.keys()), set(expected.keys()), 'Mismatch: %s keys' % msg) <NEW_LINE> for key in expected: <NEW_LINE> <INDENT> eq_(set(result[key]), set(expected[key]), 'Mismatch: %s - %s' % (msg, key)) <NEW_LINE> <DEDENT> <DEDENT> def test_detect_types(self): <NEW_LINE> <INDENT> for dataset in config['datasets']: <NEW_LINE> <INDENT> for uri in dataset['uris']: <NEW_LINE> <INDENT> data = Data(uri) <NEW_LINE> result = al.types(data) <NEW_LINE> self.check_type(result, dataset['types'], dataset['table']) <NEW_LINE> <DEDENT> print('for %s on %s' % (dataset['table'], getengine(dataset['uris'])))
Test autolysis.types
6259900a507cdc57c63a5964
class TestDygraphIfElseNet(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.x = np.random.random([10, 16]).astype('float32') <NEW_LINE> self.Net = NetWithControlFlowIf <NEW_LINE> <DEDENT> def _run_static(self): <NEW_LINE> <INDENT> return self._run(to_static=True) <NEW_LINE> <DEDENT> def _run_dygraph(self): <NEW_LINE> <INDENT> return self._run(to_static=False) <NEW_LINE> <DEDENT> def _run(self, to_static=False): <NEW_LINE> <INDENT> prog_trans = ProgramTranslator() <NEW_LINE> prog_trans.enable(to_static) <NEW_LINE> with fluid.dygraph.guard(place): <NEW_LINE> <INDENT> net = self.Net() <NEW_LINE> x_v = fluid.dygraph.to_variable(self.x) <NEW_LINE> ret = net(x_v) <NEW_LINE> return ret.numpy() <NEW_LINE> <DEDENT> <DEDENT> def test_ast_to_func(self): <NEW_LINE> <INDENT> self.assertTrue((self._run_dygraph() == self._run_static()).all())
TestCase for the transformation from control flow `if/else` dependent on tensor in Dygraph into Static `fluid.layers.cond`.
6259900a0a366e3fb87dd5b8
class Cellule() : <NEW_LINE> <INDENT> def __init__(self, data, aretes) : <NEW_LINE> <INDENT> self.cellid = data['cellid'] <NEW_LINE> self.x = data['x'] <NEW_LINE> self.y = data['y'] <NEW_LINE> self.radius = data['radius'] <NEW_LINE> self.player = -1 <NEW_LINE> self.offunits = 0 <NEW_LINE> self.offsize = data['offsize'] <NEW_LINE> self.offprod = data['prod'] <NEW_LINE> self.coeff = 0 <NEW_LINE> self.defunits = 0 <NEW_LINE> self.defsize = data['defsize'] <NEW_LINE> self.defprod = 1 <NEW_LINE> self.neighbours = {} <NEW_LINE> for arete in aretes : <NEW_LINE> <INDENT> if arete['cellid1'] == self.cellid : <NEW_LINE> <INDENT> self.neighbours[arete['cellid2']] = arete['distance'] <NEW_LINE> <DEDENT> if arete['cellid2'] == self.cellid : <NEW_LINE> <INDENT> self.neighbours[arete['cellid1']] = arete['distance'] <NEW_LINE> <DEDENT> <DEDENT> if self.offprod == 3: <NEW_LINE> <INDENT> self.coeff = 1 <NEW_LINE> <DEDENT> elif self.offprod == 2: <NEW_LINE> <INDENT> self.coeff = 1.5 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.coeff = 2 <NEW_LINE> <DEDENT> <DEDENT> def update(self, data) : <NEW_LINE> <INDENT> self.defunits = data['defunits'] <NEW_LINE> self.offunits = data['offunits'] <NEW_LINE> self.player = data['owner'] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.cellid) + "owner : " + str(self.player) + "\nUnité offensive : " + str(self.offunits) + "/" + str(self.offsize) + " \tCadence de production : " + str(self.offprod) + "\nUnité défensive : " + str(self.defunits) + "/" + str(self.defsize) + " \tCadence de production : " + str(self.defprod)
Initialise une cellule @param data : informations sur les cellules et obtenues grâce à la chaine d'initialisation qui a été récupérée puis parsée @param aretes : informations sur les voisins de chaque cellule
6259900a925a0f43d25e8c06
@graphql_scalar('ID') <NEW_LINE> class GraphQlLaxIdDescriptor(GraphQlScalarDescriptor): <NEW_LINE> <INDENT> def graphql_to_python(self, value): <NEW_LINE> <INDENT> if isinstance(value, bool): <NEW_LINE> <INDENT> raise TypeError('Input is not a string or an integer') <NEW_LINE> <DEDENT> elif isinstance(value, (int, long)): <NEW_LINE> <INDENT> if not (-2 ** 31 <= value < 2 ** 31): <NEW_LINE> <INDENT> raise ValueError( 'In GraphQL, integer values must be between -2^31 and ' '2^31 - 1') <NEW_LINE> <DEDENT> <DEDENT> elif not isinstance(value, basestring): <NEW_LINE> <INDENT> raise TypeError('Input is not a string or an integer') <NEW_LINE> <DEDENT> return str(value) <NEW_LINE> <DEDENT> def python_to_graphql(self, value): <NEW_LINE> <INDENT> return str(value)
Lax GraphQlScalarDescriptor for the "ID" type. A non-strictly validating GraphQlScalarDescriptor for the built-in ID type.
6259900b0a366e3fb87dd5bc
class YeelightDevice: <NEW_LINE> <INDENT> def __init__(self, hass, ipaddr, config): <NEW_LINE> <INDENT> self._hass = hass <NEW_LINE> self._config = config <NEW_LINE> self._ipaddr = ipaddr <NEW_LINE> self._name = config.get(CONF_NAME) <NEW_LINE> self._model = config.get(CONF_MODEL) <NEW_LINE> self._bulb_device = None <NEW_LINE> self._available = False <NEW_LINE> <DEDENT> @property <NEW_LINE> def bulb(self): <NEW_LINE> <INDENT> if self._bulb_device is None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._bulb_device = Bulb(self._ipaddr, model=self._model) <NEW_LINE> self.update() <NEW_LINE> self._available = True <NEW_LINE> <DEDENT> except BulbException as ex: <NEW_LINE> <INDENT> self._available = False <NEW_LINE> _LOGGER.error("Failed to connect to bulb %s, %s: %s", self._ipaddr, self._name, ex) <NEW_LINE> <DEDENT> <DEDENT> return self._bulb_device <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @property <NEW_LINE> def config(self): <NEW_LINE> <INDENT> return self._config <NEW_LINE> <DEDENT> @property <NEW_LINE> def ipaddr(self): <NEW_LINE> <INDENT> return self._ipaddr <NEW_LINE> <DEDENT> @property <NEW_LINE> def available(self): <NEW_LINE> <INDENT> return self._available <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_nightlight_enabled(self) -> bool: <NEW_LINE> <INDENT> if self.bulb is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.bulb.last_properties.get('active_mode') == '1' <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_nightlight_supported(self) -> bool: <NEW_LINE> <INDENT> return self.bulb.get_model_specs().get('night_light', False) <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_ambilight_supported(self) -> bool: <NEW_LINE> <INDENT> return self.bulb.get_model_specs().get('background_light', False) <NEW_LINE> <DEDENT> def turn_on(self, duration=DEFAULT_TRANSITION, light_type=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.bulb.turn_on(duration=duration, light_type=light_type) <NEW_LINE> <DEDENT> except BulbException as ex: <NEW_LINE> <INDENT> _LOGGER.error("Unable to turn the bulb on: %s", ex) <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> def turn_off(self, duration=DEFAULT_TRANSITION, light_type=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.bulb.turn_off(duration=duration, light_type=light_type) <NEW_LINE> <DEDENT> except BulbException as ex: <NEW_LINE> <INDENT> _LOGGER.error("Unable to turn the bulb off: %s", ex) <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> def update(self): <NEW_LINE> <INDENT> if not self.bulb: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.bulb.get_properties(UPDATE_REQUEST_PROPERTIES) <NEW_LINE> self._available = True <NEW_LINE> <DEDENT> except BulbException as ex: <NEW_LINE> <INDENT> if self._available: <NEW_LINE> <INDENT> _LOGGER.error("Unable to update bulb status: %s", ex) <NEW_LINE> <DEDENT> self._available = False <NEW_LINE> <DEDENT> dispatcher_send(self._hass, DATA_UPDATED.format(self._ipaddr))
Represents single Yeelight device.
6259900b627d3e7fe0e07a64
class Patient(object): <NEW_LINE> <INDENT> def __init__(self, viruses, maxPop): <NEW_LINE> <INDENT> self.viruses = viruses <NEW_LINE> self.maxPop = maxPop <NEW_LINE> <DEDENT> def getViruses(self): <NEW_LINE> <INDENT> return self.viruses <NEW_LINE> <DEDENT> def getMaxPop(self): <NEW_LINE> <INDENT> return self.maxPop <NEW_LINE> <DEDENT> def getTotalPop(self): <NEW_LINE> <INDENT> return len(self.viruses) <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> it_viruses = self.viruses <NEW_LINE> for virus in it_viruses: <NEW_LINE> <INDENT> if virus.doesClear(): <NEW_LINE> <INDENT> self.viruses.remove(virus) <NEW_LINE> <DEDENT> popDensity = float(self.getTotalPop())/self.getMaxPop() <NEW_LINE> if popDensity == 0: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.viruses.append(virus.reproduce(popDensity)) <NEW_LINE> <DEDENT> except NoChildException: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> return self.getTotalPop()
Representation of a simplified patient. The patient does not take any drugs and his/her virus populations have no drug resistance.
6259900b3cc13d1c6d466313
class Problem10(TwoPointBVP): <NEW_LINE> <INDENT> m = [2]*256 <NEW_LINE> a = 0 <NEW_LINE> b = 1 <NEW_LINE> n_a = 256 <NEW_LINE> linear = False <NEW_LINE> homogenous = True <NEW_LINE> vectorized = True <NEW_LINE> def f(self, x, u): <NEW_LINE> <INDENT> return np.zeros((self.n_a, x.size)) <NEW_LINE> <DEDENT> def df(self, x, u): <NEW_LINE> <INDENT> return np.zeros((self.n_a, 2*self.n_a, x.size)) <NEW_LINE> <DEDENT> def g(self, u_a, u_b): <NEW_LINE> <INDENT> return np.concatenate([u_a[::2] - 0, u_b[::2] - 1]) <NEW_LINE> <DEDENT> def dg(self, u_a, u_b): <NEW_LINE> <INDENT> du_a = np.zeros((2*self.n_a, 2*self.n_a)) <NEW_LINE> du_b = np.zeros((2*self.n_a, 2*self.n_a)) <NEW_LINE> i = np.arange(0, self.n_a) <NEW_LINE> j = np.arange(0, 2*self.n_a, 2) <NEW_LINE> du_a[i,j] = 1 <NEW_LINE> du_b[i+self.n_a,j] = 1 <NEW_LINE> return (du_a, du_b) <NEW_LINE> <DEDENT> guess = None <NEW_LINE> def exact_solution(self, x): <NEW_LINE> <INDENT> x = np.asarray(x) <NEW_LINE> v = np.zeros((x.size, self.n_a*2)) <NEW_LINE> v[:,::2] = x[:,None] <NEW_LINE> v[:,1::2] = 1 <NEW_LINE> return v
A big trivial test problem:: y'' = 0 y(0) = 0, y(1) = 1
6259900b462c4b4f79dbc5d3
class GymDiscreteProblem(problem.Problem): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(GymDiscreteProblem, self).__init__(*args, **kwargs) <NEW_LINE> self._env = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def env_name(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @property <NEW_LINE> def env(self): <NEW_LINE> <INDENT> if self._env is None: <NEW_LINE> <INDENT> self._env = gym.make(self.env_name) <NEW_LINE> <DEDENT> return self._env <NEW_LINE> <DEDENT> @property <NEW_LINE> def num_actions(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @property <NEW_LINE> def num_rewards(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @property <NEW_LINE> def num_steps(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @property <NEW_LINE> def num_shards(self): <NEW_LINE> <INDENT> return 10 <NEW_LINE> <DEDENT> @property <NEW_LINE> def num_dev_shards(self): <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> def get_action(self, observation=None): <NEW_LINE> <INDENT> return self.env.action_space.sample() <NEW_LINE> <DEDENT> def hparams(self, defaults, unused_model_hparams): <NEW_LINE> <INDENT> p = defaults <NEW_LINE> p.input_modality = {"inputs": ("image:identity", 256), "inputs_prev": ("image:identity", 256), "reward": ("symbol:identity", self.num_rewards), "action": ("symbol:identity", self.num_actions)} <NEW_LINE> p.target_modality = ("image:identity", 256) <NEW_LINE> p.input_space_id = problem.SpaceID.IMAGE <NEW_LINE> p.target_space_id = problem.SpaceID.IMAGE <NEW_LINE> <DEDENT> def generator(self, data_dir, tmp_dir): <NEW_LINE> <INDENT> self.env.reset() <NEW_LINE> action = self.get_action() <NEW_LINE> prev_observation, observation = None, None <NEW_LINE> for _ in range(self.num_steps): <NEW_LINE> <INDENT> prev_prev_observation = prev_observation <NEW_LINE> prev_observation = observation <NEW_LINE> observation, reward, done, _ = self.env.step(action) <NEW_LINE> action = self.get_action(observation) <NEW_LINE> if done: <NEW_LINE> <INDENT> self.env.reset() <NEW_LINE> <DEDENT> def flatten(nparray): <NEW_LINE> <INDENT> flat1 = [x for sublist in nparray.tolist() for x in sublist] <NEW_LINE> return [x for sublist in flat1 for x in sublist] <NEW_LINE> <DEDENT> if prev_prev_observation is not None: <NEW_LINE> <INDENT> yield {"inputs_prev": flatten(prev_prev_observation), "inputs": flatten(prev_observation), "action": [action], "done": [done], "reward": [reward], "targets": flatten(observation)} <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def generate_data(self, data_dir, tmp_dir, task_id=-1): <NEW_LINE> <INDENT> train_paths = self.training_filepaths( data_dir, self.num_shards, shuffled=False) <NEW_LINE> dev_paths = self.dev_filepaths( data_dir, self.num_dev_shards, shuffled=False) <NEW_LINE> all_paths = train_paths + dev_paths <NEW_LINE> generator_utils.generate_files( self.generator(data_dir, tmp_dir), all_paths) <NEW_LINE> generator_utils.shuffle_dataset(all_paths)
Gym environment with discrete actions and rewards.
6259900b925a0f43d25e8c0c
class FractionalOverheadSuite: <NEW_LINE> <INDENT> def setup(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> from time import process_time <NEW_LINE> self.time = process_time <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> from time import clock <NEW_LINE> self.time = clock <NEW_LINE> <DEDENT> from tqdm import tqdm <NEW_LINE> self.tqdm = tqdm <NEW_LINE> try: <NEW_LINE> <INDENT> self.iterable = xrange(int(6e6)) <NEW_LINE> <DEDENT> except NameError: <NEW_LINE> <INDENT> self.iterable = range(int(6e6)) <NEW_LINE> <DEDENT> t0 = self.time() <NEW_LINE> [0 for _ in self.iterable] <NEW_LINE> t1 = self.time() <NEW_LINE> self.t = t1 - t0 <NEW_LINE> <DEDENT> def track_tqdm(self): <NEW_LINE> <INDENT> t0 = self.time() <NEW_LINE> [0 for _ in self.tqdm(self.iterable)] <NEW_LINE> t1 = self.time() <NEW_LINE> return (t1 - t0 - self.t) / self.t <NEW_LINE> <DEDENT> def track_optimsed(self): <NEW_LINE> <INDENT> t0 = self.time() <NEW_LINE> [0 for _ in self.tqdm(self.iterable, miniters=6e5, smoothing=0)] <NEW_LINE> t1 = self.time() <NEW_LINE> return (t1 - t0 - self.t) / self.t
An example benchmark that times the performance of various kinds of iterating over dictionaries in Python.
6259900b56b00c62f0fb348b
class ExportOpenGLRenderImageOperator(bpy.types.Operator, ExportHelper): <NEW_LINE> <INDENT> bl_idname = "photogrammetry_importer.export_opengl_render_image" <NEW_LINE> bl_label = "Export Point Cloud Rendering as Image" <NEW_LINE> bl_description = "Use a single camera to render the point cloud." <NEW_LINE> filename_ext = "" <NEW_LINE> @classmethod <NEW_LINE> def poll(cls, context): <NEW_LINE> <INDENT> cam = get_selected_camera() <NEW_LINE> return cam is not None <NEW_LINE> <DEDENT> def execute(self, context): <NEW_LINE> <INDENT> log_report("INFO", "Export opengl render as image: ...", self) <NEW_LINE> scene = context.scene <NEW_LINE> save_point_size = scene.opengl_panel_settings.save_point_size <NEW_LINE> filename_ext = scene.opengl_panel_settings.render_file_format <NEW_LINE> ofp = self.filepath + "." + filename_ext <NEW_LINE> log_report("INFO", "Output File Path: " + ofp, self) <NEW_LINE> image_name = "OpenGL Export" <NEW_LINE> cam = get_selected_camera() <NEW_LINE> draw_manager = DrawManager.get_singleton() <NEW_LINE> coords, colors = draw_manager.get_coords_and_colors(visible_only=True) <NEW_LINE> render_opengl_image(image_name, cam, coords, colors, save_point_size) <NEW_LINE> save_alpha = scene.opengl_panel_settings.save_alpha <NEW_LINE> save_image_to_disk(image_name, ofp, save_alpha) <NEW_LINE> log_report("INFO", "Save opengl render as image: Done", self) <NEW_LINE> return {"FINISHED"}
An Operator to save a rendering of the point cloud to disk.
6259900b15fb5d323ce7f90d
class KaraokeView(drf_generics.RetrieveUpdateAPIView): <NEW_LINE> <INDENT> queryset = models.Karaoke.objects.all() <NEW_LINE> serializer_class = serializers.KaraokeSerializer <NEW_LINE> permission_classes = [ IsAuthenticated, permissions.IsPlaylistManager | internal_permissions.IsReadOnly, ] <NEW_LINE> def perform_update(self, serializer): <NEW_LINE> <INDENT> super().perform_update(serializer) <NEW_LINE> karaoke = serializer.instance <NEW_LINE> if "date_stop" in serializer.validated_data: <NEW_LINE> <INDENT> existing_job_id = cache.get(KARAOKE_JOB_NAME) <NEW_LINE> if existing_job_id is not None: <NEW_LINE> <INDENT> existing_job = scheduler.get_job(existing_job_id) <NEW_LINE> if existing_job is not None: <NEW_LINE> <INDENT> existing_job.remove() <NEW_LINE> logger.debug("Existing date stop job was found and unscheduled") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cache.delete(KARAOKE_JOB_NAME) <NEW_LINE> <DEDENT> <DEDENT> if karaoke.date_stop is not None: <NEW_LINE> <INDENT> job = scheduler.add_job( clear_date_stop, "date", run_date=karaoke.date_stop ) <NEW_LINE> cache.set(KARAOKE_JOB_NAME, job.id) <NEW_LINE> logger.debug("New date stop job was scheduled") <NEW_LINE> <DEDENT> <DEDENT> if "ongoing" in serializer.validated_data and not karaoke.ongoing: <NEW_LINE> <INDENT> send_to_channel("playlist.device", "send_idle") <NEW_LINE> player = models.Player.cache.create(karaoke=karaoke) <NEW_LINE> models.PlaylistEntry.objects.all().delete() <NEW_LINE> models.PlayerError.objects.all().delete() <NEW_LINE> return <NEW_LINE> <DEDENT> if ( karaoke.ongoing and "player_play_next_song" in serializer.validated_data and karaoke.player_play_next_song ): <NEW_LINE> <INDENT> player, _ = models.Player.cache.get_or_create(karaoke=karaoke) <NEW_LINE> if player.playlist_entry is None: <NEW_LINE> <INDENT> next_playlist_entry = models.PlaylistEntry.objects.get_next() <NEW_LINE> if next_playlist_entry is not None: <NEW_LINE> <INDENT> send_to_channel( "playlist.device", "send_playlist_entry", data={"playlist_entry": next_playlist_entry}, ) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def get_object(self): <NEW_LINE> <INDENT> return models.Karaoke.objects.get_object()
Get or edit the kara status.
6259900b56b00c62f0fb348d
class _EBLFile: <NEW_LINE> <INDENT> def __init__(self, file_path, page_size): <NEW_LINE> <INDENT> self._file_path = file_path <NEW_LINE> self._page_size = page_size <NEW_LINE> self._page_index = 0 <NEW_LINE> self._num_pages = os.path.getsize(file_path) // self._page_size <NEW_LINE> if os.path.getsize(file_path) % self._page_size != 0: <NEW_LINE> <INDENT> self._num_pages += 1 <NEW_LINE> <DEDENT> <DEDENT> def get_next_mem_page(self): <NEW_LINE> <INDENT> with open(self._file_path, "rb") as file: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> read_bytes = file.read(self._page_size) <NEW_LINE> if not read_bytes: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if len(read_bytes) < self._page_size: <NEW_LINE> <INDENT> padded_array = bytearray(read_bytes) <NEW_LINE> padded_array.extend(repeat(0xFF, self._page_size - len(read_bytes))) <NEW_LINE> read_bytes = bytes(padded_array) <NEW_LINE> <DEDENT> yield read_bytes <NEW_LINE> self._page_index += 1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @property <NEW_LINE> def num_pages(self): <NEW_LINE> <INDENT> return self._num_pages <NEW_LINE> <DEDENT> @property <NEW_LINE> def page_index(self): <NEW_LINE> <INDENT> return self._page_index <NEW_LINE> <DEDENT> @property <NEW_LINE> def percent(self): <NEW_LINE> <INDENT> return ((self._page_index + 1) * 100) // self._num_pages
Helper class that represents a local firmware file in 'ebl' format.
6259900b15fb5d323ce7f90f
class ManagedClusterListResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'next_link': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'value': {'key': 'value', 'type': '[ManagedCluster]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, value: Optional[List["ManagedCluster"]] = None, **kwargs ): <NEW_LINE> <INDENT> super(ManagedClusterListResult, self).__init__(**kwargs) <NEW_LINE> self.value = value <NEW_LINE> self.next_link = None
The response from the List Managed Clusters operation. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The list of managed clusters. :vartype value: list[~azure.mgmt.containerservice.v2018_08_01_preview.models.ManagedCluster] :ivar next_link: The URL to get the next set of managed cluster results. :vartype next_link: str
6259900b627d3e7fe0e07a6a
class DebuggerClient: <NEW_LINE> <INDENT> def __init__(self, server_host, server_port): <NEW_LINE> <INDENT> self.host = server_host <NEW_LINE> self.port = int(server_port) <NEW_LINE> <DEDENT> def breakpoint(self): <NEW_LINE> <INDENT> import pydevd <NEW_LINE> from app.config.DevelopmentConfig import ENVIRONMENT <NEW_LINE> if ENVIRONMENT.lower() == 'development': <NEW_LINE> <INDENT> pydevd.settrace(self.host, port=self.port, stdoutToServer=True, stderrToServer=True)
Shell class that stores properties to be used by the debugger Exposes methods to be used for debugging purposes
6259900b507cdc57c63a5970
class GolemResourceReservation(models.Model): <NEW_LINE> <INDENT> _inherit = 'golem.resource.reservation' <NEW_LINE> resource_option_ids = fields.One2many(related="resource_id.option_ids") <NEW_LINE> selected_option_ids = fields.Many2many( 'golem.resource.option', string='Selected options', index=True, readonly=True, domain='[("resource_id", "=", resource_id)]', states={'draft': [('readonly', False)], 'confirmed': [('readonly', False)]})
GOLEM Resource Reservation Option Model
6259900b21a7993f00c66b4c
class StudentListView(ListView): <NEW_LINE> <INDENT> queryset = Student.objects.all().filter(gender="nan") <NEW_LINE> template_name = "student_list.html"
需要设置俩个主要内容 1.queryset:数据来源集合 2.template_name:模板名称
6259900bd164cc6175821b4e
@Seq2SeqEncoder.register("PointerNet") <NEW_LINE> class PointerNet(Seq2SeqEncoder): <NEW_LINE> <INDENT> def __init__(self, input_size: int, hidden_dim: int, lstm_layers: int = 2, dropout: float = 0.2, bidirectional=False): <NEW_LINE> <INDENT> super(PointerNet, self).__init__() <NEW_LINE> self.bidir = bidirectional <NEW_LINE> self._encoder = PointerNetEncoder(input_size, hidden_dim, lstm_layers, dropout, bidirectional) <NEW_LINE> self._decoder = PointerNetDecoder(input_size, hidden_dim) <NEW_LINE> self.decoder_input0 = Parameter(torch.FloatTensor(input_size), requires_grad=False) <NEW_LINE> nn.init.uniform_(self.decoder_input0, -1, 1) <NEW_LINE> <DEDENT> @overrides <NEW_LINE> def forward(self, embedded_inputs: torch.Tensor, passages_mask: torch.Tensor): <NEW_LINE> <INDENT> batch_size = embedded_inputs.size(0) <NEW_LINE> fake_inputs = self.decoder_input0.unsqueeze(0).expand(batch_size, -1) <NEW_LINE> encoder_hidden0 = self._encoder.init_hidden(batch_size) <NEW_LINE> encoder_outputs, encoder_hidden = self._encoder(embedded_inputs, encoder_hidden0) <NEW_LINE> if self.bidir: <NEW_LINE> <INDENT> hidden0 = (torch.cat(tuple(encoder_hidden[0][-2:]), dim=-1), torch.cat(tuple(encoder_hidden[1][-2:]), dim=-1)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> hidden0 = (encoder_hidden[0][-1], encoder_hidden[1][-1]) <NEW_LINE> <DEDENT> return self._decoder(embedded_inputs, hidden0, encoder_outputs, fake_inputs, passages_mask)
Pointer-Net
6259900b3cc13d1c6d46631b
class SenseVoltageSensor(SensorEntity): <NEW_LINE> <INDENT> _attr_native_unit_of_measurement = ELECTRIC_POTENTIAL_VOLT <NEW_LINE> _attr_extra_state_attributes = {ATTR_ATTRIBUTION: ATTRIBUTION} <NEW_LINE> _attr_icon = ICON <NEW_LINE> _attr_should_poll = False <NEW_LINE> _attr_available = False <NEW_LINE> def __init__( self, data, index, sense_monitor_id, ): <NEW_LINE> <INDENT> line_num = index + 1 <NEW_LINE> self._attr_name = f"L{line_num} Voltage" <NEW_LINE> self._attr_unique_id = f"{sense_monitor_id}-L{line_num}" <NEW_LINE> self._data = data <NEW_LINE> self._sense_monitor_id = sense_monitor_id <NEW_LINE> self._voltage_index = index <NEW_LINE> <DEDENT> async def async_added_to_hass(self): <NEW_LINE> <INDENT> self.async_on_remove( async_dispatcher_connect( self.hass, f"{SENSE_DEVICE_UPDATE}-{self._sense_monitor_id}", self._async_update_from_data, ) ) <NEW_LINE> <DEDENT> @callback <NEW_LINE> def _async_update_from_data(self): <NEW_LINE> <INDENT> new_state = round(self._data.active_voltage[self._voltage_index], 1) <NEW_LINE> if self._attr_available and self._attr_native_value == new_state: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self._attr_available = True <NEW_LINE> self._attr_native_value = new_state <NEW_LINE> self.async_write_ha_state()
Implementation of a Sense energy voltage sensor.
6259900b15fb5d323ce7f915
class StockState(models.Model): <NEW_LINE> <INDENT> section_id = models.CharField(max_length=100, db_index=True) <NEW_LINE> case_id = models.CharField(max_length=100, db_index=True) <NEW_LINE> product_id = models.CharField(max_length=100, db_index=True) <NEW_LINE> stock_on_hand = models.DecimalField(max_digits=20, decimal_places=5, default=Decimal(0)) <NEW_LINE> daily_consumption = models.DecimalField(max_digits=20, decimal_places=5, null=True) <NEW_LINE> last_modified_date = models.DateTimeField() <NEW_LINE> sql_product = models.ForeignKey(SQLProduct) <NEW_LINE> objects = ActiveManager() <NEW_LINE> include_archived = models.Manager() <NEW_LINE> @property <NEW_LINE> def months_remaining(self): <NEW_LINE> <INDENT> return months_of_stock_remaining( self.stock_on_hand, self.get_daily_consumption() ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def resupply_quantity_needed(self): <NEW_LINE> <INDENT> monthly_consumption = self.get_monthly_consumption() <NEW_LINE> if monthly_consumption is not None: <NEW_LINE> <INDENT> stock_levels = self.get_domain().commtrack_settings.stock_levels_config <NEW_LINE> needed_quantity = int( monthly_consumption * stock_levels.overstock_threshold ) <NEW_LINE> return int(max(needed_quantity - self.stock_on_hand, 0)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def stock_category(self): <NEW_LINE> <INDENT> return state_stock_category(self) <NEW_LINE> <DEDENT> @memoized <NEW_LINE> def get_domain(self): <NEW_LINE> <INDENT> return Domain.get_by_name( DocDomainMapping.objects.get(doc_id=self.case_id).domain_name ) <NEW_LINE> <DEDENT> def get_daily_consumption(self): <NEW_LINE> <INDENT> if self.daily_consumption is not None: <NEW_LINE> <INDENT> return self.daily_consumption <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> monthly = self._get_default_monthly_consumption() <NEW_LINE> if monthly is not None: <NEW_LINE> <INDENT> return Decimal(monthly) / Decimal(DAYS_IN_MONTH) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def get_monthly_consumption(self): <NEW_LINE> <INDENT> if self.daily_consumption is not None: <NEW_LINE> <INDENT> return self.daily_consumption * Decimal(DAYS_IN_MONTH) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self._get_default_monthly_consumption() <NEW_LINE> <DEDENT> <DEDENT> def _get_default_monthly_consumption(self): <NEW_LINE> <INDENT> domain = self.get_domain() <NEW_LINE> if domain and domain.commtrack_settings: <NEW_LINE> <INDENT> config = domain.commtrack_settings.get_consumption_config() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> config = None <NEW_LINE> <DEDENT> return compute_default_monthly_consumption( self.case_id, self.product_id, config ) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> unique_together = ('section_id', 'case_id', 'product_id')
Read only reporting model for keeping computed stock states per case/product
6259900bd164cc6175821b51
class PublicLawRestrictionBase(Base): <NEW_LINE> <INDENT> __tablename__ = 'public_law_restriction_base' <NEW_LINE> __table_args__ = {'schema': 'regional_land_use_plans'} <NEW_LINE> id = sa.Column(sa.String, primary_key=True, autoincrement=False) <NEW_LINE> public_law_restriction_id = sa.Column( sa.String, sa.ForeignKey(PublicLawRestriction.id), nullable=False ) <NEW_LINE> public_law_restriction_base_id = sa.Column( sa.String, sa.ForeignKey(PublicLawRestriction.id), nullable=False ) <NEW_LINE> plr = relationship( PublicLawRestriction, backref='basis', foreign_keys=[public_law_restriction_id] ) <NEW_LINE> base = relationship( PublicLawRestriction, foreign_keys=[public_law_restriction_base_id] ) <NEW_LINE> liefereinheit = sa.Column(sa.Integer, nullable=True)
Meta bucket (join table) for public law restrictions which acts as a base for other public law restrictions. Attributes: id (int): The identifier. This is used in the database only and must not be set manually. If you don't like it - don't care about. public_law_restriction_id (int): The foreign key to the public law restriction which bases on another public law restriction. public_law_restriction_base_id (int): The foreign key to the public law restriction which is the base for the public law restriction. plr (pyramid_oereb.standard.models.regional_land_use_plans.PublicLawRestriction): The dedicated relation to the public law restriction (which bases on) instance from database. base (pyramid_oereb.standard.models.regional_land_use_plans.PublicLawRestriction): The dedicated relation to the public law restriction (which is the base) instance from database.
6259900b627d3e7fe0e07a72
class Chassis(ResourceInfo): <NEW_LINE> <INDENT> NAME_TEMPLATE = "Chassis {}" <NEW_LINE> FAMILY_NAME = "L1 Switch" <NEW_LINE> def __init__(self, resource_id, address, model_name, serial_number=None): <NEW_LINE> <INDENT> self._address = address <NEW_LINE> name = self.NAME_TEMPLATE.format( EntityValidator.validate_id_for_name_template(resource_id) ) <NEW_LINE> family_name = self.FAMILY_NAME <NEW_LINE> super(Chassis, self).__init__( resource_id, name, family_name, model_name, serial_number ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def address(self): <NEW_LINE> <INDENT> return self._address <NEW_LINE> <DEDENT> def set_model_name(self, value): <NEW_LINE> <INDENT> if value: <NEW_LINE> <INDENT> self.attributes.append(StringAttribute("Model Name", value)) <NEW_LINE> <DEDENT> <DEDENT> def set_serial_number(self, value): <NEW_LINE> <INDENT> if value: <NEW_LINE> <INDENT> self.attributes.append(StringAttribute("Serial Number", value)) <NEW_LINE> <DEDENT> <DEDENT> def set_os_version(self, value): <NEW_LINE> <INDENT> if value: <NEW_LINE> <INDENT> self.attributes.append(StringAttribute("OS Version", value))
Chassis resource entity.
6259900bbf627c535bcb2087
class Votes(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.vote_records = VOTES <NEW_LINE> <DEDENT> def find_vote(self, id): <NEW_LINE> <INDENT> response = None <NEW_LINE> for item in self.vote_records: <NEW_LINE> <INDENT> if item['meetup_id'] == id: <NEW_LINE> <INDENT> response = item <NEW_LINE> <DEDENT> <DEDENT> return response <NEW_LINE> <DEDENT> def save(self, id, vote): <NEW_LINE> <INDENT> data = { "meetup_id": id, "votes": 0, "voted_on": datetime.datetime.now() } <NEW_LINE> if vote: <NEW_LINE> <INDENT> data['votes'] += 1 <NEW_LINE> <DEDENT> elif data['votes'] > 0: <NEW_LINE> <INDENT> data['downvotes'] -= 1 <NEW_LINE> <DEDENT> self.vote_records.append(data) <NEW_LINE> return self.vote_records <NEW_LINE> <DEDENT> def vote(self, id, vote): <NEW_LINE> <INDENT> record = self.find_vote(id) <NEW_LINE> if record is not None: <NEW_LINE> <INDENT> if vote: <NEW_LINE> <INDENT> record['votes'] += 1 <NEW_LINE> <DEDENT> elif record['votes'] > 0: <NEW_LINE> <INDENT> record['votes'] -= 1 <NEW_LINE> <DEDENT> return record <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> response = self.save(id, vote) <NEW_LINE> <DEDENT> return response
Map vote models and data relations
6259900b627d3e7fe0e07a74
@export <NEW_LINE> class FatturaPrivati12(Fattura): <NEW_LINE> <INDENT> def get_versione(self): <NEW_LINE> <INDENT> return "FPR12"
Fattura privati 1.2
6259900b0a366e3fb87dd5cc
class RootWindow(Manager): <NEW_LINE> <INDENT> def __init__(self, screen): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self._screen = screen <NEW_LINE> self._children = [] <NEW_LINE> self.clock = pygame.time.Clock() <NEW_LINE> self.running = True <NEW_LINE> <DEDENT> def render(self, *args): <NEW_LINE> <INDENT> self._screen.fill(CONFIG.get('border_colour', (0, 0, 0))) <NEW_LINE> for c in self._children: <NEW_LINE> <INDENT> c.render(self._screen, (0, 0)) <NEW_LINE> <DEDENT> pygame.display.update() <NEW_LINE> <DEDENT> def events(self): <NEW_LINE> <INDENT> self.clock.tick(CONFIG.get('fps', 30)) <NEW_LINE> event = pygame.event.poll() <NEW_LINE> while event.type != pygame.NOEVENT: <NEW_LINE> <INDENT> if event.type == pygame.VIDEORESIZE: <NEW_LINE> <INDENT> self._screen = pygame.display.set_mode(event.size, (not CONFIG.get('rpi')) * pygame.RESIZABLE, 32) <NEW_LINE> <DEDENT> elif event.type == pygame.QUIT: <NEW_LINE> <INDENT> self.running = False <NEW_LINE> return <NEW_LINE> <DEDENT> if self._children: <NEW_LINE> <INDENT> self._children[-1].event(event, (0, 0)) <NEW_LINE> <DEDENT> event = pygame.event.poll() <NEW_LINE> <DEDENT> pygame.time.wait(10) <NEW_LINE> <DEDENT> def tick(self): <NEW_LINE> <INDENT> for c in self._children: <NEW_LINE> <INDENT> c.tick() <NEW_LINE> <DEDENT> <DEDENT> def add_child(self, child): <NEW_LINE> <INDENT> if not isinstance(child, Manager): <NEW_LINE> <INDENT> nc = SingleManager() <NEW_LINE> nc.set_c(child) <NEW_LINE> child = nc <NEW_LINE> <DEDENT> self._children.append(child) <NEW_LINE> child.parent = self <NEW_LINE> return child <NEW_LINE> <DEDENT> def remove_child(self, child): <NEW_LINE> <INDENT> if child in self._children: <NEW_LINE> <INDENT> self._children.remove(child) <NEW_LINE> child.parent = None <NEW_LINE> <DEDENT> return child <NEW_LINE> <DEDENT> def request_size(self, child): <NEW_LINE> <INDENT> return self._screen.get_size() <NEW_LINE> <DEDENT> def mainloop(self): <NEW_LINE> <INDENT> while self.running: <NEW_LINE> <INDENT> self.render() <NEW_LINE> self.events() <NEW_LINE> self.tick() <NEW_LINE> <DEDENT> pygame.quit()
This class 'owns' the connection to the screen and is the root propagator of all events and render requests. It allows for a single child to be attached. This is recommended to be a manager, although any `Griddable` element is accepted. TODO: Allow for multiple stacked children.
6259900b56b00c62f0fb3499
class MultipleButtonControl(object): <NEW_LINE> <INDENT> def __init__(self, *, commands, **kwargs): <NEW_LINE> <INDENT> self._command_buttons_config = commands <NEW_LINE> self._orientation = Qt.Horizontal <NEW_LINE> self.buttons = [] <NEW_LINE> self.create_buttons() <NEW_LINE> super(MultipleButtonControl, self).__init__(**kwargs) <NEW_LINE> self.controls_frame.setLayout(QGridLayout()) <NEW_LINE> self.controlButtonHorizontal = True <NEW_LINE> <DEDENT> @Property(bool) <NEW_LINE> def controlButtonHorizontal(self): <NEW_LINE> <INDENT> return self._orientation == Qt.Horizontal <NEW_LINE> <DEDENT> @controlButtonHorizontal.setter <NEW_LINE> def controlButtonHorizontal(self, checked): <NEW_LINE> <INDENT> self.clear_control_layout() <NEW_LINE> self._orientation = Qt.Vertical <NEW_LINE> if checked: <NEW_LINE> <INDENT> self._orientation = Qt.Horizontal <NEW_LINE> <DEDENT> layout = self.controls_frame.layout() <NEW_LINE> if self._orientation == Qt.Vertical: <NEW_LINE> <INDENT> for i, btn in enumerate(self.buttons): <NEW_LINE> <INDENT> layout.addWidget(btn, i, 0) <NEW_LINE> <DEDENT> <DEDENT> elif self._orientation == Qt.Horizontal: <NEW_LINE> <INDENT> for i, btn in enumerate(self.buttons): <NEW_LINE> <INDENT> layout.addWidget(btn, 0, i) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def clear_control_layout(self): <NEW_LINE> <INDENT> layout = self.controls_frame.layout() <NEW_LINE> if not isinstance(layout, QGridLayout): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for col in range(0, layout.columnCount()): <NEW_LINE> <INDENT> for row in range(0, layout.rowCount()): <NEW_LINE> <INDENT> item = layout.itemAtPosition(row, col) <NEW_LINE> if item is not None: <NEW_LINE> <INDENT> w = item.widget() <NEW_LINE> if w is not None: <NEW_LINE> <INDENT> layout.removeWidget(w) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def create_buttons(self): <NEW_LINE> <INDENT> for btn in self._command_buttons_config: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> text = btn['text'] <NEW_LINE> value = btn['value'] <NEW_LINE> btn = PyDMPushButton(label=text, pressValue=value) <NEW_LINE> self.buttons.append(btn) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> logger.exception('Invalid config for MultipleButtonControl.') <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def create_channels(self): <NEW_LINE> <INDENT> super(MultipleButtonControl, self).create_channels() <NEW_LINE> if self._channels_prefix: <NEW_LINE> <INDENT> for idx, btn in enumerate(self.buttons): <NEW_LINE> <INDENT> suffix = self._command_buttons_config[idx]['suffix'] <NEW_LINE> btn.channel = "{}{}".format(self._channels_prefix, suffix) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def destroy_channels(self): <NEW_LINE> <INDENT> super(MultipleButtonControl, self).destroy_channels() <NEW_LINE> for btn in self.buttons: <NEW_LINE> <INDENT> btn.channel = None
The MultipleButtonControl class adds multiple PyDMPushButton instances to the widget for controls. Parameters ---------- commands : list List of dictionaries containing the specifications for the buttons. Required keys for now are: - suffix: str suffix to be used along with the channelPrefix from PCDSSymbolBase to compose the command button channel address - text: str the text to display at the button - value the value to be written when the button is pressed
6259900b507cdc57c63a597a
class Throttle: <NEW_LINE> <INDENT> def __init__(self, delay): <NEW_LINE> <INDENT> self.delay = delay <NEW_LINE> self.domains = {} <NEW_LINE> <DEDENT> def wait(self, url): <NEW_LINE> <INDENT> domain = urlparse.urlparse(url).netloc <NEW_LINE> last_accessed = self.domains.get(domain) <NEW_LINE> if self.delay > 0 and last_accessed is not None: <NEW_LINE> <INDENT> sleep_secs = random.randint(0,2) <NEW_LINE> if sleep_secs > 0: <NEW_LINE> <INDENT> time.sleep(sleep_secs) <NEW_LINE> <DEDENT> <DEDENT> self.domains[domain] = datetime.now()
Throttle downloading by sleeping between requests to same domain
6259900bbf627c535bcb2089
class BillingAccount(_messages.Message): <NEW_LINE> <INDENT> displayName = _messages.StringField(1) <NEW_LINE> masterBillingAccount = _messages.StringField(2) <NEW_LINE> name = _messages.StringField(3) <NEW_LINE> open = _messages.BooleanField(4)
A billing account in [GCP Console](https://console.cloud.google.com/). You can assign a billing account to one or more projects. Fields: displayName: The display name given to the billing account, such as `My Billing Account`. This name is displayed in the GCP Console. masterBillingAccount: If this account is a [subaccount](https://cloud.google.com/billing/docs/concepts), then this will be the resource name of the master billing account that it is being resold through. Otherwise this will be empty. name: The resource name of the billing account. The resource name has the form `billingAccounts/{billing_account_id}`. For example, `billingAccounts/012345-567890-ABCDEF` would be the resource name for billing account `012345-567890-ABCDEF`. open: True if the billing account is open, and will therefore be charged for any usage on associated projects. False if the billing account is closed, and therefore projects associated with it will be unable to use paid services.
6259900b462c4b4f79dbc5e3
class SegregationSimulation(dworp.TwoStageSimulation): <NEW_LINE> <INDENT> def __init__(self, params, observer): <NEW_LINE> <INDENT> self.params = params <NEW_LINE> self.rng = random <NEW_LINE> self.rng.seed(params.seed) <NEW_LINE> factory = HouseholdFactory(self.rng, params.similarity, params.colors[0], params.colors[1]) <NEW_LINE> time = dworp.InfiniteTime() <NEW_LINE> scheduler = PYRandomOrderScheduler(self.rng.shuffle) <NEW_LINE> terminator = SegTerminator() <NEW_LINE> agents = [] <NEW_LINE> grid = DictGrid(params.grid_width, params.grid_height) <NEW_LINE> env = SegregationEnvironment(grid, self.rng) <NEW_LINE> for x in range(params.grid_width): <NEW_LINE> <INDENT> for y in range(params.grid_height): <NEW_LINE> <INDENT> if self.rng.uniform(0., 1.) < params.density: <NEW_LINE> <INDENT> agent = factory.create(x, y) <NEW_LINE> grid.put(agent, x, y) <NEW_LINE> agents.append(agent) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> super().__init__(agents, env, time, scheduler, observer, terminator)
Simulation with two stages (moving and then happiness test)
6259900bbf627c535bcb208b
class SynapticElementIntegrator(object): <NEW_LINE> <INDENT> def __init__(self, tau_ca=10000.0, beta_ca=0.001): <NEW_LINE> <INDENT> self.tau_ca = tau_ca <NEW_LINE> self.beta_ca = beta_ca <NEW_LINE> self.t_minus = 0 <NEW_LINE> self.ca_minus = 0 <NEW_LINE> self.se_minus = 0 <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self.t_minus = 0 <NEW_LINE> self.ca_minus = 0 <NEW_LINE> self.se_minus = 0 <NEW_LINE> <DEDENT> def handle_spike(self, t): <NEW_LINE> <INDENT> assert t >= self.t_minus <NEW_LINE> self.se_minus = self.get_se(t) <NEW_LINE> self.ca_minus = self.get_ca(t) + self.beta_ca <NEW_LINE> self.t_minus = t <NEW_LINE> <DEDENT> def get_ca(self, t): <NEW_LINE> <INDENT> assert t >= self.t_minus <NEW_LINE> ca = self.ca_minus * math.exp((self.t_minus - t) / self.tau_ca) <NEW_LINE> if ca > 0: <NEW_LINE> <INDENT> return ca <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> <DEDENT> def get_se(self, t): <NEW_LINE> <INDENT> return 0.0
Generic class which describes how to compute the number of Synaptic Element based on Ca value Each derived class should overwrite the get_se(self, t) method
6259900b462c4b4f79dbc5e7
class WechatUserInfo(models.Model): <NEW_LINE> <INDENT> add_time = models.DateTimeField('添加时间', auto_now=True) <NEW_LINE> openId = models.CharField('openId', max_length=128, blank=True) <NEW_LINE> nickName = models.CharField('昵称', max_length=128, blank=True) <NEW_LINE> avatarUrl = models.CharField('头像', max_length=128, blank=True) <NEW_LINE> gender = models.IntegerField('性别', blank=True) <NEW_LINE> country = models.CharField('国家', max_length=24, blank=True) <NEW_LINE> province = models.CharField('省份', max_length=24, blank=True) <NEW_LINE> city = models.CharField('城市', max_length=24, blank=True) <NEW_LINE> language = models.CharField('语言', max_length=10, blank=True) <NEW_LINE> timestamp = models.IntegerField('时间戳') <NEW_LINE> is_valid = models.BooleanField('是否有效', default=True) <NEW_LINE> session_key = models.CharField('session_key', max_length=128, blank=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return f'{self.nickName}' <NEW_LINE> <DEDENT> def avatar(self): <NEW_LINE> <INDENT> avatar_html = f"<img src={self.avatarUrl}> </img>" <NEW_LINE> return mark_safe(avatar_html) <NEW_LINE> <DEDENT> def sex(self): <NEW_LINE> <INDENT> return '男' if self.gender == 1 else '女' <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def create_user(wechat_user): <NEW_LINE> <INDENT> from myaccount.models import UserProfile <NEW_LINE> from pypinyin import lazy_pinyin <NEW_LINE> import datetime <NEW_LINE> username = lazy_pinyin(wechat_user.nickName, errors='ignore') <NEW_LINE> now = datetime.datetime.now() <NEW_LINE> print('-' * 100) <NEW_LINE> print(username, now) <NEW_LINE> username = ''.join(username) + '_' + str(now) <NEW_LINE> username = username.replace(' ', '_') <NEW_LINE> print(username) <NEW_LINE> user = User(username=username, first_name=wechat_user.nickName) <NEW_LINE> user.save() <NEW_LINE> user_profile = UserProfile(user=user, wechat=wechat_user) <NEW_LINE> user_profile.save()
微信用户信息
6259900b3cc13d1c6d466329
class TimelineHandler (util.TemplatingBaseHandler): <NEW_LINE> <INDENT> @util.oauth_decorator.oauth_aware <NEW_LINE> def get(self): <NEW_LINE> <INDENT> if not util.oauth_decorator.has_credentials(): <NEW_LINE> <INDENT> self.redirect("/") <NEW_LINE> <DEDENT> self._render_template("timeline.html", {}) <NEW_LINE> <DEDENT> @util.oauth_decorator.oauth_aware <NEW_LINE> def post(self): <NEW_LINE> <INDENT> if not util.oauth_decorator.has_credentials(): <NEW_LINE> <INDENT> self.error(403) <NEW_LINE> <DEDENT> mirror = apiclient.discovery.build( serviceName="mirror", version="v1", http=util.oauth_decorator.http()) <NEW_LINE> card = self.quake_card() <NEW_LINE> mapimg = self.map_image() <NEW_LINE> media_body = apiclient.http.MediaIoBaseUpload(io.BytesIO(mapimg), mimetype="image/png", resumable=True) <NEW_LINE> timeline_transaction = mirror.timeline() <NEW_LINE> timeline_transaction.insert(body=card, media_body=media_body).execute() <NEW_LINE> <DEDENT> def map_image(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return urllib2.urlopen(quakemap(*self.coords())).read() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> <DEDENT> def coords(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return ( float(self.request.get("lng")), float(self.request.get("lat")) ) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return (0.0, 0.0) <NEW_LINE> <DEDENT> <DEDENT> def quake_card(self): <NEW_LINE> <INDENT> template = util.get_template("quake.html") <NEW_LINE> values = {"loc": self.request.get("loc"), "mag": 0.0} <NEW_LINE> try: <NEW_LINE> <INDENT> values["mag"] = float(self.request.get("mag")) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> mapurl = quakemap(*self.coords()) <NEW_LINE> return { "displayTime": datetime.datetime.utcnow().isoformat() + "Z", "html": template.render(values), "attachments": [{"contentType": "image/png", "contentUrl": mapurl}], "menuItems": [{"action": "DELETE"}], }
Request handler for directly pushing (fake) quake cards to the user's Glass timeline.
6259900bd164cc6175821b5e
class IdentityProofModel(QObject): <NEW_LINE> <INDENT> def __init__(self, app, connection): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.app = app <NEW_LINE> self.connection = connection <NEW_LINE> self._connections_processor = ConnectionsProcessor.instanciate(self.app) <NEW_LINE> self._identities_processor = IdentitiesProcessor.instanciate(self.app) <NEW_LINE> self._blockchain_processor = BlockchainProcessor.instanciate(self.app) <NEW_LINE> <DEDENT> def change_connection(self, index): <NEW_LINE> <INDENT> self.connection = self.connections_repo.get_currencies()[index] <NEW_LINE> <DEDENT> def available_connections(self): <NEW_LINE> <INDENT> return self._connections_processor.connections_with_uids() <NEW_LINE> <DEDENT> def set_connection(self, index): <NEW_LINE> <INDENT> connections = self._connections_processor.connections_with_uids() <NEW_LINE> self.connection = connections[index] <NEW_LINE> <DEDENT> def notification(self): <NEW_LINE> <INDENT> return self.app.parameters.notifications
The model of Certification component
6259900b21a7993f00c66b5e
class NXPyroSession(object): <NEW_LINE> <INDENT> def __init__(self, user, hostname, localPort): <NEW_LINE> <INDENT> self.user = user <NEW_LINE> self.hostname = hostname <NEW_LINE> self.localPort = localPort <NEW_LINE> self.sshService = None <NEW_LINE> self.sshTunnel = None <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> command = "nxstartserver" <NEW_LINE> self.sshService = NXPyroSSH(self.user, self.hostname, command=command, getURI=True) <NEW_LINE> uri = self.sshService.getURIfromQueue() <NEW_LINE> if (uri == "UNSET"): <NEW_LINE> <INDENT> print("SSH could not start NXpyro service!") <NEW_LINE> return False <NEW_LINE> <DEDENT> tokens = uri.split(":") <NEW_LINE> port = int(tokens[2]) <NEW_LINE> self.sshTunnel = NXPyroSSH(self.user, self.hostname, localPort=self.localPort, remotePort=port) <NEW_LINE> return True <NEW_LINE> <DEDENT> def terminate(self): <NEW_LINE> <INDENT> print("session terminating ssh connections...") <NEW_LINE> if self.sshTunnel != None: <NEW_LINE> <INDENT> self.sshTunnel.terminate() <NEW_LINE> <DEDENT> if self.sshService != None: <NEW_LINE> <INDENT> self.sshService.terminate()
Sets up a NXPyro session on given host
6259900b3cc13d1c6d46632b
class Exponential(gamma.Gamma): <NEW_LINE> <INDENT> def __init__(self, lam, validate_args=False, allow_nan_stats=True, name="Exponential"): <NEW_LINE> <INDENT> with ops.name_scope(name, values=[lam]) as ns: <NEW_LINE> <INDENT> self._lam = ops.convert_to_tensor(lam, name="lam") <NEW_LINE> super(Exponential, self).__init__( alpha=array_ops.ones((), dtype=self._lam.dtype), beta=self._lam, allow_nan_stats=allow_nan_stats, validate_args=validate_args, name=ns) <NEW_LINE> self._is_reparameterized = True <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def _param_shapes(sample_shape): <NEW_LINE> <INDENT> return {"lam": ops.convert_to_tensor(sample_shape, dtype=dtypes.int32)} <NEW_LINE> <DEDENT> @property <NEW_LINE> def lam(self): <NEW_LINE> <INDENT> return self._lam <NEW_LINE> <DEDENT> def _sample_n(self, n, seed=None): <NEW_LINE> <INDENT> shape = array_ops.concat(0, ([n], array_ops.shape(self._lam))) <NEW_LINE> sampled = random_ops.random_uniform( shape, minval=np.nextafter(self.dtype.as_numpy_dtype(0.), self.dtype.as_numpy_dtype(1.)), maxval=array_ops.ones((), dtype=self.dtype), seed=seed, dtype=self.dtype) <NEW_LINE> return -math_ops.log(sampled) / self._lam
The Exponential distribution with rate parameter lam. The PDF of this distribution is: ```prob(x) = (lam * e^(-lam * x)), x > 0``` Note that the Exponential distribution is a special case of the Gamma distribution, with Exponential(lam) = Gamma(1, lam).
6259900bbf627c535bcb2091
class NoopAnonymizer(object): <NEW_LINE> <INDENT> def ProcessPath(self, path): <NEW_LINE> <INDENT> return path <NEW_LINE> <DEDENT> def ProcessAccount(self, account): <NEW_LINE> <INDENT> return account <NEW_LINE> <DEDENT> def ProcessProject(self, project): <NEW_LINE> <INDENT> return project <NEW_LINE> <DEDENT> def ProcessUsername(self, username): <NEW_LINE> <INDENT> return username <NEW_LINE> <DEDENT> def ProcessPassword(self, password): <NEW_LINE> <INDENT> return password
Noop anonymizer.
6259900b507cdc57c63a5984
class MergeForm(forms.Form): <NEW_LINE> <INDENT> how_merge_choices = [ ('', _('- Choose row selection method -')), ('outer', _('1) Select all rows in both the existing and new table')), ('inner', _( '2) Select only the rows with keys present in both the ' + 'existing and new table')), ('left', _('3) Select only the rows with keys in the existing table')), ('right', _('4) Select only the rows with keys in the new table')), ] <NEW_LINE> merge_help = _('Select one method to see detailed information') <NEW_LINE> how_merge_initial = None <NEW_LINE> def __init__(self, *args, **kargs): <NEW_LINE> <INDENT> given_how = kargs.pop('how_merge', None) <NEW_LINE> self.how_merge_initial = next(( mrg for mrg in self.how_merge_choices if given_how == mrg[0]), None) <NEW_LINE> super().__init__(*args, **kargs) <NEW_LINE> self.fields['how_merge'] = forms.ChoiceField( initial=self.how_merge_initial, choices=self.how_merge_choices, required=True, label=_('Method to select rows to merge'), help_text=self.merge_help)
Form to choose the merge method for data frames.
6259900b56b00c62f0fb34a3
class historic_ExtDBServAttr(BaseModel): <NEW_LINE> <INDENT> real_db_id = -1 <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> BaseModel.__init__(self) <NEW_LINE> self.server_db_id = None <NEW_LINE> self.location = "" <NEW_LINE> self.owner = "" <NEW_LINE> self.description = "" <NEW_LINE> self.unmapped_attributes_list = [ 'parts', 'ExtServAttr' ]
Model object of extra Attributes to a server. IN DB_CACHE, this is stored in an own table
6259900b462c4b4f79dbc5ed
class Role(BASE): <NEW_LINE> <INDENT> __tablename__ = 'role' <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> name = Column(String, unique=True) <NEW_LINE> target_system = Column(String) <NEW_LINE> description = Column(Text) <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(Role, self).__init__(**kwargs) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<Role %r : target_system %r, description:%r>' % ( self.name, self.target_system, self.description)
The Role table stores avaiable roles of one target system. .. note:: the host can be deployed to one or several roles in the cluster. :param id: int, identity as primary key. :param name: role name. :param target_system: str, the target_system. :param description: str, the description of the role.
6259900b21a7993f00c66b62
class FirstLoginPage(BasePage): <NEW_LINE> <INDENT> PAGE_NAME = "First login page---" <NEW_LINE> def __init__(self, driver): <NEW_LINE> <INDENT> super(FirstLoginPage, self).__init__(driver) <NEW_LINE> <DEDENT> def get_login_button_by_id(self, id=None): <NEW_LINE> <INDENT> logger.info(self.PAGE_NAME + " get login button") <NEW_LINE> return self.ui_locator.find_element_by_id(id)
Flow: Main page login
6259900b56b00c62f0fb34a5
class State(object): <NEW_LINE> <INDENT> def __init__(self, pos, random=None): <NEW_LINE> <INDENT> self.pos = pos <NEW_LINE> if random is not None: <NEW_LINE> <INDENT> self.random_state = random <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.random_state = np.random.get_state() <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "State(pos={0}, random_state={1})".format(self.pos, self.random_state) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return iter((self.pos, self.random_state))
This is a class to hold the current state and handle state updating for the Gibbs Sampler Object Its main purposes is to hold the params list and whatever point in parameter space the markov chain is currently at Will also contain methods used in the sampler object
6259900b0a366e3fb87dd5da
class EvolvedLookerUp(LookerUp): <NEW_LINE> <INDENT> name = "EvolvedLookerUp" <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> plays = 2 <NEW_LINE> opponent_start_plays = 2 <NEW_LINE> self_histories = [''.join(x) for x in product('CD', repeat=plays)] <NEW_LINE> other_histories = [''.join(x) for x in product('CD', repeat=plays)] <NEW_LINE> opponent_starts = [''.join(x) for x in product('CD', repeat=opponent_start_plays)] <NEW_LINE> lookup_table_keys = list(product(opponent_starts, self_histories, other_histories)) <NEW_LINE> pattern='CDCCDCCCDCDDDDDCCDCCCDDDCDDDDDDCDDDDCDDDDCCDDCDDCDDDCCCDCDCDDDDD' <NEW_LINE> lookup_table = dict(zip(lookup_table_keys, pattern)) <NEW_LINE> LookerUp.__init__(self, lookup_table=lookup_table)
A LookerUp strategy that uses a lookup table generated using an evolutionary algorithm.
6259900b507cdc57c63a5988
class IndexView(Auth, Throttle, APIView): <NEW_LINE> <INDENT> def get(self, request): <NEW_LINE> <INDENT> print('permission_classes', self.throttle_classes) <NEW_LINE> print(request.user) <NEW_LINE> return HttpResponse('网站首页')
所有人都能访问 节流:匿名用户10/m, 登录用户20/m
6259900b21a7993f00c66b64
class XYZSnapshot(Snapshot): <NEW_LINE> <INDENT> def read(self, path_or_file): <NEW_LINE> <INDENT> with stream_safe_open(path_or_file) as f: <NEW_LINE> <INDENT> line = f.readline() <NEW_LINE> if not line: raise NoSnapshotError <NEW_LINE> number_of_atoms = int(line) <NEW_LINE> if not number_of_atoms > 0: raise NoSnapshotError <NEW_LINE> comment = f.readline() <NEW_LINE> c = io.StringIO() <NEW_LINE> for i in range(number_of_atoms): c.write(f.readline()) <NEW_LINE> c.seek(0) <NEW_LINE> table = pandas.read_table(c, sep='\s+', names=('atom','x','y','z'), nrows=number_of_atoms) <NEW_LINE> self.x = table[['x','y','z']].values.copy('c').astype(numpy.longdouble) <NEW_LINE> self.species = table['atom'].tolist() <NEW_LINE> self.time = self.box = None <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> if (sys.version_info > (3, 0)): f = io.StringIO() <NEW_LINE> else: f = io.BytesIO() <NEW_LINE> f.write('%d\n' % self.n) <NEW_LINE> if type(self.species) is str: <NEW_LINE> <INDENT> for i in range(self.n): <NEW_LINE> <INDENT> f.write('\n') <NEW_LINE> f.write('%s ' % self.species) <NEW_LINE> f.write(' '.join(map(str, self.x[i,:]))) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for i in range(self.n): <NEW_LINE> <INDENT> f.write('\n') <NEW_LINE> f.write('%s ' % self.species[i]) <NEW_LINE> f.write(' '.join(map(str, self.x[i,:]))) <NEW_LINE> <DEDENT> <DEDENT> return f.getvalue()
Snapshot of a system of particles in XYZ (.xyz) file format. Interface defined in parent class Snapshot. Further documentation can be found there.
6259900b15fb5d323ce7f929
class ElectionPosition(polymodel.PolyModel): <NEW_LINE> <INDENT> election = db.ReferenceProperty(Election, required=True) <NEW_LINE> position = db.ReferenceProperty(Position, required=True) <NEW_LINE> vote_required = db.BooleanProperty(required=True) <NEW_LINE> write_in_slots = db.IntegerProperty(required=True) <NEW_LINE> winners = db.ListProperty(db.Key) <NEW_LINE> description = db.TextProperty(required=False, default="") <NEW_LINE> datetime_created = db.DateTimeProperty(required=True, auto_now_add=True) <NEW_LINE> def to_json(self): <NEW_LINE> <INDENT> json = { 'id': str(self.key()), 'name': self.position.name, 'write_in_slots': self.write_in_slots, 'vote_required': self.vote_required, 'candidates': [], 'description': self.description } <NEW_LINE> for epc in self.election_position_candidates: <NEW_LINE> <INDENT> logging.info(epc.name) <NEW_LINE> if epc.written_in and epc.key() not in self.winners: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> candidate = {'name': epc.name, 'id': str(epc.key())} <NEW_LINE> if epc.key() in self.winners: <NEW_LINE> <INDENT> candidate['winner'] = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> candidate['winner'] = False <NEW_LINE> <DEDENT> json['candidates'].append(candidate) <NEW_LINE> <DEDENT> return json <NEW_LINE> <DEDENT> def compute_winners(self): <NEW_LINE> <INDENT> assert datetime.now() > self.election.end <NEW_LINE> assert not self.election.result_computed
A position for a specific election within an organization.
6259900c627d3e7fe0e07a84
class FutureResult(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._result = AsyncResult() <NEW_LINE> self.created_at = time.time() <NEW_LINE> <DEDENT> def get(self, timeout=None): <NEW_LINE> <INDENT> return self._result.get(block=True, timeout=timeout) <NEW_LINE> <DEDENT> def set(self, value): <NEW_LINE> <INDENT> self._result.set(value) <NEW_LINE> <DEDENT> def set_exception(self, exception): <NEW_LINE> <INDENT> self._result.set_exception(exception)
Future results for asynchronous operations.
6259900c5166f23b2e243fbe
class IEditableMenuSettings(model.Schema): <NEW_LINE> <INDENT> form.widget(menu_tabs_json=EditableMenuSettingsFieldWidget) <NEW_LINE> menu_tabs_json = schema.Text( title=_('config_tabs_label', u'Menu configuration.'), required=False, default=u'{"/":{"items":[]}}', )
Settings used in the control panel for cookiecosent: unified panel
6259900c925a0f43d25e8c2d
class SatelliteNumber(_VSOSimpleAttr): <NEW_LINE> <INDENT> pass
The GOES Satellite Number
6259900cd164cc6175821b6a
class _LanguageType(type): <NEW_LINE> <INDENT> def __repr__(cls): <NEW_LINE> <INDENT> return '{}.{}'.format(cls.__module__, cls.__name__)
Language meta type that prints a customized repr string.
6259900c21a7993f00c66b6a
class Quiz(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=255, unique=True) <NEW_LINE> video = models.ForeignKey(Video, on_delete=models.CASCADE) <NEW_LINE> points = models.IntegerField() <NEW_LINE> question = ArrayModelField(model_container=Question) <NEW_LINE> is_deleted = models.BooleanField(default=False) <NEW_LINE> created_at = models.DateTimeField(auto_now_add=True, editable=False) <NEW_LINE> updated_at = models.DateTimeField(auto_now=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name
"Represents Quiz details in Table
6259900c56b00c62f0fb34ad
class CatCommand(clinix.ClinixCommand): <NEW_LINE> <INDENT> def __init__(self, args, options): <NEW_LINE> <INDENT> super().__init__(options) <NEW_LINE> self.filenames = args <NEW_LINE> <DEDENT> def parse_options(self, options): <NEW_LINE> <INDENT> self.number = options.get('number', False) or options.get('n', False) <NEW_LINE> <DEDENT> def cat_one(self, filename): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(filename) as f: <NEW_LINE> <INDENT> lines = f.read().splitlines() <NEW_LINE> lines = self.cat_lines(lines) <NEW_LINE> return CatSuccess(filename, '\n'.join(lines)) <NEW_LINE> <DEDENT> <DEDENT> except IOError as e: <NEW_LINE> <INDENT> return CatError(filename, e.strerror) <NEW_LINE> <DEDENT> <DEDENT> def cat_lines(self, lines): <NEW_LINE> <INDENT> if self.number: <NEW_LINE> <INDENT> lines = list(enumerate(lines, 1)) <NEW_LINE> max_num_len = len(str(len(lines))) <NEW_LINE> lines = [str(linenum).rjust(4 + max_num_len) + ' ' + line for linenum, line in lines] <NEW_LINE> <DEDENT> return lines <NEW_LINE> <DEDENT> def cat_stdin(self): <NEW_LINE> <INDENT> return CatSuccess('-', '\n'.join(self.cat_lines(self.read_stdin().splitlines()))) <NEW_LINE> <DEDENT> def eval(self): <NEW_LINE> <INDENT> filenames = clinix.expand_files(self.filenames) <NEW_LINE> if filenames: <NEW_LINE> <INDENT> return [self.cat_one(f) for f in filenames] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [self.cat_stdin()] <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> def singlestr(arg): <NEW_LINE> <INDENT> if isinstance(arg, CatSuccess): <NEW_LINE> <INDENT> return arg.contents <NEW_LINE> <DEDENT> elif isinstance(arg, CatError): <NEW_LINE> <INDENT> return arg.file + ': ' + arg.reason <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception("Don't know how to handle cat result " + arg.__class__.__name__) <NEW_LINE> <DEDENT> <DEDENT> return '\n'.join(singlestr(arg) for arg in self.eval())
Class to represent a cat command
6259900cbf627c535bcb209e
class DEMove(RedBlueMove): <NEW_LINE> <INDENT> def __init__(self, sigma, gamma0=None, **kwargs): <NEW_LINE> <INDENT> self.sigma = sigma <NEW_LINE> self.gamma0 = gamma0 <NEW_LINE> super(DEMove, self).__init__(**kwargs) <NEW_LINE> <DEDENT> def setup(self, ensemble): <NEW_LINE> <INDENT> self.g0 = self.gamma0 <NEW_LINE> if self.g0 is None: <NEW_LINE> <INDENT> self.g0 = 2.38 / np.sqrt(2 * ensemble.ndim) <NEW_LINE> <DEDENT> <DEDENT> def get_proposal(self, ens, s, c): <NEW_LINE> <INDENT> Ns, Nc = len(s), len(c) <NEW_LINE> q = np.empty((Ns, ens.ndim), dtype=np.float64) <NEW_LINE> f = ens.random.randn(Ns) <NEW_LINE> for i in xrange(Ns): <NEW_LINE> <INDENT> inds = ens.random.choice(Nc, 2, replace=False) <NEW_LINE> g = np.diff(c[inds], axis=0) * (1 + self.g0 * f[i]) <NEW_LINE> q[i] = s[i] + g <NEW_LINE> <DEDENT> return q, np.zeros(Ns, dtype=np.float64)
A `differential evolution <http://www.stat.columbia.edu/~gelman/stuff_for_blog/cajo.pdf>`_ proposal implemented following `Nelson et al. (2013) <http://arxiv.org/abs/1311.5229>`_. :param sigma: The standard deviation of the Gaussian used to stretch the proposal vector. :param gamma0: (optional) The mean stretch factor for the proposal vector. By default, it is :math:`2.38 / \sqrt{2\,\mathrm{ndim}}` as recommended by MAGIC and the two references.
6259900c3cc13d1c6d466337
class CharacterFeatures(Model): <NEW_LINE> <INDENT> skin = IntegerField(default = 0) <NEW_LINE> face = IntegerField(default = 0) <NEW_LINE> hair_style = IntegerField(default = 0) <NEW_LINE> hair_color = IntegerField(default = 0) <NEW_LINE> facial_hair = IntegerField(default = 0) <NEW_LINE> class Meta(object): <NEW_LINE> <INDENT> database = DB
Features specific to a player character.
6259900c21a7993f00c66b6c
class TraitementMessages(BaseCallback): <NEW_LINE> <INDENT> def __init__(self, contexte: ContexteRessourcesDocumentsMilleGrilles, gateway: GatewayBlynk): <NEW_LINE> <INDENT> super().__init__(contexte) <NEW_LINE> self._gateway = gateway <NEW_LINE> self.__timezone = pytz.timezone('America/Montreal') <NEW_LINE> <DEDENT> def traiter_message(self, ch, method, properties, body): <NEW_LINE> <INDENT> message_dict = json.loads(body.decode('utf-8')) <NEW_LINE> routing_key = method.routing_key <NEW_LINE> action = routing_key.split('.')[-1] <NEW_LINE> if action == 'lecture': <NEW_LINE> <INDENT> self.traiter_lecture(message_dict) <NEW_LINE> <DEDENT> elif action == 'majNoeud': <NEW_LINE> <INDENT> self._gateway.maj_noeud(message_dict) <NEW_LINE> <DEDENT> elif action == 'majSenseur': <NEW_LINE> <INDENT> self._gateway.maj_senseur(message_dict) <NEW_LINE> <DEDENT> <DEDENT> def traiter_lecture(self, message_dict: dict): <NEW_LINE> <INDENT> uuid_senseur = message_dict.get(SenseursPassifsConstantes.TRANSACTION_ID_SENSEUR) <NEW_LINE> senseurs = message_dict.get('senseurs') <NEW_LINE> if uuid_senseur and senseurs: <NEW_LINE> <INDENT> date_lecture_plusrecente = 0 <NEW_LINE> for type_senseur, senseur in senseurs.items(): <NEW_LINE> <INDENT> date_lecture = senseur.get('timestamp') <NEW_LINE> date_lecture_plusrecente = max(date_lecture_plusrecente, date_lecture) <NEW_LINE> valeur = senseur.get('valeur') <NEW_LINE> if valeur: <NEW_LINE> <INDENT> self._gateway.transmettre_lecture(uuid_senseur, type_senseur, valeur) <NEW_LINE> <DEDENT> if date_lecture is not None: <NEW_LINE> <INDENT> self._gateway.touch_senseur(uuid_senseur, type_senseur, datetime.datetime.fromtimestamp(date_lecture)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._gateway.touch_senseur(uuid_senseur, type_senseur) <NEW_LINE> <DEDENT> <DEDENT> try: <NEW_LINE> <INDENT> if date_lecture_plusrecente == 0: <NEW_LINE> <INDENT> date_lecture_plusrecente = datetime.datetime.utcnow() <NEW_LINE> <DEDENT> self._gateway.transmettre_lecture(uuid_senseur, 'derniere_lecture/epoch', date_lecture_plusrecente) <NEW_LINE> date_formattee = datetime.datetime.fromtimestamp(date_lecture_plusrecente, tz=self.__timezone).strftime('%Y/%m/%d %H:%M:%S') <NEW_LINE> self._gateway.transmettre_lecture(uuid_senseur, 'derniere_lecture/str', date_formattee) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self.__logger.info("Erreur traitement date senseur: " + str(e))
Recoit les messages d'evenements et changements de configuration SenseursPassifs
6259900c21a7993f00c66b6e
class ExtractSingleCfgTarget(InvariantAwareCommand): <NEW_LINE> <INDENT> _verbose_ = True <NEW_LINE> dll = None <NEW_LINE> _dll = None <NEW_LINE> class DllArg(PathInvariant): <NEW_LINE> <INDENT> _help = "Path to the DLL (e.g. C:\\Windows\\System32\\ntdll.dll)" <NEW_LINE> _mandatory = True <NEW_LINE> <DEDENT> base_output_dir = None <NEW_LINE> _base_output_dir = None <NEW_LINE> class BaseOutputDirArg(DirectoryInvariant): <NEW_LINE> <INDENT> _help = ("Base output directory.") <NEW_LINE> _mandatory = False <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> InvariantAwareCommand.run(self) <NEW_LINE> conf = self.conf <NEW_LINE> out = self._out <NEW_LINE> from .util import mkdir <NEW_LINE> if not self._base_output_dir: <NEW_LINE> <INDENT> base = self.conf.base_output_dir <NEW_LINE> mkdir(base) <NEW_LINE> self.base_output_dir = base <NEW_LINE> <DEDENT> output_dir = self._base_output_dir <NEW_LINE> from .dumpbin import Dumpbin <NEW_LINE> dll = self._dll <NEW_LINE> db = Dumpbin(dll) <NEW_LINE> if not db.is_cf_instrumented: <NEW_LINE> <INDENT> raise CommandError("%s is not CF instrumented." % dll) <NEW_LINE> <DEDENT> db.save(output_dir)
TBD.
6259900c56b00c62f0fb34b1
class Corpus(object): <NEW_LINE> <INDENT> def __init__(self,dir_name): <NEW_LINE> <INDENT> self.dir_name = dir_name <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> for file_name in os.listdir(self.dir_name): <NEW_LINE> <INDENT> if os.path.isdir(os.path.join(self.dir_name, file_name)): <NEW_LINE> <INDENT> files = map(lambda x: os.path.join(self.dir_name, file_name, x), os.listdir(os.path.join(self.dir_name, file_name))) <NEW_LINE> for item in files: <NEW_LINE> <INDENT> doc = ''.join(map(lambda x:x.strip(), open(item, 'r').readlines())) <NEW_LINE> yield segment(doc)
语料库的generator
6259900cbf627c535bcb20a2
class ContainerRepairer(Tool): <NEW_LINE> <INDENT> DEFAULT_REBUILD_BASES = True <NEW_LINE> DEFAULT_SYNC_BASES = True <NEW_LINE> DEFAULT_UPDATE_ACCOUNT = True <NEW_LINE> def __init__(self, conf, containers=None, **kwargs): <NEW_LINE> <INDENT> super(ContainerRepairer, self).__init__(conf, **kwargs) <NEW_LINE> self.containers = containers <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def string_from_item(item): <NEW_LINE> <INDENT> namespace, account, container = item <NEW_LINE> return '%s|%s|%s' % ( namespace, account, container) <NEW_LINE> <DEDENT> def _fetch_items_from_containers(self): <NEW_LINE> <INDENT> for obj in self.containers: <NEW_LINE> <INDENT> namespace = obj['namespace'] <NEW_LINE> account = obj['account'] <NEW_LINE> container = obj['container'] <NEW_LINE> yield namespace, account, container <NEW_LINE> <DEDENT> <DEDENT> def _fetch_items(self): <NEW_LINE> <INDENT> if self.containers: <NEW_LINE> <INDENT> return self._fetch_items_from_containers() <NEW_LINE> <DEDENT> def _empty_generator(): <NEW_LINE> <INDENT> return <NEW_LINE> yield <NEW_LINE> <DEDENT> return _empty_generator() <NEW_LINE> <DEDENT> def _get_report(self, status, end_time, counters): <NEW_LINE> <INDENT> containers_processed, total_containers_processed, errors, total_errors = counters <NEW_LINE> time_since_last_report = (end_time - self.last_report) or 0.00001 <NEW_LINE> total_time = (end_time - self.start_time) or 0.00001 <NEW_LINE> report = ( '%(status)s ' 'last_report=%(last_report)s %(time_since_last_report).2fs ' 'containers=%(containers)d %(containers_rate).2f/s ' 'errors=%(errors)d %(errors_rate).2f%% ' 'start_time=%(start_time)s %(total_time).2fs ' 'total_containers=' '%(total_containers)d %(total_containers_rate).2f/s ' 'total_errors=%(total_errors)d %(total_errors_rate).2f%%' % { 'status': status, 'last_report': datetime.fromtimestamp( int(self.last_report)).isoformat(), 'time_since_last_report': time_since_last_report, 'containers': containers_processed, 'containers_rate': containers_processed / time_since_last_report, 'errors': errors, 'errors_rate': 100 * errors / float(containers_processed or 1), 'start_time': datetime.fromtimestamp( int(self.start_time)).isoformat(), 'total_time': total_time, 'total_containers': total_containers_processed, 'total_containers_rate': total_containers_processed / total_time, 'total_errors': total_errors, 'total_errors_rate': 100 * total_errors / float(total_containers_processed or 1) }) <NEW_LINE> if self.total_expected_items is not None: <NEW_LINE> <INDENT> progress = 100 * total_containers_processed / float(self.total_expected_items or 1) <NEW_LINE> report += ' progress=%d/%d %.2f%%' % (total_containers_processed, self.total_expected_items, progress) <NEW_LINE> <DEDENT> return report <NEW_LINE> <DEDENT> def create_worker(self, queue_workers, queue_reply): <NEW_LINE> <INDENT> return ContainerRepairerWorker(self, queue_workers, queue_reply) <NEW_LINE> <DEDENT> def _load_total_expected_items(self): <NEW_LINE> <INDENT> if self.containers and isinstance(self.containers, list): <NEW_LINE> <INDENT> self.total_expected_items = len(self.containers)
Repair containers.
6259900c15fb5d323ce7f933
class DebugControl(object): <NEW_LINE> <INDENT> def __init__(self, options, output): <NEW_LINE> <INDENT> self.options = options <NEW_LINE> self.output = output <NEW_LINE> <DEDENT> def should(self, option): <NEW_LINE> <INDENT> return (option in self.options or option in FORCED_DEBUG) <NEW_LINE> <DEDENT> def write(self, msg): <NEW_LINE> <INDENT> if self.should('pid'): <NEW_LINE> <INDENT> msg = "pid %5d: %s" % (os.getpid(), msg) <NEW_LINE> <DEDENT> self.output.write(msg+"\n") <NEW_LINE> self.output.flush() <NEW_LINE> <DEDENT> def write_formatted_info(self, info): <NEW_LINE> <INDENT> for line in info_formatter(info): <NEW_LINE> <INDENT> self.write(" %s" % line)
Control and output for debugging.
6259900cd164cc6175821b70
class HardBrakeEvent(Base): <NEW_LINE> <INDENT> __tablename__ = 'hard_brake_events' <NEW_LINE> hard_brake_event_id = Column(Integer, primary_key=True) <NEW_LINE> trip_id = Column(Integer, ForeignKey('trips.trip_id')) <NEW_LINE> lat = Column(Float) <NEW_LINE> lon = Column(Float) <NEW_LINE> ts = Column(BigInteger) <NEW_LINE> g = Column(Float) <NEW_LINE> point = Column(Geometry(geometry_type='POINT', srid=settings.TARGET_PROJECTION)) <NEW_LINE> def __init__(self, trip, event, path): <NEW_LINE> <INDENT> event = event.copy() <NEW_LINE> event['point'] = SpatialQueries.convert_geographic_coordinates_to_projected_point( event['lat'], event['lon'] ) <NEW_LINE> super(HardBrakeEvent, self).__init__(**event) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Warning! Based on your driving patterns, " "you are likely to brake hard within {} meters.".format(settings.ALERT_DISTANCE)
Database table for hard braking events, child of relation from trips table.
6259900c925a0f43d25e8c35
class AESCipher(object): <NEW_LINE> <INDENT> def __init__(self, key): <NEW_LINE> <INDENT> self.key = key <NEW_LINE> self.iv = bytes(16*'\x00'.encode()) <NEW_LINE> <DEDENT> def encrypt_file(self, in_filename, out_filename=None, chunksize=64*1024): <NEW_LINE> <INDENT> key = self.key <NEW_LINE> if out_filename is None: <NEW_LINE> <INDENT> out_filename = in_filename + '.enc' <NEW_LINE> <DEDENT> iv = self.iv <NEW_LINE> encryptor = AES.new(key, AES.MODE_CBC, iv) <NEW_LINE> filesize = os.path.getsize(in_filename) <NEW_LINE> with open(in_filename, 'rb') as infile: <NEW_LINE> <INDENT> with open(out_filename, 'wb') as outfile: <NEW_LINE> <INDENT> outfile.write(struct.pack('<Q', filesize)) <NEW_LINE> outfile.write(iv) <NEW_LINE> while True: <NEW_LINE> <INDENT> chunk = infile.read(chunksize) <NEW_LINE> if len(chunk) == 0: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> elif len(chunk) % 16 != 0: <NEW_LINE> <INDENT> chunk += bytes((16 - len(chunk) % 16)*' '.encode()) <NEW_LINE> <DEDENT> outfile.write(encryptor.encrypt(chunk)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def decrypt_file(self,in_filename, out_filename=None, chunksize=24*1024): <NEW_LINE> <INDENT> key = self.key <NEW_LINE> if out_filename is None: <NEW_LINE> <INDENT> out_filename = os.path.splitext(in_filename)[0] + ".dec" <NEW_LINE> <DEDENT> with open(in_filename, 'rb') as infile: <NEW_LINE> <INDENT> origsize = struct.unpack('<Q', infile.read(struct.calcsize('Q')))[0] <NEW_LINE> iv = infile.read(16) <NEW_LINE> decryptor = AES.new(key, AES.MODE_CBC, iv) <NEW_LINE> with open(out_filename, 'wb') as outfile: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> chunk = infile.read(chunksize) <NEW_LINE> if len(chunk) == 0: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> outfile.write(decryptor.decrypt(chunk)) <NEW_LINE> <DEDENT> outfile.truncate(origsize) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def encrypt(self, variable): <NEW_LINE> <INDENT> variable = variable.encode() <NEW_LINE> raw = pad(variable) <NEW_LINE> cipher = AES.new(self.key, AES.MODE_CBC, self.iv) <NEW_LINE> enc.cipher.encrypt(raw) <NEW_LINE> return base64.b64encode(enc).decode('utf-8')
https://github.com/dlitz/pycrypto
6259900cd164cc6175821b72
class ClientError(Exception): <NEW_LINE> <INDENT> pass
接口调用发起端的错误
6259900c507cdc57c63a5998
class Component(ApplicationSession): <NEW_LINE> <INDENT> @inlineCallbacks <NEW_LINE> def onJoin(self, details): <NEW_LINE> <INDENT> print("session attached") <NEW_LINE> self.received = 0 <NEW_LINE> sub = yield self.subscribe(self.on_event, 'com.myapp.topic1') <NEW_LINE> print("Subscribed to com.myapp.topic1 with {}".format(sub.id)) <NEW_LINE> <DEDENT> def on_event(self, i): <NEW_LINE> <INDENT> print("Got event: {}".format(i)) <NEW_LINE> self.received += 1 <NEW_LINE> pub_options = PublishOptions( acknowledge=True, exclude_me=True ) <NEW_LINE> self.publish('com.myapp.topic1',["aho"],options=pub_options) <NEW_LINE> <DEDENT> def onDisconnect(self): <NEW_LINE> <INDENT> print("disconnected") <NEW_LINE> if reactor.running: <NEW_LINE> <INDENT> reactor.stop()
An application component that subscribes and receives events, and stop after having received 5 events.
6259900cd164cc6175821b76
class FdfsStorage(FileSystemStorage): <NEW_LINE> <INDENT> def _save(self, name, content): <NEW_LINE> <INDENT> client = Fdfs_client('/dailyfresh/utils/fastdfs/client.conf') <NEW_LINE> try: <NEW_LINE> <INDENT> data = content.read() <NEW_LINE> json = client.upload_by_buffer(data) <NEW_LINE> print(json.get('Status')) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> raise e <NEW_LINE> <DEDENT> if json.get('Status') == 'Upload successed.': <NEW_LINE> <INDENT> path = json.get('Remote file_id') <NEW_LINE> print(path) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('出错了') <NEW_LINE> <DEDENT> return path <NEW_LINE> <DEDENT> def url(self, name): <NEW_LINE> <INDENT> host = 'http://127.0.0.1:8888/' <NEW_LINE> return host + super().url(name)
自定义文件存储
6259900c507cdc57c63a599a
class _BaseInstances(object): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def GetDatabaseInstances(limit=None, batch_size=None): <NEW_LINE> <INDENT> client = api_util.SqlClient(api_util.API_VERSION_DEFAULT) <NEW_LINE> sql_client = client.sql_client <NEW_LINE> sql_messages = client.sql_messages <NEW_LINE> project_id = properties.VALUES.core.project.Get(required=True) <NEW_LINE> params = {} <NEW_LINE> if limit is not None: <NEW_LINE> <INDENT> params['limit'] = limit <NEW_LINE> <DEDENT> if batch_size is not None: <NEW_LINE> <INDENT> params['batch_size'] = batch_size <NEW_LINE> <DEDENT> yielded = list_pager.YieldFromList( sql_client.instances, sql_messages.SqlInstancesListRequest(project=project_id), **params) <NEW_LINE> def YieldInstancesWithAModifiedState(): <NEW_LINE> <INDENT> for result in yielded: <NEW_LINE> <INDENT> if result.settings and result.settings.activationPolicy == 'NEVER': <NEW_LINE> <INDENT> result.state = 'STOPPED' <NEW_LINE> <DEDENT> yield result <NEW_LINE> <DEDENT> <DEDENT> return YieldInstancesWithAModifiedState() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def PrintAndConfirmAuthorizedNetworksOverwrite(): <NEW_LINE> <INDENT> console_io.PromptContinue( message='When adding a new IP address to authorized networks, ' 'make sure to also include any IP addresses that have already been ' 'authorized. Otherwise, they will be overwritten and de-authorized.', default=True, cancel_on_no=True) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def IsPostgresDatabaseVersion(database_version): <NEW_LINE> <INDENT> return _POSTGRES_DATABASE_VERSION_PREFIX in database_version
Common utility functions for sql instances.
6259900c21a7993f00c66b76
class SharedPartitionTemplateNotSupported(acos_errors.FeatureNotSupported): <NEW_LINE> <INDENT> def __init__(self, resource, template_key): <NEW_LINE> <INDENT> msg = ('Shared partition template lookup for [{0}] is not supported' ' on template `{1}`').format(resource, template_key) <NEW_LINE> super(SharedPartitionTemplateNotSupported, self).__init__(code=505, msg=msg)
Occurs when shared partition lookup for templates is not supported on acos client
6259900c15fb5d323ce7f93b
class PosixPollSerial(Serial): <NEW_LINE> <INDENT> def read(self, size=1): <NEW_LINE> <INDENT> if self.fd is None: <NEW_LINE> <INDENT> raise portNotOpenError <NEW_LINE> <DEDENT> read = bytearray() <NEW_LINE> poll = select.poll() <NEW_LINE> poll.register(self.fd, select.POLLIN | select.POLLERR | select.POLLHUP | select.POLLNVAL) <NEW_LINE> if size > 0: <NEW_LINE> <INDENT> while len(read) < size: <NEW_LINE> <INDENT> for fd, event in poll.poll(self._timeout * 1000): <NEW_LINE> <INDENT> if event & (select.POLLERR | select.POLLHUP | select.POLLNVAL): <NEW_LINE> <INDENT> raise SerialException('device reports error (poll)') <NEW_LINE> <DEDENT> <DEDENT> buf = os.read(self.fd, size - len(read)) <NEW_LINE> read.extend(buf) <NEW_LINE> if ((self._timeout is not None and self._timeout >= 0) or (self._inter_byte_timeout is not None and self._inter_byte_timeout > 0)) and not buf: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return bytes(read)
Poll based read implementation. Not all systems support poll properly. However this one has better handling of errors, such as a device disconnecting while it's in use (e.g. USB-serial unplugged).
6259900c627d3e7fe0e07a96
class DefaultOpenStruct(collections.defaultdict): <NEW_LINE> <INDENT> def __init__(self, *args, **keywords): <NEW_LINE> <INDENT> collections.defaultdict.__init__(self, None, *args, **keywords) <NEW_LINE> self.__dict__ = self <NEW_LINE> <DEDENT> def __getattr__(self, name): <NEW_LINE> <INDENT> if name not in self.__dict__: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.__dict__[name]
The fusion of dict and struct, with default values
6259900c0a366e3fb87dd5ef
class conf(object): <NEW_LINE> <INDENT> def __init__(self, ini_filename): <NEW_LINE> <INDENT> self.data = {} <NEW_LINE> self.load(ini_filename) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _check_type_(v): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> a = int(v) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> a = float(v) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> a = v <NEW_LINE> <DEDENT> <DEDENT> return a <NEW_LINE> <DEDENT> def load(self, ini_filename): <NEW_LINE> <INDENT> lines = open(ini_filename, "r").readlines() <NEW_LINE> for l in lines: <NEW_LINE> <INDENT> p0 = l.find("=") <NEW_LINE> p1 = l.find("#") <NEW_LINE> k = l[:p0].strip() <NEW_LINE> v = l[p0+1:p1].strip() if p1 > -1 else l[p0+1:].strip() <NEW_LINE> v = self._check_type_(v) <NEW_LINE> self.data[k] = v <NEW_LINE> <DEDENT> <DEDENT> def __getitem__(self, item): <NEW_LINE> <INDENT> return self.data.get(item, None)
Configuration file loader
6259900cd164cc6175821b78
class Config(object): <NEW_LINE> <INDENT> DEBUG = False <NEW_LINE> SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') <NEW_LINE> SQLALCHEMY_TRACK_MODIFICATIONS = False <NEW_LINE> SECRET = os.getenv('SECRET')
Parent configuration class.
6259900c3cc13d1c6d466345
class Workspace(models.Model): <NEW_LINE> <INDENT> name = models.CharField( max_length=100, null=False, blank=False, validators=[validate_name]) <NEW_LINE> owner = models.ForeignKey(User) <NEW_LINE> description = models.TextField(null=True, blank=True) <NEW_LINE> creation_date = models.DateTimeField(auto_now_add=True) <NEW_LINE> clone_of = models.CharField(max_length=200, null=True, blank=True) <NEW_LINE> clone_of_ser = models.TextField(null=True, blank=True) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return u'%s: %s' % (self.owner.username, self.name) <NEW_LINE> <DEDENT> def get_pesigs(self): <NEW_LINE> <INDENT> return self.pesig_set.get_queryset() <NEW_LINE> <DEDENT> def get_fnsigs(self): <NEW_LINE> <INDENT> return self.functionsig_set.get_queryset() <NEW_LINE> <DEDENT> def get_literalsigs(self): <NEW_LINE> <INDENT> return self.literalsig_set.get_queryset() <NEW_LINE> <DEDENT> def get_peimplementations(self): <NEW_LINE> <INDENT> return self.peimplementation_set.get_queryset() <NEW_LINE> <DEDENT> def get_fnimplementations(self): <NEW_LINE> <INDENT> return self.fnimplementation_set.get_queryset() <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> unique_together = ('owner', 'name', ) <NEW_LINE> verbose_name = 'workspace' <NEW_LINE> permissions = ( ('view_meta_workspace', 'Can view the workspace in a list.'), ('view_contents_workspace', 'Can view the contents of a workspace and clone it.'), ('modify_meta_workspace', 'Can modify the metadata of a workspace.'), ('modify_contents_workspace', 'Can alter the contents of a workspace.'), )
The workspace entity. A workspace is designed so that it provides an independent sandbox for storing and working with various kinds of workspace items and related entities. A workspace is identified by the user+name.
6259900c21a7993f00c66b7a
class ConfigDataRevision(object): <NEW_LINE> <INDENT> __slots__ = ( '_data', '_hash', '__weakref__' ) <NEW_LINE> def __init__(self, data): <NEW_LINE> <INDENT> self._data = data <NEW_LINE> self._hash = self._hash_data(data) <NEW_LINE> <DEDENT> @property <NEW_LINE> def data(self): <NEW_LINE> <INDENT> return self._data <NEW_LINE> <DEDENT> @property <NEW_LINE> def hash(self): <NEW_LINE> <INDENT> return self._hash <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _hash_data(data): <NEW_LINE> <INDENT> if isinstance(data, (dict, list)): <NEW_LINE> <INDENT> to_hash = dumps(data, sort_keys=True) <NEW_LINE> <DEDENT> elif is_proto_message(data): <NEW_LINE> <INDENT> to_hash = ':'.join(( data.__class__.__module__, data.__class__.__name__, data.SerializeToString())) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> to_hash = str(hash(data)) <NEW_LINE> <DEDENT> return md5(to_hash).hexdigest()[:12]
Holds a specific snapshot of the local configuration for config node. It shall be treated as an immutable object, although in Python this is very difficult to enforce! As such, we can compute a unique hash based on the config data which can be used to establish equivalence. It also has a time-stamp to track changes. This object must be treated as immutable, including its nested config data. This is very important. The entire config module depends on hashes we create over the data, so altering the data can lead to unpredictable detriments.
6259900c56b00c62f0fb34bd
class DisablersInFile: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.lastblock = -1 <NEW_LINE> self.lines = set() <NEW_LINE> self.blocks = [] <NEW_LINE> <DEDENT> def copy(self): <NEW_LINE> <INDENT> return deepcopy(self)
Container for file disablers
6259900c3cc13d1c6d466347
class manager: <NEW_LINE> <INDENT> def __init__(self, sub_mgr_list = []): <NEW_LINE> <INDENT> self._sub = {} <NEW_LINE> if isinstance(sub_mgr_list, sub_manager): <NEW_LINE> <INDENT> for mem in sub_mgr_list: <NEW_LINE> <INDENT> self._sub[mem.system_name] = mem <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> ans = "" <NEW_LINE> for system_name in self._sub: <NEW_LINE> <INDENT> if ans != "": <NEW_LINE> <INDENT> ans += ", " <NEW_LINE> <DEDENT> ans += "{0}:{1}".format(system_name, len(self._sub[mem.system_name])) <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> def get_sub_mgr(self, efemeris_filter=None): <NEW_LINE> <INDENT> _sub_mgr = [] <NEW_LINE> for system_name in self._sub: <NEW_LINE> <INDENT> _sub_mgr.append(self._sub[system_name].copy(efemeris_filter)) <NEW_LINE> <DEDENT> return _sub_mgr <NEW_LINE> <DEDENT> def add_sub_manager(self, sub_mgr): <NEW_LINE> <INDENT> if isinstance(sub_mgr, sub_manager): <NEW_LINE> <INDENT> self._sub[sub_mgr.system_name] = sub_mgr <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> def get_satellite_info(self, filter_func): <NEW_LINE> <INDENT> ans = {} <NEW_LINE> for system_name in self._sub: <NEW_LINE> <INDENT> hoge = self._sub[system_name].get_anything() <NEW_LINE> if hoge != None: <NEW_LINE> <INDENT> ans[system_name] = hoge <NEW_LINE> <DEDENT> <DEDENT> return ans
GNSS全ての測位衛星に関するエフェメリスを管理するマネージャークラス 2014/2/16時点では汎用性を重視しています。 今後、利用頻度と汎用性が高いメソッドがあれば実装したいと思います。
6259900c627d3e7fe0e07a9c
class DataContext: <NEW_LINE> <INDENT> server = {'host': '127.0.0.1', 'port': 3306 } <NEW_LINE> user = {'username': 'cwork', 'password': '7HgMoGl7N6FDyP9mIbCp' } <NEW_LINE> database = 'cwork' <NEW_LINE> def __enter__(self): <NEW_LINE> <INDENT> self.connection = pymysql.connect( host = self.server['host'], port = self.server['port'], user = self.user['username'], passwd = self.user['password'], db = self.database ) <NEW_LINE> self.cursor = self.connection.cursor() <NEW_LINE> return self <NEW_LINE> <DEDENT> def __exit__(self, exc_type, exc_val, exc_tb): <NEW_LINE> <INDENT> self.cursor.close() <NEW_LINE> self.connection.close() <NEW_LINE> <DEDENT> def execute(self, sql, *args): <NEW_LINE> <INDENT> self.cursor.execute(sql, *args) <NEW_LINE> return self.cursor <NEW_LINE> <DEDENT> def commit(self): <NEW_LINE> <INDENT> self.connection.commit() <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self.cursor.close() <NEW_LINE> self.cursor = self.connection.cursor()
Класс-обертка для использования подключения к СУБД
6259900c5166f23b2e243fd4
class JsonUtil: <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def itemToStr(item): <NEW_LINE> <INDENT> item = JSONEncoder().encode(item) <NEW_LINE> return ast.literal_eval(item) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def listToStr(items): <NEW_LINE> <INDENT> collection = [] <NEW_LINE> for item in items: <NEW_LINE> <INDENT> collection.append(JsonUtil.itemToStr(item)) <NEW_LINE> <DEDENT> return collection
json.dumps(obj) -- Serialize obj to a JSON formatted str json.loads(str) -- Unserialize a JSON object from a string s
6259900c3cc13d1c6d46634b
class MB_inter_IAMB_Lner(MB_BasedLner): <NEW_LINE> <INDENT> def __init__(self, states_df, alpha, verbose=False, vtx_to_states=None, learn_later=False): <NEW_LINE> <INDENT> MB_BasedLner.__init__(self, states_df, alpha, verbose, vtx_to_states, learn_later) <NEW_LINE> <DEDENT> def find_MB(self, vtx=None): <NEW_LINE> <INDENT> if self.verbose: <NEW_LINE> <INDENT> print('alpha=', self.alpha) <NEW_LINE> <DEDENT> vertices = self.states_df.columns <NEW_LINE> if vtx is None: <NEW_LINE> <INDENT> tar_list = vertices <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tar_list = [vtx] <NEW_LINE> <DEDENT> self.vtx_to_MB = {} <NEW_LINE> for tar in tar_list: <NEW_LINE> <INDENT> self.vtx_to_MB[tar] = [] <NEW_LINE> changing = True <NEW_LINE> while changing: <NEW_LINE> <INDENT> changing = False <NEW_LINE> mi_max = None <NEW_LINE> y_max = None <NEW_LINE> for y in vertices: <NEW_LINE> <INDENT> if y != tar and y not in self.vtx_to_MB[tar]: <NEW_LINE> <INDENT> mi = DataEntropy.cond_mut_info(self.states_df, [tar], [y], self.vtx_to_MB[tar]) <NEW_LINE> if mi_max is None or mi > mi_max: <NEW_LINE> <INDENT> mi_max = mi <NEW_LINE> y_max = y <NEW_LINE> if self.verbose: <NEW_LINE> <INDENT> print('tar, y_max, mi_max=', tar, y_max, mi_max) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> if y_max is not None and mi_max > self.alpha: <NEW_LINE> <INDENT> self.vtx_to_MB[tar].append(y_max) <NEW_LINE> changing = True <NEW_LINE> <DEDENT> for y in self.vtx_to_MB[tar]: <NEW_LINE> <INDENT> mi = DataEntropy.cond_mut_info(self.states_df, [tar], [y], list(set(self.vtx_to_MB[tar]) - {y})) <NEW_LINE> if mi < self.alpha: <NEW_LINE> <INDENT> self.vtx_to_MB[tar].remove(y) <NEW_LINE> changing = True
The MB_inter_IAMB_Lner (Interleaved Incremental Association Markov Blanket Learner) is a subclass of MB_BasedLner. See docstring for MB_BasedLner for more info about this type of algo. Interleaved refers to the fact that the growing and shrinking phases ( growing = adding true positives, shrinking = removing false positives) are intermingled and performed at the same time rather than one after the other as in the original MB_ algo, Grow Shrink. See Shunkai Fu Thesis for pseudo code on which this class is based. Attributes ---------- vtx_to_MB : dict[str, list[str]] A dictionary mapping each vertex to a list of the vertices in its Markov Blanket. (The MB of a node consists of its parents, children and children's parents, aka spouses).
6259900c0a366e3fb87dd5f9
class ShareProtocolSettings(Model): <NEW_LINE> <INDENT> _attribute_map = { 'smb': {'key': 'Smb', 'type': 'ShareSmbSettings', 'xml': {'name': 'SMB'}}, } <NEW_LINE> _xml_map = { } <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(ShareProtocolSettings, self).__init__(**kwargs) <NEW_LINE> self.smb = kwargs.get('smb', None)
Protocol settings. :param smb: Settings for SMB protocol. :type smb: ~azure.storage.fileshare.models.ShareSmbSettings
6259900c5166f23b2e243fd8
class Machine: <NEW_LINE> <INDENT> def __init__(self, r, delta, mat): <NEW_LINE> <INDENT> self.r = r <NEW_LINE> self.delta = delta <NEW_LINE> self.mat = mat <NEW_LINE> self.L = NotImplementedError <NEW_LINE> <DEDENT> @property <NEW_LINE> def V_r(self): <NEW_LINE> <INDENT> return np.pi * self.r ** 2 * self.L <NEW_LINE> <DEDENT> @property <NEW_LINE> def V_s(self): <NEW_LINE> <INDENT> return np.pi * ((1.5 * self.r ** 2) - self.r ** 2) * self.L <NEW_LINE> <DEDENT> def newMachineFromNewLength(self, L) -> "Machine": <NEW_LINE> <INDENT> newMachine = deepcopy(self) <NEW_LINE> newMachine.L = L <NEW_LINE> return newMachine <NEW_LINE> <DEDENT> def check_required_properites(): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_missing_properties(): <NEW_LINE> <INDENT> pass
Class defines a Machine object Attributes: TODO
6259900c462c4b4f79dbc60f
class ChoiceInline(admin.TabularInline): <NEW_LINE> <INDENT> model = Choice <NEW_LINE> extra = 3
Class for choice in admin.
6259900c627d3e7fe0e07aa2
class TensorBundleCoords(VectorBundleCoords): <NEW_LINE> <INDENT> def __init__ (self, value:np.ndarray, *, chart:'CotangentBundleChart') -> None: <NEW_LINE> <INDENT> VectorBundleCoords.__init__(self, value, chart=chart)
Instances of this class each represent a coordinatized point in a particular trivialized chart (i.e. direct product of base and fiber charts) in a particular tensor bundle. Users should not construct instances of this class directly; use the corresponding TensorBundleChart instance instead. The `value` attribute is the actual coordinates value. The `chart` attribute gives the "type" of the coordinates (i.e. the coordinate chart). The base and fiber methods can be used to obtain Coords views into the base and fiber components of the cotangent bundle element that this instance represents.
6259900c0a366e3fb87dd5fd
class ModuleManager: <NEW_LINE> <INDENT> def __init__(self, name): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.modules = OrderedDict() <NEW_LINE> self.module_instance = None <NEW_LINE> self.module_name = '' <NEW_LINE> self.module_parameters = [] <NEW_LINE> <DEDENT> def register(self, module): <NEW_LINE> <INDENT> assert not module.get_module_id() in self.modules <NEW_LINE> self.modules[module.get_module_id()] = module <NEW_LINE> <DEDENT> def get_modules_ids(self): <NEW_LINE> <INDENT> return self.modules.keys() <NEW_LINE> <DEDENT> def get_chosen_name(self): <NEW_LINE> <INDENT> return self.module_name <NEW_LINE> <DEDENT> def get_module(self): <NEW_LINE> <INDENT> assert self.module_instance is not None <NEW_LINE> return self.module_instance <NEW_LINE> <DEDENT> def build_module(self, args): <NEW_LINE> <INDENT> assert self.module_instance is None <NEW_LINE> module_args = getattr(args, self.name) <NEW_LINE> self.module_name = module_args[0] <NEW_LINE> self.module_parameters = module_args[1:] <NEW_LINE> self.module_instance = self.modules[self.module_name](args, *self.module_parameters) <NEW_LINE> return self.module_instance <NEW_LINE> <DEDENT> def add_argparse(self, group_args, comment): <NEW_LINE> <INDENT> assert len(self.modules.keys()) <NEW_LINE> keys = list(self.modules.keys()) <NEW_LINE> group_args.add_argument( '--{}'.format(self.name), type=str, nargs='+', default=[keys[0]], help=comment + ' Choices available: {}'.format(', '.join(keys)) ) <NEW_LINE> <DEDENT> def save(self, config_group): <NEW_LINE> <INDENT> config_group[self.name] = ' '.join([self.module_name] + self.module_parameters) <NEW_LINE> <DEDENT> def load(self, args, config_group): <NEW_LINE> <INDENT> setattr(args, self.name, config_group.get(self.name).split(' ')) <NEW_LINE> <DEDENT> def print(self, args): <NEW_LINE> <INDENT> print('{}: {}'.format( self.name, ' '.join(getattr(args, self.name)) ))
Class which manage modules A module can be any class, as long as it implement the static method get_module_id and has a compatible constructor. The role of the module manager is to ensure that only one of the registered classes are used on the program. The first added module will be the one used by default. For now the modules can't save their state.
6259900dd164cc6175821b86
class Customer(models.Model): <NEW_LINE> <INDENT> qq = models.CharField(verbose_name='qq', max_length=64, unique=True, help_text='QQ号必须唯一') <NEW_LINE> name = models.CharField(verbose_name='学生姓名', max_length=16) <NEW_LINE> gender_choices = ((1, '男'), (2, '女')) <NEW_LINE> gender = models.SmallIntegerField(verbose_name='性别', choices=gender_choices) <NEW_LINE> education_choices = ( (1, '重点大学'), (2, '普通本科'), (3, '独立院校'), (4, '民办本科'), (5, '大专'), (6, '民办专科'), (7, '高中'), (8, '其他') ) <NEW_LINE> education = models.IntegerField(verbose_name='学历', choices=education_choices, blank=True, null=True, ) <NEW_LINE> graduation_school = models.CharField(verbose_name='毕业学校', max_length=64, blank=True, null=True) <NEW_LINE> major = models.CharField(verbose_name='所学专业', max_length=64, blank=True, null=True) <NEW_LINE> experience_choices = [ (1, '在校生'), (2, '应届毕业'), (3, '半年以内'), (4, '半年至一年'), (5, '一年至三年'), (6, '三年至五年'), (7, '五年以上'), ] <NEW_LINE> experience = models.IntegerField(verbose_name='工作经验', blank=True, null=True, choices=experience_choices) <NEW_LINE> work_status_choices = [ (1, '在职'), (2, '无业') ] <NEW_LINE> work_status = models.IntegerField(verbose_name="职业状态", choices=work_status_choices, default=1, blank=True, null=True) <NEW_LINE> company = models.CharField(verbose_name="目前就职公司", max_length=64, blank=True, null=True) <NEW_LINE> salary = models.CharField(verbose_name="当前薪资", max_length=64, blank=True, null=True) <NEW_LINE> source_choices = [ (1, "qq群"), (2, "内部转介绍"), (3, "官方网站"), (4, "百度推广"), (5, "360推广"), (6, "搜狗推广"), (7, "腾讯课堂"), (8, "广点通"), (9, "高校宣讲"), (10, "渠道代理"), (11, "51cto"), (12, "智汇推"), (13, "网盟"), (14, "DSP"), (15, "SEO"), (16, "其它"), ] <NEW_LINE> source = models.SmallIntegerField('客户来源', choices=source_choices, default=1) <NEW_LINE> referral_from = models.ForeignKey( 'self', blank=True, null=True, verbose_name="转介绍自学员", help_text="若此客户是转介绍自内部学员,请在此处选择内部学员姓名", related_name="internal_referral" ) <NEW_LINE> course = models.ManyToManyField(verbose_name="咨询课程", to="Course") <NEW_LINE> status_choices = [ (1, "已报名"), (2, "未报名") ] <NEW_LINE> status = models.IntegerField( verbose_name="状态", choices=status_choices, default=2, help_text=u"选择客户此时的状态" ) <NEW_LINE> consultant = models.ForeignKey(verbose_name="课程顾问", to='UserInfo', related_name='consultanter', limit_choices_to={'depart_id': 1003}) <NEW_LINE> date = models.DateField(verbose_name="咨询日期", auto_now_add=True) <NEW_LINE> recv_date = models.DateField(verbose_name="当前课程顾问的接单日期", null=True) <NEW_LINE> last_consult_date = models.DateField(verbose_name="最后跟进日期", ) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return "姓名:{0},QQ:{1}".format(self.name, self.qq, )
客户表
6259900dbf627c535bcb20ba
class ConsistencyFilter(Filter): <NEW_LINE> <INDENT> def filter(self, parses, explanations): <NEW_LINE> <INDENT> parses = self.validate(parses) <NEW_LINE> if not parses: return [], [] <NEW_LINE> explanations = explanations if isinstance(explanations, list) else [explanations] <NEW_LINE> explanation_dict = {exp.name: exp for exp in explanations} <NEW_LINE> good_parses = [] <NEW_LINE> bad_parses = [] <NEW_LINE> unknown_parses = [] <NEW_LINE> for parse in parses: <NEW_LINE> <INDENT> lf = parse.function <NEW_LINE> exp_name = extract_exp_name(lf) <NEW_LINE> exp = explanation_dict[exp_name] <NEW_LINE> if not isinstance(exp.candidate, RelationMention): <NEW_LINE> <INDENT> unknown_parses.append(parse) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if lf(exp.candidate): <NEW_LINE> <INDENT> good_parses.append(parse) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> bad_parses.append(FilteredParse(parse, exp.candidate)) <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> unknown_parses.append(parse) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if unknown_parses: <NEW_LINE> <INDENT> print("Note: {} LFs did not have candidates and therefore could " "not be filtered.".format(len(unknown_parses))) <NEW_LINE> <DEDENT> good_parses += unknown_parses <NEW_LINE> print("{} parse(s) remain ({} parse(s) removed by {}).".format( len(good_parses), len(bad_parses), self.name())) <NEW_LINE> return good_parses, bad_parses
Filters out parses that incorrectly label their accompanying candidate.
6259900d56b00c62f0fb34c9
class Migration(migrations.Migration): <NEW_LINE> <INDENT> dependencies = [ ('core', '0009_course'), ] <NEW_LINE> operations = [ migrations.RunPython(forward_course_abc_to_mti, backward_course_abc_to_mti) ]
- For each course ABC (Abstract Base Class), instanciate an MTI (Multi Table Inheritance - Save MTI - Associate speakers from ABC to MTI - Delete ABC
6259900d925a0f43d25e8c4b