code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
|---|---|---|
class CommandSendConfirmationStatus(Enum): <NEW_LINE> <INDENT> REJECTED = 0 <NEW_LINE> ACCEPTED = 1
|
Enum class for status of command send confirmation.
|
625990003cc13d1c6d4661c5
|
class TestCompareXLSXFiles(ExcelComparisonTest): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.set_filename('chart_font03.xlsx') <NEW_LINE> <DEDENT> def test_create_file(self): <NEW_LINE> <INDENT> workbook = Workbook(self.got_filename) <NEW_LINE> worksheet = workbook.add_worksheet() <NEW_LINE> chart = workbook.add_chart({'type': 'bar'}) <NEW_LINE> chart.axis_ids = [45704704, 45716224] <NEW_LINE> data = [ [1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], ] <NEW_LINE> worksheet.write_column('A1', data[0]) <NEW_LINE> worksheet.write_column('B1', data[1]) <NEW_LINE> worksheet.write_column('C1', data[2]) <NEW_LINE> chart.add_series({'values': '=Sheet1!$A$1:$A$5'}) <NEW_LINE> chart.add_series({'values': '=Sheet1!$B$1:$B$5'}) <NEW_LINE> chart.add_series({'values': '=Sheet1!$C$1:$C$5'}) <NEW_LINE> chart.set_title({ 'name': 'Title', 'name_font': {'bold': 0, 'italic': 1}, }) <NEW_LINE> chart.set_x_axis({ 'name': 'XXX', 'name_font': {'bold': 0, 'italic': 1}, 'num_font': {'size': 11, 'bold': 1, 'italic': 1}, }) <NEW_LINE> chart.set_y_axis({ 'name': 'YYY', 'name_font': {'bold': 1, 'italic': 1}, 'num_font': {'size': 9, 'bold': 0, 'italic': 1}, }) <NEW_LINE> worksheet.insert_chart('E9', chart) <NEW_LINE> workbook.close() <NEW_LINE> self.assertExcelEqual()
|
Test file created by XlsxWriter against a file created by Excel.
|
62599000627d3e7fe0e07919
|
class SyncServer(ServerBase): <NEW_LINE> <INDENT> def _map_method_to_handler(self, name, method): <NEW_LINE> <INDENT> return self._execute_call
|
A server that executes every RPC synchronously, which means that the server will not return a response to the client
until the request completes.
Although it's very simple, for most implementations you probably want to use :py:class:`Server` instead since with
this server the client can't tell if the server is stuck or the request is still in progress.
:param transport: a transport layer object (e.g. :py:class:`ZeroRPCServerTransport` instance)
:param service: a service object (e.g. a child instance of :py:class:`ServiceBase`)
|
625990003cc13d1c6d4661c9
|
class Rotator: <NEW_LINE> <INDENT> def __init__(self, apps:List[App], duration:int, pauseLength:int): <NEW_LINE> <INDENT> self.apps = apps <NEW_LINE> self.duration = duration <NEW_LINE> self.pauseLength = pauseLength <NEW_LINE> self.paused = True <NEW_LINE> self.pausedUntil = time_ns() + pauseLength <NEW_LINE> self.animator = None <NEW_LINE> <DEDENT> def update(self, now:int, elapsed:int): <NEW_LINE> <INDENT> if self.paused and self.pausedUntil < now: <NEW_LINE> <INDENT> self.pausedUntil = 0 <NEW_LINE> self.paused = False <NEW_LINE> start, finish = zip(*map(lambda a: (a.y, a.y-10), self.apps)) <NEW_LINE> self.animator = Animator(now, start, finish, self.duration) <NEW_LINE> <DEDENT> if self.paused: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> y = self.animator.value(now) <NEW_LINE> if self.animator.done: <NEW_LINE> <INDENT> self.paused = True <NEW_LINE> self.pausedUntil = now + self.pauseLength <NEW_LINE> <DEDENT> for i, app in enumerate(self.apps): <NEW_LINE> <INDENT> app.y = y[i] <NEW_LINE> if app.y <= -10: <NEW_LINE> <INDENT> app.y = (len(self.apps)-1) * 10
|
Rotator rotates apps vertically on the screen
|
625990000a366e3fb87dd472
|
class TestBirthdayChocolate(unittest.TestCase): <NEW_LINE> <INDENT> def test_hackerrank_sample1(self): <NEW_LINE> <INDENT> result = birthday_chocolate([1, 2, 1, 3, 2], 3, 2) <NEW_LINE> self.assertEquals(result, 2) <NEW_LINE> <DEDENT> def test_hackerrank_sample2(self): <NEW_LINE> <INDENT> result = birthday_chocolate([1, 1, 1, 1, 1, 1], 3, 2) <NEW_LINE> self.assertEquals(result, 0) <NEW_LINE> <DEDENT> def test_hackerrank_sample3(self): <NEW_LINE> <INDENT> result = birthday_chocolate([4], 4, 1) <NEW_LINE> self.assertEquals(result, 1) <NEW_LINE> <DEDENT> def test_hackerrank_sample4(self): <NEW_LINE> <INDENT> result = birthday_chocolate([2, 2, 1, 3, 2], 4, 2) <NEW_LINE> self.assertEquals(result, 2)
|
Validate number of segments that can be provided
|
6259900115fb5d323ce7f7c6
|
class ContainerServiceSshConfiguration(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'public_keys': {'required': True}, } <NEW_LINE> _attribute_map = { 'public_keys': {'key': 'publicKeys', 'type': '[ContainerServiceSshPublicKey]'}, } <NEW_LINE> def __init__( self, *, public_keys: List["ContainerServiceSshPublicKey"], **kwargs ): <NEW_LINE> <INDENT> super(ContainerServiceSshConfiguration, self).__init__(**kwargs) <NEW_LINE> self.public_keys = public_keys
|
SSH configuration for Linux-based VMs running on Azure.
All required parameters must be populated in order to send to Azure.
:ivar public_keys: Required. The list of SSH public keys used to authenticate with Linux-based
VMs. Only expect one key specified.
:vartype public_keys:
list[~azure.mgmt.containerservice.v2021_02_01.models.ContainerServiceSshPublicKey]
|
6259900115fb5d323ce7f7ca
|
class CronException(Exception): <NEW_LINE> <INDENT> def __init__(self, value): <NEW_LINE> <INDENT> Exception.__init__(self) <NEW_LINE> self.value = value <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return repr(self.value)
|
cron exception
|
62599001462c4b4f79dbc48f
|
class Fping(extensions.ExtensionDescriptor): <NEW_LINE> <INDENT> name = "Fping" <NEW_LINE> alias = "os-fping" <NEW_LINE> namespace = "http://docs.openstack.org/compute/ext/fping/api/v1.1" <NEW_LINE> updated = "2012-07-06T00:00:00Z" <NEW_LINE> def get_resources(self): <NEW_LINE> <INDENT> res = extensions.ResourceExtension( "os-fping", FpingController()) <NEW_LINE> return [res]
|
Fping Management Extension.
|
62599001627d3e7fe0e07927
|
class _CDC_DescriptorSubTypes: <NEW_LINE> <INDENT> HEADER_FUNCTIONAL = 0 <NEW_LINE> CALL_MANAGMENT = 1 <NEW_LINE> ABSTRACT_CONTROL_MANAGEMENT = 2 <NEW_LINE> DIRECT_LINE_MANAGEMENT = 3 <NEW_LINE> TELEPHONE_RINGER = 4 <NEW_LINE> TELEPHONE_CALL = 5 <NEW_LINE> UNION_FUNCTIONAL = 6 <NEW_LINE> COUNTRY_SELECTION = 7 <NEW_LINE> TELEPHONE_OPERATIONAL_MODES = 8 <NEW_LINE> USB_TERMINAL = 9 <NEW_LINE> NETWORK_CHANNEL_TERMINAL = 0xa <NEW_LINE> PROTOCOL_UNIT = 0xb <NEW_LINE> EXTENSION_UNIT = 0xc <NEW_LINE> MULTI_CHANNEL_MANAGEMENT = 0xd <NEW_LINE> CAPI_CONTROL_MANAGEMENT = 0xe <NEW_LINE> ETHERNET_NETWORKING = 0xf <NEW_LINE> ATM_NETWORKING = 0x10
|
Descriptor sub types [usbcdc11.pdf table 25]
|
625990013cc13d1c6d4661d7
|
class CommonInvalidParam7(IndyError): <NEW_LINE> <INDENT> pass
|
Caller passed invalid value as param 7 (null, invalid json and etc..)
|
62599001462c4b4f79dbc493
|
class Health_Indicator(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=100, unique=True) <NEW_LINE> important = models.BooleanField( default=False, verbose_name='Show on overview', help_text='Display a chart for this indicator on the overview page for a state or county' ) <NEW_LINE> slug = models.SlugField() <NEW_LINE> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> if self.slug is None or self.slug == '': <NEW_LINE> <INDENT> self.slug = slugify(self.name) <NEW_LINE> <DEDENT> super(Health_Indicator, self).save(*args, **kwargs) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return f"{self.name} ({self.id})" <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = 'Health indicator'
|
Represents some health metric that we want to store data sets for,
e.g. obesity, mortality, education, etc.
|
6259900115fb5d323ce7f7d2
|
class MITCampus(Campus): <NEW_LINE> <INDENT> def __init__(self, center_loc, tent_loc = Location(0,0)): <NEW_LINE> <INDENT> Campus.__init__(self, center_loc) <NEW_LINE> self.tents=[] <NEW_LINE> self.add_tent(tent_loc) <NEW_LINE> <DEDENT> def add_tent(self, new_tent_loc): <NEW_LINE> <INDENT> for l in self.tents: <NEW_LINE> <INDENT> if l.dist_from(new_tent_loc) < 0.5: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> self.tents.append(new_tent_loc) <NEW_LINE> return True <NEW_LINE> <DEDENT> def remove_tent(self, tent_loc): <NEW_LINE> <INDENT> self.tents.remove(tent_loc) <NEW_LINE> <DEDENT> def get_tents(self): <NEW_LINE> <INDENT> tents = [] <NEW_LINE> for t in self.tents: <NEW_LINE> <INDENT> tents.append(t.__str__()) <NEW_LINE> <DEDENT> tents.sort() <NEW_LINE> return tents
|
A MITCampus is a Campus that contains tents
|
625990013cc13d1c6d4661df
|
class DateRange: <NEW_LINE> <INDENT> thrift_spec = ( None, (1, TType.I64, 'dateFrom', None, None, ), (2, TType.I64, 'dateTo', None, None, ), ) <NEW_LINE> def __init__(self, dateFrom=None, dateTo=None,): <NEW_LINE> <INDENT> self.dateFrom = dateFrom <NEW_LINE> self.dateTo = dateTo <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 1: <NEW_LINE> <INDENT> if ftype == TType.I64: <NEW_LINE> <INDENT> self.dateFrom = iprot.readI64(); <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 2: <NEW_LINE> <INDENT> if ftype == TType.I64: <NEW_LINE> <INDENT> self.dateTo = iprot.readI64(); <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('DateRange') <NEW_LINE> if self.dateFrom is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('dateFrom', TType.I64, 1) <NEW_LINE> oprot.writeI64(self.dateFrom) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.dateTo is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('dateTo', TType.I64, 2) <NEW_LINE> oprot.writeI64(self.dateTo) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other)
|
DTO
Attributes:
- dateFrom
- dateTo
|
62599001627d3e7fe0e07937
|
class Business(): <NEW_LINE> <INDENT> def __init__(self, busId, userId, busName, busLocation, busCategory, busDescription): <NEW_LINE> <INDENT> self.busId=busId <NEW_LINE> self.userId=userId <NEW_LINE> self.busName = busName <NEW_LINE> self.busLocation=busLocation <NEW_LINE> self.busCategory=busCategory <NEW_LINE> self.busDescription = busDescription <NEW_LINE> self.businessList = [] <NEW_LINE> <DEDENT> def createBusiness(self, busId, userId, busName, busLocation, busCategory, busDescription): <NEW_LINE> <INDENT> result = None <NEW_LINE> oldBizListLength = len(self.businessList) <NEW_LINE> self.businessList.append({busId:[userId, busName, busLocation, busCategory, busDescription]}) <NEW_LINE> if len(self.businessList) > oldBizListLength: <NEW_LINE> <INDENT> result = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result = False <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def checkBusinessExists(self, busId): <NEW_LINE> <INDENT> if self.businessList: <NEW_LINE> <INDENT> print('here') <NEW_LINE> for bus in self.businessList: <NEW_LINE> <INDENT> if busId in bus.keys(): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> result = False <NEW_LINE> <DEDENT> <DEDENT> def updateBusiness(self, busId, userId, busName, busLocation, busCategory, busDescription): <NEW_LINE> <INDENT> oldList=[] <NEW_LINE> newList=[] <NEW_LINE> if self.businessList: <NEW_LINE> <INDENT> for xt in self.businessList: <NEW_LINE> <INDENT> for key, val in xt.items(): <NEW_LINE> <INDENT> if key == busId: <NEW_LINE> <INDENT> oldList.append([x for x in val]) <NEW_LINE> xt[key]=[busId, userId, busName, busLocation, busCategory, busDescription] <NEW_LINE> newList.append([x for x in xt[key]]) <NEW_LINE> if oldList[0] == newList[0] and oldList[1] == newList[1] and oldList[2] == newList[2] and oldList[3] == newList[3] and oldList[4] == newList[4]: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def deleteBusiness(self, busId): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def getOwnBusinesses(self, userId): <NEW_LINE> <INDENT> foundrows=[] <NEW_LINE> if self.businessList: <NEW_LINE> <INDENT> for x in self.businessList: <NEW_LINE> <INDENT> for val in x.values(): <NEW_LINE> <INDENT> if val[0] == userId: <NEW_LINE> <INDENT> foundrows.append(x) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return foundrows <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> <DEDENT> def getAllBusinesses(self): <NEW_LINE> <INDENT> foundBusinesses = [] <NEW_LINE> if len(self.businessList) > 0: <NEW_LINE> <INDENT> for x in self.businessList: <NEW_LINE> <INDENT> foundBusinesses.append(x) <NEW_LINE> <DEDENT> <DEDENT> return foundBusinesses
|
class that handles bussiness logic ie. create business,view own businesses,view all businesses,
delete a business and update business the functions in this class include
createBusiness, checkBusinessExists, updateBusiness, deleteBusiness, getOwnBusinesses, getAllBusinesses
|
6259900115fb5d323ce7f7e0
|
class ModelTests(TestCase): <NEW_LINE> <INDENT> def test_create_user_with_email_successful(self): <NEW_LINE> <INDENT> email = 'test@gmail.com' <NEW_LINE> password = 'Testpass1234' <NEW_LINE> user = get_user_model().objects.create_user( email=email, password=password ) <NEW_LINE> self.assertEqual(user.email, email) <NEW_LINE> self.assertTrue(user.check_password(password)) <NEW_LINE> <DEDENT> def test_new_user_email_normalized(self): <NEW_LINE> <INDENT> email = 'test@GMAIL.COM' <NEW_LINE> user = get_user_model().objects.create_user(email, 'Testpass1234') <NEW_LINE> self.assertEqual(user.email, email.lower()) <NEW_LINE> <DEDENT> def test_new_user_invalid_email(self): <NEW_LINE> <INDENT> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> get_user_model().objects.create_user(None, 'Testpass1234') <NEW_LINE> <DEDENT> <DEDENT> def test_create_new_superuser(self): <NEW_LINE> <INDENT> user = get_user_model().objects.create_superuser( 'test@gmail.com', 'Testpass1234' ) <NEW_LINE> self.assertTrue(user.is_superuser) <NEW_LINE> self.assertTrue(user.is_staff) <NEW_LINE> <DEDENT> def test_tag_str(self): <NEW_LINE> <INDENT> tag = models.Tag.objects.create( user=sample_user(), name='Vegan' ) <NEW_LINE> self.assertEqual(str(tag), tag.name) <NEW_LINE> <DEDENT> def test_ingredients_str(self): <NEW_LINE> <INDENT> ingredient = models.Ingredient.objects.create( user=sample_user(), name='Cucumber' ) <NEW_LINE> self.assertEqual(str(ingredient), ingredient.name) <NEW_LINE> <DEDENT> def test_recipe_str(self): <NEW_LINE> <INDENT> recipe = models.Recipe.objects.create( user=sample_user(), title='Steak and mushroom sauce', time_minutes=5, price=5.00 ) <NEW_LINE> self.assertEqual(str(recipe), recipe.title) <NEW_LINE> <DEDENT> @patch('uuid.uuid4') <NEW_LINE> def test_recipe_filename_uuid(self, mock_uuid): <NEW_LINE> <INDENT> uuid = 'test-uuid' <NEW_LINE> mock_uuid.return_value = uuid <NEW_LINE> file_path = models.recipe_image_file_path(None, 'myimage.jpg') <NEW_LINE> exp_path = f'uploads/recipe/{uuid}.jpg' <NEW_LINE> self.assertEqual(file_path, exp_path)
|
docstring for ModelTests.
|
625990013cc13d1c6d4661eb
|
class OrthoArrayAdapter(_ArrayAdapter): <NEW_LINE> <INDENT> def _apply_keys(self): <NEW_LINE> <INDENT> array = self._concrete.__getitem__(self._keys) <NEW_LINE> return array
|
Exposes a "concrete" data source which supports orthogonal indexing
as a :class:`biggus.Array`.
Orthogonal indexing treats multiple iterable index keys as
independent (which is also the behaviour of a :class:`biggus.Array`).
For example::
>>> ortho_concrete.shape
(100, 200, 300)
>> ortho_concrete[(0, 3, 4), :, (1, 9)].shape
(3, 200, 2)
A netCDF4.Variable instance is an example orthogonal concrete array.
NB. Orthogonal indexing contrasts with NumPy "fancy indexing" where
multiple iterable index keys are zipped together to allow the
selection of sparse locations.
|
625990023cc13d1c6d4661ed
|
class ProductListAdmin(views.MethodView): <NEW_LINE> <INDENT> template = 'panel/product_list.html' <NEW_LINE> @login_required <NEW_LINE> @panel_permission.require(401) <NEW_LINE> def get(self): <NEW_LINE> <INDENT> products = ProductModel.query.order_by(ProductModel.id).all() <NEW_LINE> return render_template(self.template, products=products)
|
`get`: 查询产品列表
|
62599002462c4b4f79dbc4a9
|
class Pawn: <NEW_LINE> <INDENT> def pawn(self): <NEW_LINE> <INDENT> pdxy = self.cursor - self.select <NEW_LINE> flag = 1 if self.isRed else -1 <NEW_LINE> if abs(pdxy.x) + abs(pdxy.y) != 1 or flag * pdxy.y < 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> st, sp = (0, 4) if self.isRed else (5, 9) <NEW_LINE> if abs(pdxy.x) == 1 and st <= self.select.y <= sp: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True
|
兵卒类
|
625990023cc13d1c6d4661ef
|
class Engine: <NEW_LINE> <INDENT> bots = [] <NEW_LINE> def __init__(self, arg): <NEW_LINE> <INDENT> self.arg = arg <NEW_LINE> <DEDENT> def start_bot(self, bot): <NEW_LINE> <INDENT> self.bots.append(bot) <NEW_LINE> <DEDENT> def stop_bot(self, bot): <NEW_LINE> <INDENT> self.bots.bot.stop()
|
docstring for particular_bot
|
62599002627d3e7fe0e07947
|
class NoForceFoundError(Exception): <NEW_LINE> <INDENT> pass
|
Error raised when no forces matching the given criteria are found.
|
62599002627d3e7fe0e07949
|
@pytest.mark.release <NEW_LINE> class TestSqlAlchemyStoreMysqlDb(TestSqlAlchemyStoreSqlite): <NEW_LINE> <INDENT> DEFAULT_MYSQL_PORT = 3306 <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> os.environ[MLFLOW_SQLALCHEMYSTORE_POOL_SIZE] = "2" <NEW_LINE> os.environ[MLFLOW_SQLALCHEMYSTORE_MAX_OVERFLOW] = "1" <NEW_LINE> db_username = os.environ.get("MYSQL_TEST_USERNAME") <NEW_LINE> db_password = os.environ.get("MYSQL_TEST_PASSWORD") <NEW_LINE> db_port = int(os.environ["MYSQL_TEST_PORT"]) if "MYSQL_TEST_PORT" in os.environ else TestSqlAlchemyStoreMysqlDb.DEFAULT_MYSQL_PORT <NEW_LINE> if db_username is None or db_password is None: <NEW_LINE> <INDENT> raise Exception( "Username and password for database tests must be specified via the " "MYSQL_TEST_USERNAME and MYSQL_TEST_PASSWORD environment variables. " "environment variable. In posix shells, you can rerun your test command " "with the environment variables set, e.g: MYSQL_TEST_USERNAME=your_username " "MYSQL_TEST_PASSWORD=your_password <your-test-command>. You may optionally " "specify a database port via MYSQL_TEST_PORT (default is 3306).") <NEW_LINE> <DEDENT> self._db_name = "test_sqlalchemy_store_%s" % uuid.uuid4().hex[:5] <NEW_LINE> db_server_url = "mysql://%s:%s@localhost:%s" % (db_username, db_password, db_port) <NEW_LINE> self._engine = sqlalchemy.create_engine(db_server_url) <NEW_LINE> self._engine.execute("CREATE DATABASE %s" % self._db_name) <NEW_LINE> self.db_url = "%s/%s" % (db_server_url, self._db_name) <NEW_LINE> self.store = self._get_store(self.db_url) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> self._engine.execute("DROP DATABASE %s" % self._db_name) <NEW_LINE> <DEDENT> def test_log_many_entities(self): <NEW_LINE> <INDENT> run = self._run_factory() <NEW_LINE> for i in range(100): <NEW_LINE> <INDENT> self.store.log_metric(run.info.run_id, entities.Metric("key", i, i * 2, i * 3)) <NEW_LINE> self.store.log_param(run.info.run_id, entities.Param("pkey-%s" % i, "pval-%s" % i)) <NEW_LINE> self.store.set_tag(run.info.run_id, entities.RunTag("tkey-%s" % i, "tval-%s" % i))
|
Run tests against a MySQL database
|
625990020a366e3fb87dd4a1
|
class BlockInit(Expr): <NEW_LINE> <INDENT> def __init__(self, body: [Expr]): <NEW_LINE> <INDENT> self.body = body
|
Initializer Block Expression
|
62599002462c4b4f79dbc4b5
|
class SensAnalysisDelegate(QtGui.QItemDelegate): <NEW_LINE> <INDENT> def __init__(self, parent, windowObject): <NEW_LINE> <INDENT> QtGui.QItemDelegate.__init__(self, parent) <NEW_LINE> self.parent = parent <NEW_LINE> <DEDENT> def createEditor(self, parent, option, index): <NEW_LINE> <INDENT> if index.column() <=1: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if index.model().getDataType(index) == "Vector": <NEW_LINE> <INDENT> self.editor = QtGui.QComboBox(parent) <NEW_LINE> self.editor.setDuplicatesEnabled(True) <NEW_LINE> self.editor.setEditable(True) <NEW_LINE> self.editor.setInsertPolicy(QtGui.QComboBox.InsertAtCurrent) <NEW_LINE> self.connect(self.editor, QtCore.SIGNAL("editTextChanged(const QString)"),self.hook) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.editor = QtGui.QLineEdit(parent) <NEW_LINE> <DEDENT> self.editor.setInputMethodHints(QtCore.Qt.ImhFormattedNumbersOnly) <NEW_LINE> return self.editor <NEW_LINE> <DEDENT> def hook(self, newText): <NEW_LINE> <INDENT> self.editor.setItemText(self.editor.currentIndex(),newText) <NEW_LINE> <DEDENT> def setEditorData(self, editor, index): <NEW_LINE> <INDENT> if isinstance(editor,QtGui.QComboBox): <NEW_LINE> <INDENT> editor.addItems(index.model().getData(index)) <NEW_LINE> self.editor.view().setMinimumWidth(self.calculateListWidth()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> editor.setText(index.model().getData(index)) <NEW_LINE> <DEDENT> <DEDENT> def setModelData(self, editor, model, index): <NEW_LINE> <INDENT> if isinstance(editor,QtGui.QComboBox): <NEW_LINE> <INDENT> for i in range(0,editor.count()): <NEW_LINE> <INDENT> index.model().setData(index,editor.itemText(i),i) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> index.model().setData(index,editor.text()) <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> def calculateListWidth(self): <NEW_LINE> <INDENT> fm = QtGui.QFontMetrics(self.editor.view().font()) <NEW_LINE> minimumWidth = 0 <NEW_LINE> for i in range(0,self.editor.count()): <NEW_LINE> <INDENT> if fm.width(self.editor.itemText(i)) > minimumWidth: <NEW_LINE> <INDENT> minimumWidth = fm.width(self.editor.itemText(i)) <NEW_LINE> <DEDENT> <DEDENT> return minimumWidth <NEW_LINE> <DEDENT> def commitAndCloseEditor(self): <NEW_LINE> <INDENT> self.emit(QtCore.SIGNAL("closeEditor(QWidget*)"), self.sender())
|
This class is responsible of controlling the user interaction with a QTableView.(saTab.saList in this case)
|
62599002627d3e7fe0e07950
|
class ReferenceSource: <NEW_LINE> <INDENT> def __init__(self, commit): <NEW_LINE> <INDENT> self.src_dir = tempfile.mkdtemp() <NEW_LINE> print("Cloning git repo to a separate work directory...") <NEW_LINE> subprocess.check_output(['git', 'clone', os.getcwd(), '.'], cwd=self.src_dir) <NEW_LINE> print("Checkout '%s' to build the original autoconf.mk." % subprocess.check_output(['git', 'rev-parse', '--short', commit]).strip()) <NEW_LINE> subprocess.check_output(['git', 'checkout', commit], stderr=subprocess.STDOUT, cwd=self.src_dir) <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> shutil.rmtree(self.src_dir) <NEW_LINE> <DEDENT> def get_dir(self): <NEW_LINE> <INDENT> return self.src_dir
|
Reference source against which original configs should be parsed.
|
625990020a366e3fb87dd4a5
|
class CodeStatTest(TestCase): <NEW_LINE> <INDENT> def test_code_stat_returns_proper_values(self): <NEW_LINE> <INDENT> known_values = ( ( (source, code, 100, 50), (200, 200, 200, 2, 2, 2, 100, 50), ), ) <NEW_LINE> for args, result in known_values: <NEW_LINE> <INDENT> self.assertEqual(code_stat(*args), result)
|
Testing code_stat_test function.
|
625990023cc13d1c6d466200
|
class Card(object): <NEW_LINE> <INDENT> rank_offset = 1 <NEW_LINE> rank_two = 2 - rank_offset <NEW_LINE> rank_eight = 8 - rank_offset <NEW_LINE> rank_jack = 11 - rank_offset <NEW_LINE> rank_queen = 12 - rank_offset <NEW_LINE> @staticmethod <NEW_LINE> def make_deck_index(rank, suit): <NEW_LINE> <INDENT> suit_placement = suit * Card.suit_size() <NEW_LINE> return suit_placement + rank <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def num_suits(): <NEW_LINE> <INDENT> return 4 <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def suit_size(): <NEW_LINE> <INDENT> return 13 <NEW_LINE> <DEDENT> def __init__(self, deck_index): <NEW_LINE> <INDENT> self.__deck_index = deck_index <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.rank == other.rank and self.suit == other.suit <NEW_LINE> <DEDENT> def __deepcopy__(self, memo): <NEW_LINE> <INDENT> self_copy = Card(self.__deck_index) <NEW_LINE> memo[id(self)] = self_copy <NEW_LINE> return self_copy <NEW_LINE> <DEDENT> @property <NEW_LINE> def deck_index(self): <NEW_LINE> <INDENT> return self.__deck_index <NEW_LINE> <DEDENT> @property <NEW_LINE> def suit(self): <NEW_LINE> <INDENT> suit = self.__deck_index / Card.suit_size() <NEW_LINE> return suit <NEW_LINE> <DEDENT> @property <NEW_LINE> def rank(self): <NEW_LINE> <INDENT> rank = self.__deck_index % Card.suit_size() <NEW_LINE> return rank
|
A playing card.
|
625990023cc13d1c6d466203
|
class ProxOp(ProximalOperatorBaseClass): <NEW_LINE> <INDENT> @wraps(func) <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.args = args <NEW_LINE> self.kwargs = kwargs <NEW_LINE> <DEDENT> def __call__(self, x, rho=1.0): <NEW_LINE> <INDENT> return func(x, rho, *self.args, **self.kwargs)
|
Proximal operator base class
|
625990023cc13d1c6d466204
|
@dataclass <NEW_LINE> class ReadInt(Function): <NEW_LINE> <INDENT> src = Inputs.path( description='Path to a input text file.', path='input_path' ) <NEW_LINE> @command <NEW_LINE> def read_integer(self): <NEW_LINE> <INDENT> return 'echo parsing text information to an integer...' <NEW_LINE> <DEDENT> data = Outputs.int( description='The content of text file as an integer.', path='input_path' )
|
Read content of a text file as an integer.
|
6259900215fb5d323ce7f7fe
|
class Vector2D: <NEW_LINE> <INDENT> def __init__(self, x=0, y=0): <NEW_LINE> <INDENT> self.x = x <NEW_LINE> self.y = y <NEW_LINE> if hasattr(x, "__getitem__"): <NEW_LINE> <INDENT> x, y = x <NEW_LINE> self._v = [float(x), float(y)] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._v = [float(x), float(y)] <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return f"({self.x}, {self.y})" <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def from_points(p1, p2): <NEW_LINE> <INDENT> return Vector2D(p2[0] - p1[0], p2[1] - p1[1]) <NEW_LINE> <DEDENT> def get_magnitute(self): <NEW_LINE> <INDENT> return math.sqrt(self.x ** 2 + self.y ** 2) <NEW_LINE> <DEDENT> def normalize(self): <NEW_LINE> <INDENT> magnitude = self.get_magnitute() <NEW_LINE> try: <NEW_LINE> <INDENT> self.x /= magnitude <NEW_LINE> self.y /= magnitude <NEW_LINE> <DEDENT> except ZeroDivisionError: <NEW_LINE> <INDENT> self.x = 0 <NEW_LINE> self.y = 0 <NEW_LINE> <DEDENT> <DEDENT> def __add__(self, other): <NEW_LINE> <INDENT> return Vector2D(self.x + other.x, self.y + other.y) <NEW_LINE> <DEDENT> def __neg__(self): <NEW_LINE> <INDENT> return Vector2D(-self.x, -self.y) <NEW_LINE> <DEDENT> def __sub__(self, other): <NEW_LINE> <INDENT> return Vector2D(self.x - other.x, self.y - other.y) <NEW_LINE> <DEDENT> def __mul__(self, scalar): <NEW_LINE> <INDENT> return Vector2D(self.x * scalar, self.y * scalar) <NEW_LINE> <DEDENT> def __truediv__(self, scalar): <NEW_LINE> <INDENT> return Vector2D(self.x / scalar, self.y / scalar) <NEW_LINE> <DEDENT> def __getitem__(self, index): <NEW_LINE> <INDENT> return self._v[index] <NEW_LINE> <DEDENT> def __setitem__(self, index, value): <NEW_LINE> <INDENT> self._v[index] = 1.0 * value
|
Class utilitity for Vector objects operations
|
625990020a366e3fb87dd4af
|
class DBStore(Store): <NEW_LINE> <INDENT> def __init__(self, db, table_name): <NEW_LINE> <INDENT> self.db = db <NEW_LINE> self.table = table_name <NEW_LINE> <DEDENT> def __contains__(self, key): <NEW_LINE> <INDENT> data = self.db.select(self.table, where='session_id=$key', vars=locals()) <NEW_LINE> return bool(list(data)) <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> now = datetime.datetime.now() <NEW_LINE> try: <NEW_LINE> <INDENT> s = self.db.select(self.table, where='session_id=$key', vars=locals())[0] <NEW_LINE> self.db.update(self.table, where='session_id=$key', atime=now, vars=locals()) <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> raise KeyError(key) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.decode(s.data) <NEW_LINE> <DEDENT> <DEDENT> def __setitem__(self, key, value): <NEW_LINE> <INDENT> pickled = self.encode(value) <NEW_LINE> now = datetime.datetime.now() <NEW_LINE> if key in self: <NEW_LINE> <INDENT> self.db.update(self.table, where="session_id=$key", data=pickled, vars=locals()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.db.insert(self.table, False, session_id=key, data=pickled) <NEW_LINE> <DEDENT> <DEDENT> def __delitem__(self, key): <NEW_LINE> <INDENT> self.db.delete(self.table, where="session_id=$key", vars=locals()) <NEW_LINE> <DEDENT> def cleanup(self, timeout): <NEW_LINE> <INDENT> timeout = datetime.timedelta(timeout/(24.0*60*60)) <NEW_LINE> last_allowed_time = datetime.datetime.now() - timeout <NEW_LINE> self.db.delete(self.table, where="$last_allowed_time > atime", vars=locals())
|
Store for saving a session in database.
Needs a table with the following columns:
session_id CHAR(128) UNIQUE NOT NULL,
atime DATATIME NOT NULL DEFAULT current_timestamp,
data TEXT
|
62599002d164cc6175821a3b
|
class OutputData(): <NEW_LINE> <INDENT> def __init__(self,size=1): <NEW_LINE> <INDENT> self.dictionary={"one":1} <NEW_LINE> self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) <NEW_LINE> self.size=size <NEW_LINE> <DEDENT> def test_1(self): <NEW_LINE> <INDENT> sys.stderr.write("x"*self.size) <NEW_LINE> <DEDENT> def test_2(self): <NEW_LINE> <INDENT> self.socket.sendto("x"*self.size,('127.0.0.1',10000)) <NEW_LINE> <DEDENT> def post_test_2(self): <NEW_LINE> <INDENT> self.socket.close()
|
Compare speed of writing data to a remote UDP listener using 2 different methods:
* Write to stdout/stderr and pipe to remote listener using netcat
* Write directly to the remote listener
Start in another shell a listening UDP server which writes data to /dev/null:
$ nc -klu localhost 10000 > /dev/null
Start this script by redirecting STDERR to a nc process:
$ python compare_stdout_socket.py 2> >(nc -w1 -u localhost 10000)
|
625990023cc13d1c6d46620a
|
class RolesTestCase(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.course = Location('i4x://edX/toy/course/2012_Fall') <NEW_LINE> self.anonymous_user = AnonymousUserFactory() <NEW_LINE> self.student = UserFactory() <NEW_LINE> self.global_staff = UserFactory(is_staff=True) <NEW_LINE> self.course_staff = StaffFactory(course=self.course) <NEW_LINE> self.course_instructor = InstructorFactory(course=self.course) <NEW_LINE> <DEDENT> def test_global_staff(self): <NEW_LINE> <INDENT> self.assertFalse(GlobalStaff().has_user(self.student)) <NEW_LINE> self.assertFalse(GlobalStaff().has_user(self.course_staff)) <NEW_LINE> self.assertFalse(GlobalStaff().has_user(self.course_instructor)) <NEW_LINE> self.assertTrue(GlobalStaff().has_user(self.global_staff)) <NEW_LINE> <DEDENT> def test_group_name_case_insensitive(self): <NEW_LINE> <INDENT> uppercase_loc = "i4x://ORG/COURSE/course/NAME" <NEW_LINE> lowercase_loc = uppercase_loc.lower() <NEW_LINE> lowercase_group = "role_org/course/name" <NEW_LINE> uppercase_group = lowercase_group.upper() <NEW_LINE> lowercase_user = UserFactory(groups=lowercase_group) <NEW_LINE> uppercase_user = UserFactory(groups=uppercase_group) <NEW_LINE> self.assertTrue(CourseRole("role", lowercase_loc).has_user(lowercase_user)) <NEW_LINE> self.assertTrue(CourseRole("role", uppercase_loc).has_user(lowercase_user)) <NEW_LINE> self.assertTrue(CourseRole("role", lowercase_loc).has_user(uppercase_user)) <NEW_LINE> self.assertTrue(CourseRole("role", uppercase_loc).has_user(uppercase_user)) <NEW_LINE> <DEDENT> def test_course_role(self): <NEW_LINE> <INDENT> course_locator = loc_mapper().translate_location( self.course.course_id, self.course, add_entry_if_missing=True ) <NEW_LINE> self.assertFalse( CourseStaffRole(course_locator).has_user(self.student), "Student has premature access to {}".format(unicode(course_locator)) ) <NEW_LINE> self.assertFalse( CourseStaffRole(self.course).has_user(self.student), "Student has premature access to {}".format(self.course.url()) ) <NEW_LINE> CourseStaffRole(course_locator).add_users(self.student) <NEW_LINE> self.assertTrue( CourseStaffRole(course_locator).has_user(self.student), "Student doesn't have access to {}".format(unicode(course_locator)) ) <NEW_LINE> self.assertTrue( CourseStaffRole(self.course).has_user(self.student), "Student doesn't have access to {}".format(unicode(self.course.url())) ) <NEW_LINE> vertical_locator = BlockUsageLocator( course_id=course_locator.course_id, branch='published', block_id='madeup' ) <NEW_LINE> vertical_location = self.course.replace(category='vertical', name='madeuptoo') <NEW_LINE> self.assertTrue( CourseStaffRole(vertical_locator).has_user(self.student), "Student doesn't have access to {}".format(unicode(vertical_locator)) ) <NEW_LINE> self.assertTrue( CourseStaffRole(vertical_location, course_context=self.course.course_id).has_user(self.student), "Student doesn't have access to {}".format(unicode(vertical_location.url())) )
|
Tests of student.roles
|
6259900315fb5d323ce7f808
|
class RecoveryData(FailureData): <NEW_LINE> <INDENT> event = 'Recovery'
|
Holds recovery event data
|
625990030a366e3fb87dd4b9
|
@endpoint("openapi/ref/v1/exchanges/") <NEW_LINE> class ExchangeList(ReferenceData): <NEW_LINE> <INDENT> @dyndoc_insert(responses) <NEW_LINE> def __init__(self, params=None): <NEW_LINE> <INDENT> super(ExchangeList, self).__init__() <NEW_LINE> self.params = params
|
Retrieve a list of exchanges with detailed information about each.
The response also contains links to other relevant data, such as their
trade statuses.
|
62599003462c4b4f79dbc4d1
|
class TextFile(object): <NEW_LINE> <INDENT> UTF8_MARKER = chr(239) + chr(187) + chr(191) <NEW_LINE> _UTF8_MARKER_LEN = len(UTF8_MARKER) <NEW_LINE> UTF16_MARKER = chr(255) + chr(254) <NEW_LINE> _UTF16_MARKER_LEN = len(UTF16_MARKER) <NEW_LINE> def __init__(self, file_name, mode='r', encoding=None): <NEW_LINE> <INDENT> self.file_name = file_name <NEW_LINE> self.mode = mode.lower() <NEW_LINE> self.encoding = encoding <NEW_LINE> if self.encoding is not None: <NEW_LINE> <INDENT> self.encoding = self.encoding.lower().replace('-', '') <NEW_LINE> <DEDENT> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> self.file_object = None <NEW_LINE> if 'r' in self.mode: <NEW_LINE> <INDENT> if PYTHON_VERSION < 3: <NEW_LINE> <INDENT> with codecs.open(self.file_name, self.mode) as f: <NEW_LINE> <INDENT> header = f.read(3) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> with codecs.open(self.file_name, self.mode, encoding='ansi') as f: <NEW_LINE> <INDENT> header = f.read(3) <NEW_LINE> <DEDENT> <DEDENT> if header.startswith(self.UTF8_MARKER): <NEW_LINE> <INDENT> self.encoding = 'utf8' <NEW_LINE> <DEDENT> elif header.startswith(self.UTF16_MARKER): <NEW_LINE> <INDENT> self.encoding = 'utf16' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.encoding = 'utf8' <NEW_LINE> <DEDENT> <DEDENT> if 'w' in self.mode: <NEW_LINE> <INDENT> if self.encoding is not None and self.encoding not in ('utf8', 'utf16'): <NEW_LINE> <INDENT> raise TypeError('unable to save with encoding "{}"'.format(self.encoding)) <NEW_LINE> <DEDENT> <DEDENT> if self.encoding is None: <NEW_LINE> <INDENT> if PYTHON_VERSION < 3: <NEW_LINE> <INDENT> self.file_object = codecs.open(self.file_name, self.mode) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.file_object = codecs.open(self.file_name, self.mode, encoding='ansi') <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.file_object = codecs.open(self.file_name, self.mode, encoding=self.encoding) <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> def __exit__(self, *args): <NEW_LINE> <INDENT> self.file_object.close() <NEW_LINE> return <NEW_LINE> <DEDENT> def readlines(self, as_unicode=True): <NEW_LINE> <INDENT> return [self._process_output(line, index=i, as_unicode=as_unicode) for i, line in enumerate(self.file_object.readlines())] <NEW_LINE> <DEDENT> def read(self, limit=-1): <NEW_LINE> <INDENT> return self._process_output(self.file_object.read(limit), index=self.file_object.tell()) <NEW_LINE> <DEDENT> def _process_output(self, output, index=None, as_unicode=True): <NEW_LINE> <INDENT> output = output.strip() <NEW_LINE> if index is not None and not index: <NEW_LINE> <INDENT> if self.encoding == 'utf8' and ord(output[0]) == 65279: <NEW_LINE> <INDENT> output = output[1:] <NEW_LINE> <DEDENT> <DEDENT> if self.encoding is not None and not as_unicode: <NEW_LINE> <INDENT> output = output.encode('utf8') <NEW_LINE> <DEDENT> output = output.strip() <NEW_LINE> if PYTHON_VERSION == 2: <NEW_LINE> <INDENT> return output <NEW_LINE> <DEDENT> return str(output) <NEW_LINE> <DEDENT> def write(self, text, encoding=None): <NEW_LINE> <INDENT> if encoding is None: <NEW_LINE> <INDENT> encoding = self.encoding <NEW_LINE> <DEDENT> if encoding: <NEW_LINE> <INDENT> return self.file_object.write(text.decode(encoding)) <NEW_LINE> <DEDENT> return self.file_object.write(text)
|
Handle opening text files with different encodings.
|
62599003462c4b4f79dbc4d5
|
class GovernmentAPI(API): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(GovernmentAPI, self).__init__() <NEW_LINE> self.base_url = 'http://usaspending.gov' <NEW_LINE> self.output_format = 'xml' <NEW_LINE> self.required_params = None <NEW_LINE> self.keywords = keywords <NEW_LINE> self._detail_args = detail_args <NEW_LINE> self._sort_by_args = sort_by_args <NEW_LINE> self._re_sort_by = re.compile('sort.+') <NEW_LINE> <DEDENT> def _correct_keywords(self, **kwds): <NEW_LINE> <INDENT> if 'detail' in kwds and kwds['detail'] in self._detail_args: <NEW_LINE> <INDENT> data = kwds.pop('detail') <NEW_LINE> formatted_value = self._detail_args[data] <NEW_LINE> kwds['detail'] = formatted_value <NEW_LINE> <DEDENT> for key in kwds: <NEW_LINE> <INDENT> if self._re_sort_by.match(key): <NEW_LINE> <INDENT> data = kwds.pop(key) <NEW_LINE> formatted_value = self._sort_by_args[data] <NEW_LINE> kwds['sortby'] = formatted_value <NEW_LINE> <DEDENT> elif key in self.keywords: <NEW_LINE> <INDENT> correct_name = self.keywords[key] <NEW_LINE> data = kwds.pop(key) <NEW_LINE> kwds.update({correct_name: data}) <NEW_LINE> <DEDENT> <DEDENT> return kwds
|
Generalized Python wrapper for the USA Spending API. Resolves keyword
replacement and connecting with the API.
|
62599003d164cc6175821a4b
|
class User(ObjCD): <NEW_LINE> <INDENT> def update(self): <NEW_LINE> <INDENT> return self.client.update_user(self) <NEW_LINE> <DEDENT> def create(self): <NEW_LINE> <INDENT> return self.client.update_user(self)
|
Encapsulates an app user
|
6259900315fb5d323ce7f812
|
class Competition(models.Model): <NEW_LINE> <INDENT> competition_id = models.AutoField(primary_key=True) <NEW_LINE> competition_sender_id = models.ForeignKey(User, on_delete=models.CASCADE,) <NEW_LINE> competition_poster = models.ImageField(upload_to='competition_img', verbose_name='大赛海报') <NEW_LINE> competition_title = models.CharField(max_length=50, default="", verbose_name='大赛主题') <NEW_LINE> competition_description = models.CharField(max_length=200, verbose_name='大赛简介') <NEW_LINE> competition_time = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name='发布时间') <NEW_LINE> competition_colletion_times = models.IntegerField(default=0, blank=True, verbose_name='收藏次数')
|
大赛
|
6259900315fb5d323ce7f816
|
class NotAuthorized(BlazarClientException): <NEW_LINE> <INDENT> code = 401 <NEW_LINE> message = _("Not authorized request.")
|
HTTP 401 - Not authorized.
User have no enough rights to perform action.
|
62599003462c4b4f79dbc4db
|
class SynoDSMSecurityBinarySensor(SynologyDSMBaseEntity, BinarySensorEntity): <NEW_LINE> <INDENT> @property <NEW_LINE> def is_on(self) -> bool: <NEW_LINE> <INDENT> return getattr(self._api.security, self.entity_type) != "safe" <NEW_LINE> <DEDENT> @property <NEW_LINE> def available(self) -> bool: <NEW_LINE> <INDENT> return bool(self._api.security) <NEW_LINE> <DEDENT> @property <NEW_LINE> def extra_state_attributes(self) -> dict[str, str]: <NEW_LINE> <INDENT> return self._api.security.status_by_check
|
Representation a Synology Security binary sensor.
|
62599003627d3e7fe0e07974
|
class ResourceNotFoundError(Exception): <NEW_LINE> <INDENT> pass
|
Raised when a resoruce is not found in the application
|
625990030a366e3fb87dd4c9
|
class LocationMixin(XBlock): <NEW_LINE> <INDENT> @property <NEW_LINE> def block_id(self): <NEW_LINE> <INDENT> if hasattr(self, 'location'): <NEW_LINE> <INDENT> return self.location.block_id <NEW_LINE> <DEDENT> return 'block_id' <NEW_LINE> <DEDENT> @property <NEW_LINE> def course_key(self): <NEW_LINE> <INDENT> if hasattr(self, 'location'): <NEW_LINE> <INDENT> return self.location.course_key <NEW_LINE> <DEDENT> return 'course_key' <NEW_LINE> <DEDENT> @property <NEW_LINE> def usage_id(self): <NEW_LINE> <INDENT> if hasattr(self, 'location'): <NEW_LINE> <INDENT> return str(self.location) <NEW_LINE> <DEDENT> return 'usage_id'
|
Provides utility methods to access XBlock's `location`.
Some runtimes, e.g. workbench, don't provide location, hence stubs.
|
625990033cc13d1c6d466220
|
class RegexHandler(object): <NEW_LINE> <INDENT> def __init__(self, pat): <NEW_LINE> <INDENT> self.debugInfo = pat <NEW_LINE> self.pat = re.compile(pat) <NEW_LINE> <DEDENT> def handle(self, parent, css, attr): <NEW_LINE> <INDENT> value = "" <NEW_LINE> try: <NEW_LINE> <INDENT> value = Extractor.getValue(parent, css, attr) <NEW_LINE> m = self.pat.search(value) <NEW_LINE> value = m.group(1).strip() <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> logException( "regex-error:value=%s css=%s attr=%s pat=%s" % (value, css, attr, self.debugInfo)) <NEW_LINE> <DEDENT> return value
|
对CSS Selector处理后的数据进行正则处理
|
62599003627d3e7fe0e07976
|
class WebserverProcess(testprocess.Process): <NEW_LINE> <INDENT> new_request = pyqtSignal(Request) <NEW_LINE> Request = Request <NEW_LINE> ExpectedRequest = ExpectedRequest <NEW_LINE> KEYS = ['verb', 'path'] <NEW_LINE> def __init__(self, request, script, parent=None): <NEW_LINE> <INDENT> super().__init__(request, parent) <NEW_LINE> self._script = script <NEW_LINE> self.port = self._random_port() <NEW_LINE> self.new_data.connect(self.new_request) <NEW_LINE> <DEDENT> def _random_port(self) -> int: <NEW_LINE> <INDENT> sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) <NEW_LINE> sock.bind(('localhost', 0)) <NEW_LINE> port = sock.getsockname()[1] <NEW_LINE> sock.close() <NEW_LINE> return port <NEW_LINE> <DEDENT> def get_requests(self): <NEW_LINE> <INDENT> requests = self._get_data() <NEW_LINE> return [r for r in requests if r.path != '/favicon.ico'] <NEW_LINE> <DEDENT> def _parse_line(self, line): <NEW_LINE> <INDENT> self._log(line) <NEW_LINE> started_re = re.compile(r' \* Running on https?://127\.0\.0\.1:{}/? ' r'\(Press CTRL\+C to quit\)'.format(self.port)) <NEW_LINE> if started_re.fullmatch(line): <NEW_LINE> <INDENT> self.ready.emit() <NEW_LINE> return None <NEW_LINE> <DEDENT> return Request(line) <NEW_LINE> <DEDENT> def _executable_args(self): <NEW_LINE> <INDENT> if hasattr(sys, 'frozen'): <NEW_LINE> <INDENT> executable = str(pathlib.Path(sys.executable).parent / self._script) <NEW_LINE> args = [] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> executable = sys.executable <NEW_LINE> py_file = (pathlib.Path(__file__).parent / self._script).with_suffix('.py') <NEW_LINE> args = [str(py_file)] <NEW_LINE> <DEDENT> return executable, args <NEW_LINE> <DEDENT> def _default_args(self): <NEW_LINE> <INDENT> return [str(self.port)]
|
Abstraction over a running Flask server process.
Reads the log from its stdout and parses it.
Signals:
new_request: Emitted when there's a new request received.
|
6259900315fb5d323ce7f81c
|
class SimConfig(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=128, unique=True) <NEW_LINE> datafile = models.FilePathField(path='spyke/data/simulations/') <NEW_LINE> created = models.DateTimeField(auto_now_add=True) <NEW_LINE> edited = models.DateTimeField(auto_now=True) <NEW_LINE> def set_datafile(self): <NEW_LINE> <INDENT> self.datafile = os.path.join(SIMULATION_DIR, self.name + '.json') <NEW_LINE> <DEDENT> def save_config(self, config): <NEW_LINE> <INDENT> with open(self.datafile, 'w') as f: <NEW_LINE> <INDENT> json.dump(config, f) <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> def load_config(self): <NEW_LINE> <INDENT> with open(self.datafile) as f: <NEW_LINE> <INDENT> data = json.load(f) <NEW_LINE> <DEDENT> return data
|
Save simulation config as JSON
|
625990030a366e3fb87dd4cf
|
class Wall(NonActor): <NEW_LINE> <INDENT> mark = 'W' <NEW_LINE> type_name = 'Wall' <NEW_LINE> obstacle = True <NEW_LINE> max_hp = 5 <NEW_LINE> def attack_result(self, damage): <NEW_LINE> <INDENT> return EventResult(damage, -1, 1, 1)
|
Designed to be impassable obstacle, at least as,long as actor can not break it.
|
625990030a366e3fb87dd4d1
|
class UserTreeDataView(APIView): <NEW_LINE> <INDENT> authentication_classes = (TokenAuthentication, ) <NEW_LINE> def post(self, request): <NEW_LINE> <INDENT> tree_id = request.data.get('id', '1-1') <NEW_LINE> if str(tree_id).strip() == "": <NEW_LINE> <INDENT> tree_id = '1-1' <NEW_LINE> <DEDENT> person_flag = request.data.get('withPerson', False) <NEW_LINE> ret = func_tree_data(tree_id, person_flag) <NEW_LINE> return Response(ret)
|
获取组织树数据
|
62599003d164cc6175821a5e
|
class _PresubmitResult(object): <NEW_LINE> <INDENT> fatal = False <NEW_LINE> should_prompt = False <NEW_LINE> def __init__(self, message): <NEW_LINE> <INDENT> self._message = message <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.fatal == other.fatal and self.should_prompt == other.should_prompt and self._message == other._message
|
Base class for result objects.
|
625990040a366e3fb87dd4d9
|
class Singleton(object): <NEW_LINE> <INDENT> def __init__(self, decorated): <NEW_LINE> <INDENT> self._decorated = decorated <NEW_LINE> <DEDENT> def Instance(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self._instance <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> self._instance = self._decorated() <NEW_LINE> return self._instance <NEW_LINE> <DEDENT> <DEDENT> def __call__(self): <NEW_LINE> <INDENT> raise TypeError( 'Singletons must be accessed through the "Instance" method.')
|
A non-thread-safe helper class to ease implementing singletons.
This should be used as a decorator -- not a metaclass -- to the
class that should be a singleton.
The decorated class can define one __init__ function that
takes only the "self" argument. Other than that, there are
no restrictions that apply to the decorated class.
To get the singleton instance, use the "Instance" method. Trying
to use __call__ will result in a "TypeError" being raised.
Limitations: The decorated class cannot be inherited from and the
type of the singleton instance cannot be checked with "isinstance".
|
6259900415fb5d323ce7f82d
|
class FriendGroupManager(SingleDeleteManager): <NEW_LINE> <INDENT> def for_user(self, user): <NEW_LINE> <INDENT> return self.filter(user=user)
|
Manager des groupes d'amis
|
6259900415fb5d323ce7f82f
|
class DeDupDatabase: <NEW_LINE> <INDENT> def __init__(self, create = True): <NEW_LINE> <INDENT> self.connection = sqlite3.connect("dedup.db") <NEW_LINE> self.connection.isolation_level = None <NEW_LINE> self.cursor = self.connection.cursor() <NEW_LINE> self.resetStatement = "DROP TABLE if exists dups" <NEW_LINE> self.createStatement = "CREATE TABLE dups (filespec VARCHAR(1024), pathspec VARCHAR(2048), md5 VARCHAR(1000))" <NEW_LINE> self.insertStatement = "insert into dups (filespec, pathspec, md5) VALUES (?, ?, ?)" <NEW_LINE> self.getStatement = "select pathspec, filespec from dups where md5 = '{0}'" <NEW_LINE> self.getHashGroupsQuery = "select md5 from dups group by md5 having count(*) > 1" <NEW_LINE> if create: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.cursor.execute(self.resetStatement) <NEW_LINE> self.cursor.execute(self.createStatement) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def insert(self, path: str, file: str, md5: str): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.cursor.execute(self.insertStatement, (path, file, md5)) <NEW_LINE> <DEDENT> except Exception as ex: <NEW_LINE> <INDENT> print(str(ex)) <NEW_LINE> print(path, file, md5) <NEW_LINE> <DEDENT> <DEDENT> def getHashGroups(self): <NEW_LINE> <INDENT> self.cursor.execute(self.getHashGroupsQuery) <NEW_LINE> return self.cursor.fetchall() <NEW_LINE> <DEDENT> def getByHash(self, hash: str): <NEW_LINE> <INDENT> self.cursor.execute(self.getStatement.format(hash)) <NEW_LINE> return self.cursor.fetchall()
|
This class provides the dedup database and makes getting data into it easy.
|
62599004462c4b4f79dbc4f4
|
class _CustomSTE(Function): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def forward(ctx, input_forward: torch.Tensor, input_backward: torch.Tensor) -> torch.Tensor: <NEW_LINE> <INDENT> ctx.shape = input_backward.shape <NEW_LINE> return input_forward <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def backward(ctx, grad_in: torch.Tensor) -> tuple[None, torch.Tensor]: <NEW_LINE> <INDENT> return None, grad_in.sum_to_size(ctx.shape)
|
An efficient alternatives for
>>> input_forward.requires_grad is False
>>> input_backward.requires_grad is True
>>> input_forward + (input_backward - input_backward.detach())
|
625990043cc13d1c6d466238
|
class matrix(convolution): <NEW_LINE> <INDENT> def __init__(self, convolution_array, vectorize): <NEW_LINE> <INDENT> super(matrix, self).__init__(vectorize) <NEW_LINE> self.__convolution_array__ = convolution_array <NEW_LINE> <DEDENT> def convolve( self, image ) : <NEW_LINE> <INDENT> fun = getattr(kernels, self.fun(image)) <NEW_LINE> return type(image)(from_array=fun(image.pixels, self.__convolution_array__))
|
Convolution generale avec une taille de stencil quelconque. Permet de definir tous les stencils que l'on souhaite !
|
625990040a366e3fb87dd4e3
|
class Cisco(SwitchCommon): <NEW_LINE> <INDENT> def __init__(self, host=None, userid=None, password=None, mode=None, outfile=None): <NEW_LINE> <INDENT> self.mode = mode <NEW_LINE> self.host = host <NEW_LINE> if self.mode == 'active': <NEW_LINE> <INDENT> self.userid = userid <NEW_LINE> self.password = password <NEW_LINE> <DEDENT> elif self.mode == 'passive': <NEW_LINE> <INDENT> if os.path.isdir(GEN_PASSIVE_PATH): <NEW_LINE> <INDENT> self.outfile = GEN_PASSIVE_PATH + '/' + outfile <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.outfile = GEN_PATH + '/' + outfile <NEW_LINE> <DEDENT> f = open(self.outfile, 'a+') <NEW_LINE> f.write(str(datetime.datetime.now()) + '\n') <NEW_LINE> f.close() <NEW_LINE> <DEDENT> super(Cisco, self).__init__(host, userid, password, mode, outfile)
|
Class for configuring and retrieving information for a Cisco
Nexus switches running NX-OS. This class developed on Cisco 5020.
Cisco IOS switches may work or may need some methods overridden.
This class can be instantiated in 'active' mode, in which case the
switch will be configured or in 'passive' mode in which case the
commands needed to configure the switch are written to a file.
When in passive mode, information requests will return 'None'.
In passive mode, a filename can be generated which
will contain the active mode switch commands used for switch
configuration. This outfile will be written to the
'power-up/passive' directory if it exists or to the
'power-up' directory if the passive directory does not
exist. If no outfile name is provided a default name is used.
In active mode, the 'host, userid and password named variables
are required. If 'mode' is not provided, it is defaulted to 'passive'.
Args:
host (string): Management switch management interface IP address
or hostname or if in passive mode, a fully qualified filename of the
acquired mac address table for the switch.
userid (string): Switch management interface login user ID.
password (string): Switch management interface login password.
mode (string): Set to 'passive' to run in passive switch mode.
Defaults to 'active'
outfile (string): Name of file to direct switch output to when
in passive mode.
|
6259900415fb5d323ce7f835
|
class ImageMismatchError(BaseError): <NEW_LINE> <INDENT> pass
|
Raises error when pulled image is different from expected image
|
625990043cc13d1c6d46623c
|
class UUID(object): <NEW_LINE> <INDENT> def __init__(self, string = '00000000-0000-0000-0000-000000000000', bytes = None, offset = 0): <NEW_LINE> <INDENT> if bytes != None: <NEW_LINE> <INDENT> self.unpack_from_bytes(bytes, offset) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.uuid = uuid.UUID(string) <NEW_LINE> <DEDENT> <DEDENT> def random(self): <NEW_LINE> <INDENT> if str(self.uuid) == '00000000-0000-0000-0000-000000000000': <NEW_LINE> <INDENT> self.uuid = uuid.uuid4() <NEW_LINE> return self.uuid <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logger.warning("Attempted to overwrite a stored uuid %s with a random, that is a bad idea..." % (str(self.uuid))) <NEW_LINE> <DEDENT> <DEDENT> def unpack_from_bytes(self, bytes, offset): <NEW_LINE> <INDENT> self.uuid = uuid.UUID(bytes = bytes[offset:offset+16]) <NEW_LINE> <DEDENT> def get_bytes(self): <NEW_LINE> <INDENT> return str(self.uuid.bytes) <NEW_LINE> <DEDENT> def data(self): <NEW_LINE> <INDENT> return self.uuid <NEW_LINE> <DEDENT> def copy(self): <NEW_LINE> <INDENT> return UUID(string=str(self.uuid)) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return str(self.uuid) <NEW_LINE> <DEDENT> def __call__(self): <NEW_LINE> <INDENT> return self.uuid <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if hasattr(other,'uuid'): <NEW_LINE> <INDENT> return self.uuid == other.uuid <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def __xor__(self, arg): <NEW_LINE> <INDENT> temp = self.uuid.int ^ arg.uuid.int <NEW_LINE> result = uuid.UUID(int = temp) <NEW_LINE> return UUID(result.__str__())
|
represents a uuid as, well, a uuid
inbound LLUUID data from packets is already UUID(), they are
already the same 'datatype'
|
6259900415fb5d323ce7f83b
|
class DatModelShared(QAbstractTableModel): <NEW_LINE> <INDENT> def __init__(self, dat_file, *args, **kwargs): <NEW_LINE> <INDENT> QAbstractTableModel.__init__(self, *args, **kwargs) <NEW_LINE> if not isinstance(dat_file, DatFile): <NEW_LINE> <INDENT> raise TypeError('datfile must be a DatFile instance') <NEW_LINE> <DEDENT> self._dat_file = dat_file
|
TODO: master should be a DatFrame... but circular dependencies
|
62599004627d3e7fe0e0799a
|
class InputWidget(QtWidgets.QWidget): <NEW_LINE> <INDENT> def __init__(self, specification, scales, parent=None): <NEW_LINE> <INDENT> super().__init__(parent) <NEW_LINE> self.specification = specification <NEW_LINE> self.scales = scales <NEW_LINE> <DEDENT> def loadCut(self, cut): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def updateCut(self, cut): <NEW_LINE> <INDENT> raise NotImplementedError()
|
Abstract input widget.
>>> widget.loadCut(cut)
>>> widget.updateCut(cut)
|
625990043cc13d1c6d466246
|
class Connection(MongoClient): <NEW_LINE> <INDENT> def __init__(self, host=None, port=None, max_pool_size=10, network_timeout=None, document_class=dict, tz_aware=False, _connect=True, **kwargs): <NEW_LINE> <INDENT> if network_timeout is not None: <NEW_LINE> <INDENT> if (not isinstance(network_timeout, (int, float)) or network_timeout <= 0): <NEW_LINE> <INDENT> raise ConfigurationError("network_timeout must " "be a positive integer") <NEW_LINE> <DEDENT> kwargs['socketTimeoutMS'] = network_timeout * 1000 <NEW_LINE> <DEDENT> kwargs['auto_start_request'] = kwargs.get('auto_start_request', True) <NEW_LINE> kwargs['safe'] = kwargs.get('safe', False) <NEW_LINE> super(Connection, self).__init__(host, port, max_pool_size, document_class, tz_aware, _connect, **kwargs) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> if len(self.nodes) == 1: <NEW_LINE> <INDENT> return "Connection(%r, %r)" % (self.host, self.port) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "Connection(%r)" % ["%s:%d" % n for n in self.nodes] <NEW_LINE> <DEDENT> <DEDENT> def next(self): <NEW_LINE> <INDENT> raise TypeError("'Connection' object is not iterable")
|
Connection to MongoDB.
|
62599004bf627c535bcb1fb1
|
class Factor(object): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(Factor, self).__init__(*args, **kwargs) <NEW_LINE> <DEDENT> @property <NEW_LINE> def logp(self): <NEW_LINE> <INDENT> return self.model.fn(self.logpt) <NEW_LINE> <DEDENT> @property <NEW_LINE> def logp_elemwise(self): <NEW_LINE> <INDENT> return self.model.fn(self.logp_elemwiset) <NEW_LINE> <DEDENT> def dlogp(self, vars=None): <NEW_LINE> <INDENT> return self.model.fn(gradient(self.logpt, vars)) <NEW_LINE> <DEDENT> def d2logp(self, vars=None): <NEW_LINE> <INDENT> return self.model.fn(hessian(self.logpt, vars)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def logp_nojac(self): <NEW_LINE> <INDENT> return self.model.fn(self.logp_nojact) <NEW_LINE> <DEDENT> def dlogp_nojac(self, vars=None): <NEW_LINE> <INDENT> return self.model.fn(gradient(self.logp_nojact, vars)) <NEW_LINE> <DEDENT> def d2logp_nojac(self, vars=None): <NEW_LINE> <INDENT> return self.model.fn(hessian(self.logp_nojact, vars)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def fastlogp(self): <NEW_LINE> <INDENT> return self.model.fastfn(self.logpt) <NEW_LINE> <DEDENT> def fastdlogp(self, vars=None): <NEW_LINE> <INDENT> return self.model.fastfn(gradient(self.logpt, vars)) <NEW_LINE> <DEDENT> def fastd2logp(self, vars=None): <NEW_LINE> <INDENT> return self.model.fastfn(hessian(self.logpt, vars)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def fastlogp_nojac(self): <NEW_LINE> <INDENT> return self.model.fastfn(self.logp_nojact) <NEW_LINE> <DEDENT> def fastdlogp_nojac(self, vars=None): <NEW_LINE> <INDENT> return self.model.fastfn(gradient(self.logp_nojact, vars)) <NEW_LINE> <DEDENT> def fastd2logp_nojac(self, vars=None): <NEW_LINE> <INDENT> return self.model.fastfn(hessian(self.logp_nojact, vars)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def logpt(self): <NEW_LINE> <INDENT> if getattr(self, 'total_size', None) is not None: <NEW_LINE> <INDENT> logp = self.logp_sum_unscaledt * self.scaling <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logp = self.logp_sum_unscaledt <NEW_LINE> <DEDENT> if self.name is not None: <NEW_LINE> <INDENT> logp.name = '__logp_%s' % self.name <NEW_LINE> <DEDENT> return logp <NEW_LINE> <DEDENT> @property <NEW_LINE> def logp_nojact(self): <NEW_LINE> <INDENT> if getattr(self, 'total_size', None) is not None: <NEW_LINE> <INDENT> logp = tt.sum(self.logp_nojac_unscaledt) * self.scaling <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logp = tt.sum(self.logp_nojac_unscaledt) <NEW_LINE> <DEDENT> if self.name is not None: <NEW_LINE> <INDENT> logp.name = '__logp_%s' % self.name <NEW_LINE> <DEDENT> return logp
|
Common functionality for objects with a log probability density
associated with them.
|
625990050a366e3fb87dd4f7
|
class pairDouble(object): <NEW_LINE> <INDENT> thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> def __init__(self, *args): <NEW_LINE> <INDENT> _piranha.pairDouble_swiginit(self, _piranha.new_pairDouble(*args)) <NEW_LINE> <DEDENT> first = property(_piranha.pairDouble_first_get, _piranha.pairDouble_first_set, doc=r"""first : double""") <NEW_LINE> second = property(_piranha.pairDouble_second_get, _piranha.pairDouble_second_set, doc=r"""second : double""") <NEW_LINE> def __len__(self): <NEW_LINE> <INDENT> return 2 <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return str((self.first, self.second)) <NEW_LINE> <DEDENT> def __getitem__(self, index): <NEW_LINE> <INDENT> if not (index % 2): <NEW_LINE> <INDENT> return self.first <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.second <NEW_LINE> <DEDENT> <DEDENT> def __setitem__(self, index, val): <NEW_LINE> <INDENT> if not (index % 2): <NEW_LINE> <INDENT> self.first = val <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.second = val <NEW_LINE> <DEDENT> <DEDENT> __swig_destroy__ = _piranha.delete_pairDouble
|
Proxy of C++ std::pair< double,double > class.
|
62599005462c4b4f79dbc50e
|
class QGridLeaf(RhythmTreeMixin, TreeNode): <NEW_LINE> <INDENT> __slots__ = ( '_duration', '_is_divisible', '_offset', '_offsets_are_current', '_q_event_proxies', ) <NEW_LINE> def __init__( self, preprolated_duration=1, q_event_proxies=None, is_divisible=True): <NEW_LINE> <INDENT> from abjad.tools import quantizationtools <NEW_LINE> TreeNode.__init__(self) <NEW_LINE> RhythmTreeMixin.__init__(self, preprolated_duration) <NEW_LINE> if q_event_proxies is None: <NEW_LINE> <INDENT> self._q_event_proxies = [] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert all(isinstance(x, quantizationtools.QEventProxy) for x in q_event_proxies) <NEW_LINE> self._q_event_proxies = list(q_event_proxies) <NEW_LINE> <DEDENT> self._is_divisible = bool(is_divisible) <NEW_LINE> <DEDENT> def __call__(self, pulse_duration): <NEW_LINE> <INDENT> pulse_duration = durationtools.Duration(pulse_duration) <NEW_LINE> total_duration = pulse_duration * self.preprolated_duration <NEW_LINE> return scoretools.make_notes(0, total_duration) <NEW_LINE> <DEDENT> def __graph__(self, **kwargs): <NEW_LINE> <INDENT> from abjad.tools import documentationtools <NEW_LINE> graph = documentationtools.GraphvizGraph(name='G') <NEW_LINE> node = documentationtools.GraphvizNode( attributes={ 'label': str(self.preprolated_duration), 'shape': 'box' } ) <NEW_LINE> graph.append(node) <NEW_LINE> return graph <NEW_LINE> <DEDENT> @property <NEW_LINE> def _pretty_rtm_format_pieces(self): <NEW_LINE> <INDENT> return [str(self.preprolated_duration)] <NEW_LINE> <DEDENT> @property <NEW_LINE> def _storage_format_specification(self): <NEW_LINE> <INDENT> from abjad.tools import systemtools <NEW_LINE> return systemtools.StorageFormatSpecification( self, keywords_ignored_when_false=( 'q_event_proxies', ), ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_divisible(self): <NEW_LINE> <INDENT> return self._is_divisible <NEW_LINE> <DEDENT> @is_divisible.setter <NEW_LINE> def is_divisible(self, arg): <NEW_LINE> <INDENT> self._is_divisible = bool(arg) <NEW_LINE> <DEDENT> @property <NEW_LINE> def preceding_q_event_proxies(self): <NEW_LINE> <INDENT> return [x for x in self._q_event_proxies if x.offset < self.start_offset] <NEW_LINE> <DEDENT> @property <NEW_LINE> def q_event_proxies(self): <NEW_LINE> <INDENT> return self._q_event_proxies <NEW_LINE> <DEDENT> @property <NEW_LINE> def rtm_format(self): <NEW_LINE> <INDENT> return str(self.preprolated_duration) <NEW_LINE> <DEDENT> @property <NEW_LINE> def succeeding_q_event_proxies(self): <NEW_LINE> <INDENT> return [x for x in self._q_event_proxies if self.start_offset <= x.offset]
|
A leaf in a ``QGrid`` structure.
::
>>> leaf = quantizationtools.QGridLeaf()
::
>>> leaf
QGridLeaf(
preprolated_duration=Duration(1, 1),
is_divisible=True
)
Used internally by ``QGrid``.
|
6259900515fb5d323ce7f84a
|
class Addressable(object): <NEW_LINE> <INDENT> def discoReceived(self, user, what, node=None): <NEW_LINE> <INDENT> if 'info' == what: <NEW_LINE> <INDENT> ids = [{'category': 'hierarchy', 'type': 'leaf'}] <NEW_LINE> return {'ids': ids, 'features': [NS_DISCO_INFO]} <NEW_LINE> <DEDENT> <DEDENT> def iqReceived(self, cnx, iq): <NEW_LINE> <INDENT> typ = iq.getType() <NEW_LINE> ns = iq.getQueryNS() <NEW_LINE> if (NS_VERSION == ns) and ('get' == typ): <NEW_LINE> <INDENT> name = Node('name') <NEW_LINE> name.setData(LIB_NAME) <NEW_LINE> version = Node('version') <NEW_LINE> version.setData(LIB_VERSION) <NEW_LINE> reply = iq.buildReply('result') <NEW_LINE> query = reply.getQuery() <NEW_LINE> query.addChild(node=name) <NEW_LINE> query.addChild(node=version) <NEW_LINE> cnx.send(reply) <NEW_LINE> raise NodeProcessed <NEW_LINE> <DEDENT> elif (NS_LAST == ns) and ('get' == typ): <NEW_LINE> <INDENT> if self.last is not None: <NEW_LINE> <INDENT> reply = iq.buildReply('result') <NEW_LINE> query = reply.getQuery() <NEW_LINE> query.setAttr('seconds', (datetime.now() - self.last).seconds) <NEW_LINE> cnx.send(reply) <NEW_LINE> raise NodeProcessed <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> debug("Unhandled IQ namespace '%s'." % ns)
|
An addressable object
|
62599005bf627c535bcb1fb8
|
class HDF5DatasetSliceHandler(_HDF5HandlerBase): <NEW_LINE> <INDENT> def __init__(self, filename, key, frame_per_point=1): <NEW_LINE> <INDENT> self._fpp = frame_per_point <NEW_LINE> self._filename = filename <NEW_LINE> self._key = key <NEW_LINE> self._file = None <NEW_LINE> self._dataset = None <NEW_LINE> self.open() <NEW_LINE> <DEDENT> def __call__(self, point_number): <NEW_LINE> <INDENT> if not self._dataset: <NEW_LINE> <INDENT> self._dataset = self._file[self._key] <NEW_LINE> <DEDENT> start, stop = point_number * self._fpp, (point_number + 1) * self._fpp <NEW_LINE> return self._dataset[start:stop].squeeze()
|
Handler for data stored in one Dataset of an HDF5 file.
Parameters
----------
filename : string
path to HDF5 file
key : string
key of the single HDF5 Dataset used by this Handler
frame_per_point : integer, optional
number of frames to return as one datum, default 1
|
62599005627d3e7fe0e079aa
|
class QLearn: <NEW_LINE> <INDENT> def __init__(self, action_space, alpha=0.1, gamma=0.9, epsilon=0.1): <NEW_LINE> <INDENT> self.q = {} <NEW_LINE> self.alpha = alpha <NEW_LINE> self.gamma = gamma <NEW_LINE> self.actions = action_space <NEW_LINE> self.epsilon = epsilon <NEW_LINE> <DEDENT> def get_utility(self, state, action): <NEW_LINE> <INDENT> return self.q.get((state, action), 0.0) <NEW_LINE> <DEDENT> def choose_action(self, state): <NEW_LINE> <INDENT> if random.random() < self.epsilon: <NEW_LINE> <INDENT> action = random.choice(self.actions) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> q = [self.get_utility(state, act) for act in self.actions] <NEW_LINE> max_utility = max(q) <NEW_LINE> if q.count(max_utility) > 1: <NEW_LINE> <INDENT> best_actions = [self.actions[i] for i in range(len(self.actions)) if q[i] == max_utility] <NEW_LINE> action = random.choice(best_actions) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> action = self.actions[q.index(max_utility)] <NEW_LINE> <DEDENT> <DEDENT> return action <NEW_LINE> <DEDENT> def learn(self, state1, action, state2, reward): <NEW_LINE> <INDENT> old_utility = self.q.get((state1, action), None) <NEW_LINE> if old_utility is None: <NEW_LINE> <INDENT> self.q[(state1, action)] = reward <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> next_max_utility = max([self.get_utility(state2, a) for a in self.actions]) <NEW_LINE> self.q[(state1, action)] = old_utility + self.alpha * (reward + self.gamma * next_max_utility - old_utility)
|
Q-learning:
Q(s, a) += alpha * (reward(s,a) + gamma * max(Q(s', a') - Q(s,a))
* alpha is the learning rate.
* gamma is the value of the future reward.
It use the best next choice of utility in later state to update the former state.
|
6259900515fb5d323ce7f851
|
class Alien(Sprite): <NEW_LINE> <INDENT> def __init__(self, ai_settings, screen): <NEW_LINE> <INDENT> super(Alien, self).__init__() <NEW_LINE> self.screen = screen <NEW_LINE> self.ai_settings = ai_settings <NEW_LINE> self.image = pygame.image.load('example_5/images/alien.bmp') <NEW_LINE> self.rect = self.image.get_rect() <NEW_LINE> self.rect.x = self.rect.width <NEW_LINE> self.rect.y = self.rect.height <NEW_LINE> self.x = float(self.rect.x) <NEW_LINE> <DEDENT> def check_edges(self): <NEW_LINE> <INDENT> screen_rect = self.screen.get_rect() <NEW_LINE> if self.rect.right >= screen_rect.right: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif self.rect.left <= 0: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.x += self.ai_settings.alien_speed_factor * self.ai_settings.fleet_direction <NEW_LINE> self.rect.x = self.x <NEW_LINE> <DEDENT> def blitme(self): <NEW_LINE> <INDENT> self.screen.blit(self.image, self.rect)
|
外星人基本设置
|
625990053cc13d1c6d46625d
|
class SignatureEnvelopeDocumentResponse: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.swaggerTypes = { 'result': 'SignatureEnvelopeDocumentResult', 'status': 'str', 'error_message': 'str', 'composedOn': 'long' } <NEW_LINE> self.result = None <NEW_LINE> self.status = None <NEW_LINE> self.error_message = None <NEW_LINE> self.composedOn = None
|
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
|
62599005d164cc6175821a8f
|
class vector_insert_s(object): <NEW_LINE> <INDENT> thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined - class is abstract") <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> def make(*args, **kwargs): <NEW_LINE> <INDENT> return _blocks_swig1.vector_insert_s_make(*args, **kwargs) <NEW_LINE> <DEDENT> make = staticmethod(make) <NEW_LINE> def rewind(self): <NEW_LINE> <INDENT> return _blocks_swig1.vector_insert_s_rewind(self) <NEW_LINE> <DEDENT> def set_data(self, *args, **kwargs): <NEW_LINE> <INDENT> return _blocks_swig1.vector_insert_s_set_data(self, *args, **kwargs) <NEW_LINE> <DEDENT> __swig_destroy__ = _blocks_swig1.delete_vector_insert_s <NEW_LINE> __del__ = lambda self : None;
|
source of short's that gets its data from a vector
Constructor Specific Documentation:
Make vector insert block.
Args:
data : vector of data to insert
periodicity : number of samples between when to send
offset : initial item offset of first insert
|
625990050a366e3fb87dd507
|
class Movie(): <NEW_LINE> <INDENT> VALID_RATINGS = ["G", "PG", "PG-13", "R"] <NEW_LINE> def __init__(self, movie_title, movie_storyline, poster_image,trailer_youtube): <NEW_LINE> <INDENT> self.title = movie_title <NEW_LINE> self.storyline = movie_storyline <NEW_LINE> self.poster_image_url = poster_image <NEW_LINE> self.trailer_youtube_url = trailer_youtube <NEW_LINE> <DEDENT> def show_trailer(self): <NEW_LINE> <INDENT> webbrowser.open(self.trailer_youtube_url)
|
This class provides a way to store movie realted information
|
62599005462c4b4f79dbc51c
|
class ButtonBar(QToolBar): <NEW_LINE> <INDENT> def __init__(self, parent): <NEW_LINE> <INDENT> super().__init__(parent) <NEW_LINE> self.slots = {} <NEW_LINE> self.setMovable(False) <NEW_LINE> self.setIconSize(QSize(64, 64)) <NEW_LINE> self.setToolButtonStyle(3) <NEW_LINE> self.setContextMenuPolicy(Qt.PreventContextMenu) <NEW_LINE> self.setObjectName("StandardToolBar") <NEW_LINE> self.addAction(name="new", tool_text="Create a new MicroPython script.") <NEW_LINE> self.addAction(name="load", tool_text="Load a MicroPython script.") <NEW_LINE> self.addAction(name="save", tool_text="Save the current MicroPython script.") <NEW_LINE> self.addSeparator() <NEW_LINE> self.addAction(name="flash", tool_text="Flash your code onto the micro:bit.") <NEW_LINE> self.addAction(name="files", tool_text="Access the file system on the micro:bit.") <NEW_LINE> self.addAction(name="repl", tool_text="Use the REPL to live code the micro:bit.") <NEW_LINE> self.addSeparator() <NEW_LINE> self.addAction(name="zoom-in", tool_text="Zoom in (to make the text bigger).") <NEW_LINE> self.addAction(name="zoom-out", tool_text="Zoom out (to make the text smaller).") <NEW_LINE> self.addAction(name="theme", tool_text="Change theme between day or night.") <NEW_LINE> self.addSeparator() <NEW_LINE> self.addAction(name="check", tool_text="Check your code for mistakes.") <NEW_LINE> self.addAction(name="help", tool_text="Show help about Mu in a browser.") <NEW_LINE> self.addAction(name="quit", tool_text="Quit Mu.") <NEW_LINE> <DEDENT> def addAction(self, name, tool_text): <NEW_LINE> <INDENT> action = QAction(load_icon(name), name.capitalize(), self, toolTip=tool_text) <NEW_LINE> super().addAction(action) <NEW_LINE> self.slots[name] = action <NEW_LINE> <DEDENT> def connect(self, name, handler, *shortcuts): <NEW_LINE> <INDENT> self.slots[name].pyqtConfigure(triggered=handler) <NEW_LINE> for shortcut in shortcuts: <NEW_LINE> <INDENT> QShortcut(QKeySequence(shortcut), self.parentWidget()).activated.connect(handler)
|
Represents the bar of buttons across the top of the editor and defines
their behaviour.
|
62599005bf627c535bcb1fc3
|
class MyStatusBar(wx.StatusBar): <NEW_LINE> <INDENT> def __init__(self, parent): <NEW_LINE> <INDENT> super(MyStatusBar, self).__init__(parent, 1) <NEW_LINE> self.SetFieldsCount(1) <NEW_LINE> self.text_box = wx.StaticText(self, -1, ' hello') <NEW_LINE> if platform == 'win32': <NEW_LINE> <INDENT> field_rect = self.GetFieldRect(0) <NEW_LINE> field_rect.y += 3 <NEW_LINE> self.text_box.SetRect(field_rect) <NEW_LINE> <DEDENT> <DEDENT> def set_status_text(self, text): <NEW_LINE> <INDENT> self.text_box.SetLabel(text) <NEW_LINE> <DEDENT> def set_background(self, color): <NEW_LINE> <INDENT> self.text_box.SetBackgroundColour(color) <NEW_LINE> <DEDENT> def set_text_color(self, color): <NEW_LINE> <INDENT> self.text_box.SetForegroundColour(color)
|
Class for custom status bar to color background on errors.
|
62599005627d3e7fe0e079b4
|
class RelatedSuggestion(yahoo.search._Search): <NEW_LINE> <INDENT> NAME = "relatedSuggestion" <NEW_LINE> SERVICE = "WebSearchService" <NEW_LINE> _RESULT_FACTORY = yahoo.search.dom.web.RelatedSuggestion <NEW_LINE> def _init_valid_params(self): <NEW_LINE> <INDENT> self._valid_params.update({ "query" : (types.StringTypes, None, None, None, None, True), "results" : (types.IntType, 10, int, lambda x: x > -1 and x < 51, "the range 1 to 50", False), })
|
RelatedSuggestion - perform a Yahoo Web Related Suggestions search
This class implements the Web Search Related Suggestion web service
APIs. The only allowed parameters are:
query - The query to get related searches from
results - The number of results to return (1-50)
output - The format for the output result. If json or php is
requested, the result is not XML parseable, so we
will simply return the "raw" string.
callback - The name of the callback function to wrap around
the JSON data.
Full documentation for this service is available at:
http://developer.yahoo.net/web/V1/relatedSuggestion.html
|
625990050a366e3fb87dd509
|
@implementer(sasl_mechanisms.ISASLMechanism) <NEW_LINE> class DummySASLMechanism(object): <NEW_LINE> <INDENT> challenge = None <NEW_LINE> name = "DUMMY" <NEW_LINE> def __init__(self, initialResponse): <NEW_LINE> <INDENT> self.initialResponse = initialResponse <NEW_LINE> <DEDENT> def getInitialResponse(self): <NEW_LINE> <INDENT> return self.initialResponse <NEW_LINE> <DEDENT> def getResponse(self, challenge): <NEW_LINE> <INDENT> self.challenge = challenge <NEW_LINE> return ""
|
Dummy SASL mechanism.
This just returns the initialResponse passed on creation, stores any
challenges and replies with an empty response.
@ivar challenge: Last received challenge.
@type challenge: C{unicode}.
@ivar initialResponse: Initial response to be returned when requested
via C{getInitialResponse} or C{None}.
@type initialResponse: C{unicode}
|
6259900515fb5d323ce7f85b
|
class PositionalList(_DoublyLinkedBase): <NEW_LINE> <INDENT> class Position: <NEW_LINE> <INDENT> def __init__(self, container, node): <NEW_LINE> <INDENT> self._container = container <NEW_LINE> self._node = node <NEW_LINE> <DEDENT> def element(self): <NEW_LINE> <INDENT> return self._node._element <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return type(other) is type(self) and other._node is self._node <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) <NEW_LINE> <DEDENT> <DEDENT> def _validate(self, p): <NEW_LINE> <INDENT> if not isinstance(p, self.Position): <NEW_LINE> <INDENT> raise TypeError('p must be proper Position type') <NEW_LINE> <DEDENT> if p._container is not self: <NEW_LINE> <INDENT> raise TypeError('p does not belong to this container') <NEW_LINE> <DEDENT> if p._node._next is None: <NEW_LINE> <INDENT> raise ValueError('p is no longer valid') <NEW_LINE> <DEDENT> return p._node <NEW_LINE> <DEDENT> def _make_position(self, node): <NEW_LINE> <INDENT> if node is self._header or node is self._trailer: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.Position(self, node) <NEW_LINE> <DEDENT> <DEDENT> def first(self): <NEW_LINE> <INDENT> return self._make_position(self._header._next) <NEW_LINE> <DEDENT> def last(self): <NEW_LINE> <INDENT> return self._make_position(self._trailer._prev) <NEW_LINE> <DEDENT> def before(self, p): <NEW_LINE> <INDENT> node = self._validate(p) <NEW_LINE> return self._make_position(node._prev) <NEW_LINE> <DEDENT> def after(self, p): <NEW_LINE> <INDENT> node = self._validate(p) <NEW_LINE> return self._make_position(node._next) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> cursor = self.first() <NEW_LINE> while cursor is not None: <NEW_LINE> <INDENT> yield cursor.element() <NEW_LINE> cursor = self.after(cursor) <NEW_LINE> <DEDENT> <DEDENT> def _insert_between(self, element, predecessor, successor): <NEW_LINE> <INDENT> node = super(PositionalList, self)._insert_between(element, predecessor, successor) <NEW_LINE> return self._make_position(node) <NEW_LINE> <DEDENT> def add_first(self, e): <NEW_LINE> <INDENT> return self._insert_between(e, self._header, self._header._next) <NEW_LINE> <DEDENT> def add_last(self, e): <NEW_LINE> <INDENT> return self._insert_between(e, self._trailer._prev, self._trailer) <NEW_LINE> <DEDENT> def add_before(self, p, e): <NEW_LINE> <INDENT> original = self._validate(p) <NEW_LINE> return self._insert_between(e, original._prev, original) <NEW_LINE> <DEDENT> def add_after(self, p, e): <NEW_LINE> <INDENT> original = self._validate(p) <NEW_LINE> return self._insert_between(e, original, original._next) <NEW_LINE> <DEDENT> def delete(self, p): <NEW_LINE> <INDENT> original = self._validate(p) <NEW_LINE> return self._delete_node(original) <NEW_LINE> <DEDENT> def replace(self, p, e): <NEW_LINE> <INDENT> original = self._validate(p) <NEW_LINE> old_value = original._element <NEW_LINE> original._element = e <NEW_LINE> return old_value
|
A sequential container of elements allowing positonal access
|
6259900521a7993f00c66a96
|
class AbstractSubstringGenerator(DefaultNameMixin): <NEW_LINE> <INDENT> def generateSubstring(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def getJsonableObject(self): <NEW_LINE> <INDENT> raise NotImplementedError()
|
Generates a substring, usually for embedding in a background sequence.
|
62599005bf627c535bcb1fc9
|
class QueryGeneralStatResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.GeneralStat = None <NEW_LINE> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> if params.get("GeneralStat") is not None: <NEW_LINE> <INDENT> self.GeneralStat = GeneralStat() <NEW_LINE> self.GeneralStat._deserialize(params.get("GeneralStat")) <NEW_LINE> <DEDENT> self.RequestId = params.get("RequestId")
|
QueryGeneralStat返回参数结构体
|
625990050a366e3fb87dd50f
|
class ProgramRuleBase(Rule): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.init_libs(kwargs) <NEW_LINE> self.init_var(kwargs, 'ldflags') <NEW_LINE> if mswin: <NEW_LINE> <INDENT> targs = process_nodes(kwargs['targets']) <NEW_LINE> for n in range(len(targs)): <NEW_LINE> <INDENT> if not targs[n].lower().endswith('.exe'): <NEW_LINE> <INDENT> targs[n] += '.exe' <NEW_LINE> <DEDENT> <DEDENT> kwargs['targets'] = targs <NEW_LINE> <DEDENT> set_default(kwargs, 'rule', "${%s} ${%s_} ${LDFLAGS_} -o ${TGT} ${SRC} ${LIBS_}" % (kwargs['linker'], kwargs['flagsname'])) <NEW_LINE> Rule.__init__(self, **kwargs)
|
Standard rule for linking mutiple object files and libs into a program.
|
625990050a366e3fb87dd511
|
class SpellTotems(Structure): <NEW_LINE> <INDENT> fields = Skeleton( IDField(), ForeignKey("required_tool_category_1", "TotemCategory"), ForeignKey("required_tool_category_2", "TotemCategory"), ForeignKey("required_tool_1", "Item"), ForeignKey("required_tool_2", "Item"), )
|
SpellTotems.dbc
Split off Spell.dbc in 4.0.0.12232
|
62599005627d3e7fe0e079bc
|
class SuggestTagAdminField(forms.fields.Field): <NEW_LINE> <INDENT> def __init__(self, db_field, *args, **kwargs): <NEW_LINE> <INDENT> self.rel = db_field.rel <NEW_LINE> self.object_category = kwargs.get('category', None) <NEW_LINE> self.widget = SuggestMultipleTagAdminWidget(db_field, **kwargs) <NEW_LINE> super(SuggestTagAdminField, self).__init__(*args, **kwargs) <NEW_LINE> <DEDENT> def clean(self, value): <NEW_LINE> <INDENT> from django.forms.util import ValidationError <NEW_LINE> super(SuggestTagAdminField, self).clean(value) <NEW_LINE> tag_name = value.split(TAG_DELIMITER) <NEW_LINE> tag_name = map(lambda x: x.strip(), tag_name) <NEW_LINE> if not tag_name: <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> tags = [] <NEW_LINE> for t in tag_name: <NEW_LINE> <INDENT> if not t=='': <NEW_LINE> <INDENT> tag, status = Tag.objects.get_or_create(name=t) <NEW_LINE> tags.append(tag) <NEW_LINE> <DEDENT> <DEDENT> return tags
|
uses multitag text field
|
625990053cc13d1c6d46626b
|
class TankUserPermissionsError(Exception): <NEW_LINE> <INDENT> pass
|
Exception to raise if the current user does not have
sufficient permissions to setup a project.
|
62599005462c4b4f79dbc52a
|
class FlotillaUnit(object): <NEW_LINE> <INDENT> def __init__(self, name, unit_file, environment={}, rev_hash=None): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.unit_file = unit_file <NEW_LINE> self.environment = environment or {} <NEW_LINE> self.rev_hash = rev_hash <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return 'Unit: %s' % self.name <NEW_LINE> <DEDENT> @property <NEW_LINE> def unit_hash(self): <NEW_LINE> <INDENT> unit_hash = hashlib.sha256() <NEW_LINE> unit_hash.update(self.name) <NEW_LINE> unit_hash.update(self.unit_file) <NEW_LINE> for env_key, env_value in sorted(self.environment.items()): <NEW_LINE> <INDENT> unit_hash.update(env_key) <NEW_LINE> unit_hash.update(str(env_value)) <NEW_LINE> <DEDENT> return unit_hash.hexdigest() <NEW_LINE> <DEDENT> @property <NEW_LINE> def full_name(self): <NEW_LINE> <INDENT> name, ext = os.path.splitext(self.name) <NEW_LINE> hash = self.rev_hash or self.unit_hash <NEW_LINE> return '%s%s-%s%s' % (UNIT_PREFIX, name, hash, ext)
|
Systemd unit file and configuration (environment variables).
|
625990050a366e3fb87dd515
|
class MVNormal(MVElliptical): <NEW_LINE> <INDENT> __name__ == 'Multivariate Normal Distribution' <NEW_LINE> def rvs(self, size=1): <NEW_LINE> <INDENT> return np.random.multivariate_normal(self.mean, self.sigma, size=size) <NEW_LINE> <DEDENT> def logpdf(self, x): <NEW_LINE> <INDENT> x = np.asarray(x) <NEW_LINE> x_whitened = self.whiten(x - self.mean) <NEW_LINE> SSR = np.sum(x_whitened**2, -1) <NEW_LINE> llf = -SSR <NEW_LINE> llf -= self.nvars * np.log(2. * np.pi) <NEW_LINE> llf -= self.logdetsigma <NEW_LINE> llf *= 0.5 <NEW_LINE> return llf <NEW_LINE> <DEDENT> def cdf(self, x, **kwds): <NEW_LINE> <INDENT> return mvnormcdf(x, self.mean, self.cov, **kwds) <NEW_LINE> <DEDENT> @property <NEW_LINE> def cov(self): <NEW_LINE> <INDENT> return self.sigma <NEW_LINE> <DEDENT> def affine_transformed(self, shift, scale_matrix): <NEW_LINE> <INDENT> B = scale_matrix <NEW_LINE> mean_new = np.dot(B, self.mean) + shift <NEW_LINE> sigma_new = np.dot(np.dot(B, self.sigma), B.T) <NEW_LINE> return MVNormal(mean_new, sigma_new) <NEW_LINE> <DEDENT> def conditional(self, indices, values): <NEW_LINE> <INDENT> keep = np.asarray(indices) <NEW_LINE> given = np.asarray([i for i in range(self.nvars) if not i in keep]) <NEW_LINE> sigmakk = self.sigma[keep[:, None], keep] <NEW_LINE> sigmagg = self.sigma[given[:, None], given] <NEW_LINE> sigmakg = self.sigma[keep[:, None], given] <NEW_LINE> sigmagk = self.sigma[given[:, None], keep] <NEW_LINE> sigma_new = sigmakk - np.dot(sigmakg, np.linalg.solve(sigmagg, sigmagk)) <NEW_LINE> mean_new = self.mean[keep] + np.dot(sigmakg, np.linalg.solve(sigmagg, values-self.mean[given])) <NEW_LINE> return MVNormal(mean_new, sigma_new)
|
Class for Multivariate Normal Distribution
uses Cholesky decomposition of covariance matrix for the transformation
of the data
|
62599005d164cc6175821a9f
|
class PhysicsObject(Particle): <NEW_LINE> <INDENT> def __init__(self, physObj): <NEW_LINE> <INDENT> self.physObj = physObj <NEW_LINE> super(PhysicsObject, self).__init__() <NEW_LINE> <DEDENT> def __copy__(self): <NEW_LINE> <INDENT> physObj = copy.deepcopy( self.physObj ) <NEW_LINE> newone = type(self)(physObj) <NEW_LINE> newone.__dict__.update(self.__dict__) <NEW_LINE> newone.physObj = physObj <NEW_LINE> return newone <NEW_LINE> <DEDENT> def scaleEnergy( self, scale ): <NEW_LINE> <INDENT> p4 = self.physObj.p4() <NEW_LINE> p4 *= scale <NEW_LINE> self.physObj.setP4( p4 ) <NEW_LINE> <DEDENT> def __getattr__(self,name): <NEW_LINE> <INDENT> return getattr(self.physObj, name)
|
Extends the cmg::PhysicsObject functionalities.
|
625990060a366e3fb87dd517
|
class MySQLSHA256PasswordAuthPlugin(BaseAuthPlugin): <NEW_LINE> <INDENT> requires_ssl = True <NEW_LINE> plugin_name = 'sha256_password' <NEW_LINE> def prepare_password(self): <NEW_LINE> <INDENT> if not self._password: <NEW_LINE> <INDENT> return b'\x00' <NEW_LINE> <DEDENT> password = self._password <NEW_LINE> if PY2: <NEW_LINE> <INDENT> if isinstance(password, unicode): <NEW_LINE> <INDENT> password = password.encode('utf8') <NEW_LINE> <DEDENT> <DEDENT> elif isinstance(password, str): <NEW_LINE> <INDENT> password = password.encode('utf8') <NEW_LINE> <DEDENT> return password + b'\x00'
|
Class implementing the MySQL SHA256 authentication plugin
Note that encrypting using RSA is not supported since the Python
Standard Library does not provide this OpenSSL functionality.
|
62599006627d3e7fe0e079c2
|
@python_2_unicode_compatible <NEW_LINE> class ActionItem(models.Model): <NEW_LINE> <INDENT> SEVERITY_WISHLIST = 0 <NEW_LINE> SEVERITY_LOW = 1 <NEW_LINE> SEVERITY_NORMAL = 2 <NEW_LINE> SEVERITY_HIGH = 3 <NEW_LINE> SEVERITY_CRITICAL = 4 <NEW_LINE> SEVERITIES = ( (SEVERITY_WISHLIST, 'wishlist'), (SEVERITY_LOW, 'low'), (SEVERITY_NORMAL, 'normal'), (SEVERITY_HIGH, 'high'), (SEVERITY_CRITICAL, 'critical'), ) <NEW_LINE> package = models.ForeignKey(PackageName, related_name='action_items') <NEW_LINE> item_type = models.ForeignKey(ActionItemType, related_name='action_items') <NEW_LINE> short_description = models.TextField() <NEW_LINE> severity = models.IntegerField(choices=SEVERITIES, default=SEVERITY_NORMAL) <NEW_LINE> created_timestamp = models.DateTimeField(auto_now_add=True) <NEW_LINE> last_updated_timestamp = models.DateTimeField(auto_now=True) <NEW_LINE> extra_data = JSONField(blank=True, null=True) <NEW_LINE> objects = ActionItemManager() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> unique_together = ('package', 'item_type') <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '{package} - {desc} ({severity})'.format( package=self.package, desc=self.short_description, severity=self.get_severity_display()) <NEW_LINE> <DEDENT> def get_absolute_url(self): <NEW_LINE> <INDENT> return reverse('dtracker-action-item', kwargs={ 'item_pk': self.pk, }) <NEW_LINE> <DEDENT> @property <NEW_LINE> def full_description_template(self): <NEW_LINE> <INDENT> return self.item_type.full_description_template <NEW_LINE> <DEDENT> @cached_property <NEW_LINE> def full_description(self): <NEW_LINE> <INDENT> if not self.full_description_template: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> return mark_safe( distro_tracker_render_to_string( self.full_description_template, {'item': self, })) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> return { 'short_description': self.short_description, 'package': { 'name': self.package.name, 'id': self.package.id, }, 'full_description': self.full_description, 'severity': { 'name': self.get_severity_display(), 'level': self.severity, 'label_type': { 0: 'info', 3: 'warning', 4: 'danger', }.get(self.severity, 'default') }, 'created': self.created_timestamp.strftime('%Y-%m-%d'), 'updated': self.last_updated_timestamp.strftime('%Y-%m-%d'), }
|
Model for entries of the "action needed" panel.
|
625990063cc13d1c6d466271
|
class TarBadPathError(Exception): <NEW_LINE> <INDENT> def __init__(self, root, offensive_path, *args, **kwargs): <NEW_LINE> <INDENT> self.root = root <NEW_LINE> self.offensive_path = offensive_path <NEW_LINE> Exception.__init__(self, *args, **kwargs)
|
Raised when a root directory does not contain all file paths.
|
62599006462c4b4f79dbc52e
|
class TestInterWikiMapBackend: <NEW_LINE> <INDENT> def test_load_file(self): <NEW_LINE> <INDENT> tmpdir = tempfile.mkdtemp() <NEW_LINE> with pytest.raises(IOError): <NEW_LINE> <INDENT> InterWikiMap.from_file(os.path.join(tmpdir, 'void')) <NEW_LINE> <DEDENT> testfile = os.path.join(tmpdir, 'foo.iwm') <NEW_LINE> with open(testfile, 'w') as f: <NEW_LINE> <INDENT> f.write('foo bar\n' 'baz spam\n' 'ham end end # this is really the end.') <NEW_LINE> <DEDENT> testiwm = InterWikiMap.from_file(testfile) <NEW_LINE> assert testiwm.iwmap == dict(foo='bar', baz='spam', ham='end end') <NEW_LINE> testfile = os.path.join(tmpdir, 'bar.iwm') <NEW_LINE> with open(testfile, 'w') as f: <NEW_LINE> <INDENT> f.write('# This is a malformed interwiki file\n' 'fails # ever') <NEW_LINE> <DEDENT> with pytest.raises(ValueError): <NEW_LINE> <INDENT> InterWikiMap.from_file(testfile) <NEW_LINE> <DEDENT> shutil.rmtree(tmpdir) <NEW_LINE> <DEDENT> def test_load_string(self): <NEW_LINE> <INDENT> assert InterWikiMap.from_string('').iwmap == dict() <NEW_LINE> assert InterWikiMap.from_string('#spam\r\n').iwmap == dict() <NEW_LINE> s = ('# foo bar\n' '#spamham\r\n' '# space space\n' 'foo bar\r\n' 'ham spam # this is a valid description') <NEW_LINE> assert InterWikiMap.from_string(s).iwmap == dict(foo='bar', ham='spam') <NEW_LINE> s = ('link1 http://link1.com/\r\n' 'link2 http://link2.in/\r\n') <NEW_LINE> assert (InterWikiMap.from_string(s).iwmap == dict(link1='http://link1.com/', link2='http://link2.in/')) <NEW_LINE> with pytest.raises(ValueError): <NEW_LINE> <INDENT> InterWikiMap.from_string('foobarbaz') <NEW_LINE> <DEDENT> <DEDENT> def test_real_interwiki_map(self): <NEW_LINE> <INDENT> this_dir = os.path.dirname(__file__) <NEW_LINE> testfile = os.path.join(this_dir, 'test_interwiki_intermap.txt') <NEW_LINE> testiwm = InterWikiMap.from_file(testfile) <NEW_LINE> assert 'MoinMaster' in testiwm.iwmap <NEW_LINE> assert testiwm.iwmap['MoinMaster'] == 'https://master.moinmo.in/' <NEW_LINE> assert 'PythonInfo' in testiwm.iwmap <NEW_LINE> assert 'this' not in testiwm.iwmap <NEW_LINE> assert testiwm.iwmap['MoinMoin'] == 'https://moinmo.in/' <NEW_LINE> assert testiwm.iwmap['hg'] == 'https://www.mercurial-scm.org/wiki/' <NEW_LINE> assert testiwm.iwmap['h2g2'] == 'http://h2g2.com/dna/h2g2/'
|
tests for interwiki map
|
62599006627d3e7fe0e079c4
|
class IpAddressRings: <NEW_LINE> <INDENT> def __init__(self, get_response): <NEW_LINE> <INDENT> self.get_response = get_response <NEW_LINE> <DEDENT> def __call__(self, request): <NEW_LINE> <INDENT> real_ip_header = 'HTTP_X_REAL_IP' <NEW_LINE> forwarded_for_header = 'HTTP_X_FORWARDED_FOR' <NEW_LINE> remote_addr = 'REMOTE_ADDR' <NEW_LINE> ip_address = request.META.get( real_ip_header, request.META.get( forwarded_for_header, request.META.get( remote_addr, 'Not Found' ) ) ) <NEW_LINE> request.source_ip_address = ip_address <NEW_LINE> ip_address_rings = settings.IP_ADDRESS_RINGS <NEW_LINE> allowed_ip_address_rings = settings.ALLOWED_IP_ADDRESS_RINGS <NEW_LINE> request.ip_address_rings = list() <NEW_LINE> for ring in allowed_ip_address_rings: <NEW_LINE> <INDENT> patterns = ip_address_rings[ring] <NEW_LINE> if re.search('|'.join(patterns), ip_address): <NEW_LINE> <INDENT> request.ip_address_rings.append(ring) <NEW_LINE> <DEDENT> <DEDENT> if not len(request.ip_address_rings): <NEW_LINE> <INDENT> return HttpResponseForbidden() <NEW_LINE> <DEDENT> response = self.get_response(request) <NEW_LINE> return response
|
Set the network_ring attribute on the request object based on the IP from
which the request was made
|
62599006462c4b4f79dbc532
|
class ConstantExpression(AbstractVariableExpression): <NEW_LINE> <INDENT> def _get_type(self): return self.variable.type <NEW_LINE> def _set_type(self, other_type=ANY_TYPE, signature=None): <NEW_LINE> <INDENT> assert isinstance(other_type, Type) <NEW_LINE> if signature is None: <NEW_LINE> <INDENT> signature = defaultdict(list) <NEW_LINE> <DEDENT> resolution = ANY_TYPE <NEW_LINE> if other_type != ANY_TYPE: <NEW_LINE> <INDENT> resolution = other_type.resolve(self.type) <NEW_LINE> <DEDENT> for varEx in signature[self.variable.name]: <NEW_LINE> <INDENT> resolution = varEx.type.resolve(resolution) <NEW_LINE> if not resolution: <NEW_LINE> <INDENT> raise InconsistentTypeHierarchyException(self) <NEW_LINE> <DEDENT> <DEDENT> signature[self.variable.name].append(self.variable) <NEW_LINE> for varEx in signature[self.variable.name]: <NEW_LINE> <INDENT> varEx.type = resolution <NEW_LINE> <DEDENT> <DEDENT> type = property(_get_type, _set_type) <NEW_LINE> def free(self): <NEW_LINE> <INDENT> return set() <NEW_LINE> <DEDENT> def bound(self): <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> def constants(self): <NEW_LINE> <INDENT> return set([self.variable])
|
This class represents variables that do not take the form of a single
character followed by zero or more digits.
|
62599006bf627c535bcb1fd9
|
class PresentationSetForm(forms.ModelForm): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> self.fields['Assessors'].label_from_instance = self.user_label_from_instance <NEW_LINE> self.fields['Assessors'].queryset = get_grouptype('2').user_set.all().select_related('usermeta') | get_grouptype('2u').user_set.all().select_related('usermeta') | get_grouptype('1').user_set.all().select_related('usermeta') <NEW_LINE> self.fields['PresentationAssessors'].label_from_instance = self.user_label_from_instance <NEW_LINE> self.fields['PresentationAssessors'].queryset = get_grouptype('7').user_set.all().select_related('usermeta') <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def user_label_from_instance(self): <NEW_LINE> <INDENT> return self.usermeta.get_nice_name <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> model = PresentationSet <NEW_LINE> fields = ['PresentationRoom', 'AssessmentRoom', 'Track', 'Assessors', 'PresentationAssessors', 'DateTime'] <NEW_LINE> labels = { 'PresentationRoom': "Presentation room", 'AssessmentRoom': "Assessment room", 'DateTime': "Start date/time", 'PresentationAssessors': "Presentation Assessor (ESA)", } <NEW_LINE> widgets = { 'PresentationRoom': widgets.MetroSelect, 'AssessmentRoom': widgets.MetroSelect, 'Track': widgets.MetroSelect, 'Assessors': widgets.MetroSelectMultiple, 'PresentationAssessors': widgets.MetroSelectMultiple, 'DateTime': widgets.MetroDateTimeInput, } <NEW_LINE> <DEDENT> def clean_DateTime(self): <NEW_LINE> <INDENT> ts = get_timeslot() <NEW_LINE> Phase = ts.timephases.get(Description=7) <NEW_LINE> data = self.cleaned_data['DateTime'] <NEW_LINE> if data == '' or data is None: <NEW_LINE> <INDENT> return data <NEW_LINE> <DEDENT> if data.date() < ts.Begin: <NEW_LINE> <INDENT> raise forms.ValidationError("The date is before the begin of this time slot. Please choose a later date") <NEW_LINE> <DEDENT> elif data.date() > Phase.End: <NEW_LINE> <INDENT> raise forms.ValidationError("The date is after the presentations time phase. Please choose an earlier date") <NEW_LINE> <DEDENT> elif data.time() > time(hour=23): <NEW_LINE> <INDENT> raise forms.ValidationError("The start time is after 23:00, which is too late") <NEW_LINE> <DEDENT> elif data.time() < time(hour=7): <NEW_LINE> <INDENT> raise forms.ValidationError("The start time is before 7:00, which is too early") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return data <NEW_LINE> <DEDENT> <DEDENT> def save(self, commit=True): <NEW_LINE> <INDENT> if commit: <NEW_LINE> <INDENT> self.instance.PresentationOptions = get_timeslot().presentationoptions <NEW_LINE> super().save(commit=True) <NEW_LINE> self.instance.save() <NEW_LINE> <DEDENT> return self.instance
|
A set of presentations. A set is a number of presentations in the same room for one track.
|
625990060a366e3fb87dd51d
|
class baseuser_add(LDAPCreate): <NEW_LINE> <INDENT> def pre_common_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options): <NEW_LINE> <INDENT> assert isinstance(dn, DN) <NEW_LINE> set_krbcanonicalname(entry_attrs) <NEW_LINE> check_fips_auth_opts(fips_mode=self.api.env.fips_mode, **options) <NEW_LINE> self.obj.convert_usercertificate_pre(entry_attrs) <NEW_LINE> <DEDENT> def post_common_callback(self, ldap, dn, entry_attrs, *keys, **options): <NEW_LINE> <INDENT> assert isinstance(dn, DN) <NEW_LINE> self.obj.convert_usercertificate_post(entry_attrs, **options) <NEW_LINE> self.obj.get_password_attributes(ldap, dn, entry_attrs) <NEW_LINE> convert_sshpubkey_post(entry_attrs) <NEW_LINE> radius_dn2pk(self.api, entry_attrs)
|
Prototype command plugin to be implemented by real plugin
|
62599006627d3e7fe0e079c8
|
class WebSystrayView(WebDialog): <NEW_LINE> <INDENT> def __init__(self, application, icon): <NEW_LINE> <INDENT> super(WebSystrayView, self).__init__(application, "systray.html", api=WebSystrayApi(application, self)) <NEW_LINE> self._icon = icon <NEW_LINE> self._view.setFocusProxy(self) <NEW_LINE> self.resize(300, 370) <NEW_LINE> self.setWindowFlags(QtCore.Qt.FramelessWindowHint | QtCore.Qt.WindowStaysOnTopHint); <NEW_LINE> <DEDENT> def replace(self): <NEW_LINE> <INDENT> rect = self._icon.geometry() <NEW_LINE> if rect.x() < 100: <NEW_LINE> <INDENT> x = rect.x() + rect.width() <NEW_LINE> y = rect.y() - self.height() + rect.height() <NEW_LINE> <DEDENT> elif rect.y() < 100: <NEW_LINE> <INDENT> x = rect.x() + rect.width() - self.width() <NEW_LINE> y = rect.y() + rect.height() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> x = rect.x() + rect.width() - self.width() <NEW_LINE> y = rect.y() - self.height() <NEW_LINE> <DEDENT> self.move(x, y) <NEW_LINE> <DEDENT> def show(self): <NEW_LINE> <INDENT> self.replace() <NEW_LINE> super(WebSystrayView, self).show() <NEW_LINE> if self.isVisible(): <NEW_LINE> <INDENT> self.raise_() <NEW_LINE> self.activateWindow() <NEW_LINE> self.setFocus(QtCore.Qt.ActiveWindowFocusReason) <NEW_LINE> <DEDENT> <DEDENT> def underMouse(self): <NEW_LINE> <INDENT> return self.geometry().contains(QtGui.QCursor.pos()) <NEW_LINE> <DEDENT> def shouldHide(self): <NEW_LINE> <INDENT> if not (self.underMouse() or self._icon.geometry().contains(QtGui.QCursor.pos())): <NEW_LINE> <INDENT> self.close() <NEW_LINE> <DEDENT> <DEDENT> def focusOutEvent(self, event): <NEW_LINE> <INDENT> if self._icon is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if not (self.underMouse() or self._icon.geometry().contains(QtGui.QCursor.pos())): <NEW_LINE> <INDENT> self.close() <NEW_LINE> <DEDENT> super(WebSystrayView, self).focusOutEvent(event) <NEW_LINE> <DEDENT> def resizeEvent(self, event): <NEW_LINE> <INDENT> super(WebSystrayView, self).resizeEvent(event) <NEW_LINE> self.replace() <NEW_LINE> <DEDENT> @QtCore.pyqtSlot() <NEW_LINE> def close(self): <NEW_LINE> <INDENT> self._icon = None <NEW_LINE> super(WebSystrayView, self).close()
|
classdocs
|
625990060a366e3fb87dd525
|
class Oper(A10BaseClass): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.ERROR_MSG = "" <NEW_LINE> self.b_key = "oper" <NEW_LINE> self.DeviceProxy = "" <NEW_LINE> self.total_sessions = "" <NEW_LINE> self.cache_list = [] <NEW_LINE> self.state = "" <NEW_LINE> self.session_list = [] <NEW_LINE> self.matched = "" <NEW_LINE> for keys, value in kwargs.items(): <NEW_LINE> <INDENT> setattr(self,keys, value)
|
This class does not support CRUD Operations please use parent.
:param total_sessions: {"type": "number", "format": "number"}
:param cache_list: {"minItems": 1, "items": {"type": "object"}, "uniqueItems": true, "type": "array", "array": [{"properties": {"cache-ttl": {"type": "number", "format": "number"}, "additional-records": {"type": "number", "format": "number"}, "question-records": {"type": "number", "format": "number"}, "cache-dns-flag": {"minLength": 1, "maxLength": 63, "type": "string", "format": "string"}, "answer-records": {"type": "number", "format": "number"}, "alias": {"minLength": 1, "maxLength": 63, "type": "string", "format": "string"}, "cache-length": {"type": "number", "format": "number"}, "optional": true, "authority-records": {"type": "number", "format": "number"}}}]}
:param state: {"minLength": 1, "maxLength": 63, "type": "string", "format": "string"}
:param session_list: {"minItems": 1, "items": {"type": "object"}, "uniqueItems": true, "type": "array", "array": [{"properties": {"aging": {"type": "number", "format": "number"}, "hits": {"type": "number", "format": "number"}, "update": {"type": "number", "format": "number"}, "client": {"minLength": 1, "maxLength": 63, "type": "string", "format": "string"}, "last-second-hits": {"type": "number", "format": "number"}, "mode": {"minLength": 1, "maxLength": 63, "type": "string", "format": "string"}, "ttl": {"minLength": 1, "maxLength": 63, "type": "string", "format": "string"}, "optional": true, "best": {"minLength": 1, "maxLength": 63, "type": "string", "format": "string"}}}]}
:param matched: {"type": "number", "format": "number"}
:param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`
|
62599006d164cc6175821ab1
|
class Solution: <NEW_LINE> <INDENT> def subsetsWithDup(self, nums): <NEW_LINE> <INDENT> if nums == None: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> nums.sort() <NEW_LINE> subset = [] <NEW_LINE> results = [] <NEW_LINE> self.dfs(nums, subset, results, 0) <NEW_LINE> return results <NEW_LINE> <DEDENT> def dfs(self, nums, subset, results, startIndex): <NEW_LINE> <INDENT> results.append(list(subset)) <NEW_LINE> for i in range(startIndex, len(nums)): <NEW_LINE> <INDENT> if i != 0 and nums[i] == nums[i-1] and i > startIndex: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> subset.append(nums[i]) <NEW_LINE> self.dfs(nums, subset, results, i+1) <NEW_LINE> subset.remove(nums[i])
|
@param nums: A set of numbers.
@return: A list of lists. All valid subsets.
|
62599006bf627c535bcb1fea
|
class TaskFactory(object): <NEW_LINE> <INDENT> _task_registry = [] <NEW_LINE> def __init__(self, basename): <NEW_LINE> <INDENT> self.basename = basename <NEW_LINE> self.clean = True <NEW_LINE> TaskFactory._task_registry.append(self) <NEW_LINE> <DEDENT> def as_task_dict(self): <NEW_LINE> <INDENT> if getattr(self, "skipped", False): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> fields = ["basename", "file_dep", "targets", "actions", "clean", "uptodate"] <NEW_LINE> return {x: getattr(self, x) for x in fields} <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def target(self): <NEW_LINE> <INDENT> if len(self.targets) == 1: <NEW_LINE> <INDENT> return self.targets[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception( "Ambiguous call to \"target\" ({} target{})".format( len(self.targets), "" if len(self.targets)==0 else "s")) <NEW_LINE> <DEDENT> <DEDENT> uptodate = property(misc.uptodate)
|
Base class for task factory objects. Derived classes must follow this
example:
>>> class MyTask(TaskFactory):
... def __init__(self, input, output):
... # Initialize base class
... TaskFactory.__init__(self, "my basename")
...
... # Define mandatory members
... self.file_dep = [input]
... self.targets = [output]
... self.actions = ["touch {}".format(output)]
A task can then be created as such:
>>> task = MyTask("foo", "bar")
If the task is not re-used, storing it in an object is not mandatory.
|
6259900615fb5d323ce7f87f
|
class extended_response_code(enum.IntEnum): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def from_param(cls, obj): <NEW_LINE> <INDENT> return int(obj) <NEW_LINE> <DEDENT> EXTENDED_RESPONSE_OK = 0 <NEW_LINE> EXTENDED_RESPONSE_INVALID_COMMAND = -1 <NEW_LINE> EXTENDED_RESPONSE_INVALID_STATE = -2 <NEW_LINE> EXTENDED_RESPONSE_OPERATION_FAILED = -3
|
A ctypes-compatible IntEnum superclass.
|
625990060a366e3fb87dd52f
|
class LEDlogic(object): <NEW_LINE> <INDENT> def __init__(self, Bit2Pin, Bit1Pin, Bit0Pin): <NEW_LINE> <INDENT> self.Bit0Pin = Bit0Pin <NEW_LINE> self.Bit1Pin = Bit1Pin <NEW_LINE> self.Bit2Pin = Bit2Pin <NEW_LINE> self.LEDpins = [Bit2Pin, Bit1Pin, Bit0Pin] <NEW_LINE> self.LastCall = None <NEW_LINE> self.Logging = True <NEW_LINE> <DEDENT> def setLogging(self, printLogs): <NEW_LINE> <INDENT> if printLogs == True: <NEW_LINE> <INDENT> self.Logging = True <NEW_LINE> <DEDENT> elif printLogs == False: <NEW_LINE> <INDENT> self.Logging = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("Error: argument must be True or False") <NEW_LINE> <DEDENT> <DEDENT> def Verbose(self): <NEW_LINE> <INDENT> print("\n___LEDs___") <NEW_LINE> print("[Logging: {}]".format(self.Logging)) <NEW_LINE> print("Bit0 Pin: {}".format(self.Bit0Pin)) <NEW_LINE> print("Bit1 Pin: {}".format(self.Bit1Pin)) <NEW_LINE> print("Bit2 Pin: {}".format(self.Bit2Pin)) <NEW_LINE> print("Pin List: {}".format(self.LEDpins)) <NEW_LINE> print("__________\n") <NEW_LINE> <DEDENT> def activatePins(self, LEDlist=[0, 0, 0], CycleTime=1): <NEW_LINE> <INDENT> if LEDlist == [0, 0, 0]: LEDlist = [1, 1, 1] <NEW_LINE> Pin0 = self.Bit0Pin <NEW_LINE> Pin1 = self.Bit1Pin <NEW_LINE> Pin2 = self.Bit2Pin <NEW_LINE> GPIO.setmode(GPIO.BCM) <NEW_LINE> GPIO.setwarnings(False) <NEW_LINE> GPIO.setup(Pin0, GPIO.OUT) <NEW_LINE> GPIO.setup(Pin1, GPIO.OUT) <NEW_LINE> GPIO.setup(Pin2, GPIO.OUT) <NEW_LINE> try: <NEW_LINE> <INDENT> MyList = np.multiply(LEDlist, self.LEDpins).tolist() <NEW_LINE> if self.Logging == True: print("MyList: {}".format(MyList)) <NEW_LINE> if self.Logging == True: print("LEDpins: {}".format(self.LEDpins)) <NEW_LINE> for i in range(-1, -4, -1): <NEW_LINE> <INDENT> if self.LEDpins[i] & MyList[i]: <NEW_LINE> <INDENT> if self.Logging == True: print("Pin {} turning ON".format(self.LEDpins[i])) <NEW_LINE> GPIO.output(self.LEDpins[i], True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self.Logging == True: print("Pin {} should be OFF".format(self.LEDpins[i])) <NEW_LINE> GPIO.output(self.LEDpins[i], False) <NEW_LINE> <DEDENT> <DEDENT> if self.Logging == True: print("Sleeping for {} sec..".format(CycleTime/2)) <NEW_LINE> sleep(CycleTime/2) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> if self.Logging == True: print("Unable to activate LED pins") <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> GPIO.cleanup() <NEW_LINE> if self.Logging == True: print("All pins should be OFF") <NEW_LINE> if self.Logging == True: print("Sleeping for {} sec..".format(CycleTime/2)) <NEW_LINE> sleep(CycleTime/2) <NEW_LINE> <DEDENT> <DEDENT> def BinaryList(self, Integer): <NEW_LINE> <INDENT> return [int(d) for d in bin(Integer)[2:].zfill(3)] <NEW_LINE> <DEDENT> def Strobe(self): <NEW_LINE> <INDENT> GPIO.setmode(GPIO.BCM) <NEW_LINE> GPIO.setwarnings(False) <NEW_LINE> for x in range(len(self.LEDpins)): <NEW_LINE> <INDENT> GPIO.setup(self.LEDpins[x], GPIO.OUT, initial=1) <NEW_LINE> <DEDENT> sleep(0.05)
|
docstring for LEDlogic.
Binary format: [Bit2, Bit1, Bit0]
|
625990063cc13d1c6d466287
|
class NSNitroNserrRltSelectorInuse(NSNitroGslbErrors): <NEW_LINE> <INDENT> pass
|
Nitro error code 1944
The selector is being referenced by one or more limit
identifiers
|
62599006462c4b4f79dbc546
|
class MGOrderStatus: <NEW_LINE> <INDENT> CREATED = "CREATED" <NEW_LINE> PROCESSING = "PROCESSING" <NEW_LINE> APPROVED = "APPROVED" <NEW_LINE> DECLINED = "DECLINED" <NEW_LINE> FILTERED = "FILTERED" <NEW_LINE> PENDING = "PENDING" <NEW_LINE> UNKNOWN = "UNKNOWN" <NEW_LINE> ERROR = "ERROR"
|
Definition of all the possible statuses of an order.
See https://mg-docs.zotapay.com/payout/1.0/#common-resources
|
62599006627d3e7fe0e079dc
|
class TimeJD(TimeFormat): <NEW_LINE> <INDENT> name = 'jd' <NEW_LINE> def set_jds(self, val1, val2): <NEW_LINE> <INDENT> self._check_scale(self._scale) <NEW_LINE> self.jd1, self.jd2 = day_frac(val1, val2) <NEW_LINE> <DEDENT> @property <NEW_LINE> def value(self): <NEW_LINE> <INDENT> return self.jd1 + self.jd2
|
Julian Date time format
|
6259900615fb5d323ce7f883
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.