code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class RawSPTableToPG(RawSPToPG): <NEW_LINE> <INDENT> table = luigi.Parameter() <NEW_LINE> def requires(self): <NEW_LINE> <INDENT> return RawDataToPG.requires(self) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> schema_cmd = ("mdb-schema -T %s %s postgres | " "sed -e 's/Postgres_Unknown 0x10/TEXT/' | " 'psql "dbname=$PGDATABASE options=--search_path=%s"') <NEW_LINE> import_cmd = ("mdb-export -I postgres -q \\' %s %s | " "sed -e 's/)$/)\;/' | " 'psql "dbname=$PGDATABASE options=--search_path=%s"' ' -q') <NEW_LINE> schema = 'luigi_raw_' + self.schema <NEW_LINE> self.pgw.shell(schema_cmd % (self.table, self.targetpath, schema)) <NEW_LINE> self.pgw.shell(import_cmd % (self.targetpath, self.table, schema)) <NEW_LINE> <DEDENT> def output(self): <NEW_LINE> <INDENT> yield PGTableTarget(self.table, 'luigi_raw_' + self.schema)
Imports single Safety Pad tables
6259902b287bf620b6272bd9
class EngineServer(object): <NEW_LINE> <INDENT> def __init__(self, engine): <NEW_LINE> <INDENT> self._engine = engine <NEW_LINE> <DEDENT> def start_workflow(self, rpc_ctx, workflow_name, workflow_input, params): <NEW_LINE> <INDENT> LOG.info( "Received RPC request 'start_workflow'[rpc_ctx=%s," " workflow_name=%s, workflow_input=%s, params=%s]" % (rpc_ctx, workflow_name, workflow_input, params) ) <NEW_LINE> return self._engine.start_workflow( workflow_name, workflow_input, **params ) <NEW_LINE> <DEDENT> def on_task_result(self, rpc_ctx, task_id, result_data, result_error): <NEW_LINE> <INDENT> task_result = wf_utils.TaskResult(result_data, result_error) <NEW_LINE> LOG.info( "Received RPC request 'on_task_result'[rpc_ctx=%s," " task_id=%s, task_result=%s]" % (rpc_ctx, task_id, task_result) ) <NEW_LINE> return self._engine.on_task_result(task_id, task_result) <NEW_LINE> <DEDENT> def run_task(self, rpc_ctx, task_id): <NEW_LINE> <INDENT> LOG.info( "Received RPC request 'run_task'[rpc_ctx=%s, task_id=%s]" % (rpc_ctx, task_id) ) <NEW_LINE> return self._engine.run_task(task_id) <NEW_LINE> <DEDENT> def pause_workflow(self, rpc_ctx, execution_id): <NEW_LINE> <INDENT> LOG.info( "Received RPC request 'pause_workflow'[rpc_ctx=%s," " execution_id=%s]" % (rpc_ctx, execution_id) ) <NEW_LINE> return self._engine.pause_workflow(execution_id) <NEW_LINE> <DEDENT> def resume_workflow(self, rpc_ctx, execution_id): <NEW_LINE> <INDENT> LOG.info( "Received RPC request 'resume_workflow'[rpc_ctx=%s," " execution_id=%s]" % (rpc_ctx, execution_id) ) <NEW_LINE> return self._engine.resume_workflow(execution_id) <NEW_LINE> <DEDENT> def stop_workflow(self, rpc_ctx, execution_id, state, message=None): <NEW_LINE> <INDENT> LOG.info( "Received RPC request 'stop_workflow'[rpc_ctx=%s, execution_id=%s," " state=%s, message=%s]" % (rpc_ctx, execution_id, state, message) ) <NEW_LINE> return self._engine.stop_workflow(execution_id, state, message) <NEW_LINE> <DEDENT> def rollback_workflow(self, rpc_ctx, execution_id): <NEW_LINE> <INDENT> LOG.info( "Received RPC request 'rollback_workflow'[rpc_ctx=%s," " execution_id=%s]" % (rpc_ctx, execution_id) ) <NEW_LINE> return self._engine.resume_workflow(execution_id)
RPC Engine server.
6259902b711fe17d825e148e
class TestBaseFCM(object): <NEW_LINE> <INDENT> def test_base_manager_stores_data(self): <NEW_LINE> <INDENT> b = BaseFlowControlManager(65535) <NEW_LINE> assert b.initial_window_size == 65535 <NEW_LINE> assert b.window_size == 65535 <NEW_LINE> assert b.document_size is None <NEW_LINE> <DEDENT> def test_base_manager_stores_document_size(self): <NEW_LINE> <INDENT> b = BaseFlowControlManager(0, 650) <NEW_LINE> assert b.document_size == 650 <NEW_LINE> <DEDENT> def test_base_manager_doesnt_function(self): <NEW_LINE> <INDENT> b = BaseFlowControlManager(10, 10) <NEW_LINE> with pytest.raises(NotImplementedError): <NEW_LINE> <INDENT> b.increase_window_size(10) <NEW_LINE> <DEDENT> <DEDENT> def test_base_manager_private_interface_doesnt_function(self): <NEW_LINE> <INDENT> b = BaseFlowControlManager(10, 10) <NEW_LINE> with pytest.raises(NotImplementedError): <NEW_LINE> <INDENT> b._handle_frame(10) <NEW_LINE> <DEDENT> <DEDENT> def test_base_manager_decrements_window_size(self): <NEW_LINE> <INDENT> class TestFCM(BaseFlowControlManager): <NEW_LINE> <INDENT> def increase_window_size(self, frame_size): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> <DEDENT> b = TestFCM(10, 10) <NEW_LINE> b._handle_frame(5) <NEW_LINE> assert b.initial_window_size == 10 <NEW_LINE> assert b.window_size == 5 <NEW_LINE> assert b.document_size == 10
Tests the base flow control manager.
6259902b0a366e3fb87dd9d0
class LOOT_375: <NEW_LINE> <INDENT> pass
Guild Recruiter
6259902b30c21e258be997f4
class PasswordCheckRequest(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._password = "" <NEW_LINE> self._password_confirmation = "" <NEW_LINE> self._policy = None <NEW_LINE> self._pwquality_settings = None <NEW_LINE> self._username = "root" <NEW_LINE> self._fullname = "" <NEW_LINE> self._secret_type = constants.SecretType.PASSWORD <NEW_LINE> <DEDENT> @property <NEW_LINE> def password(self): <NEW_LINE> <INDENT> return self._password <NEW_LINE> <DEDENT> @password.setter <NEW_LINE> def password(self, new_password): <NEW_LINE> <INDENT> self._password = new_password <NEW_LINE> <DEDENT> @property <NEW_LINE> def password_confirmation(self): <NEW_LINE> <INDENT> return self._password_confirmation <NEW_LINE> <DEDENT> @password_confirmation.setter <NEW_LINE> def password_confirmation(self, new_password_confirmation): <NEW_LINE> <INDENT> self._password_confirmation = new_password_confirmation <NEW_LINE> <DEDENT> @property <NEW_LINE> def policy(self): <NEW_LINE> <INDENT> return self._policy <NEW_LINE> <DEDENT> @policy.setter <NEW_LINE> def policy(self, new_policy): <NEW_LINE> <INDENT> self._policy = new_policy <NEW_LINE> <DEDENT> @property <NEW_LINE> def pwquality_settings(self): <NEW_LINE> <INDENT> if not self._pwquality_settings: <NEW_LINE> <INDENT> self._pwquality_settings = pwquality_settings_cache.get_settings_by_minlen(self.policy.minlen) <NEW_LINE> <DEDENT> return self._pwquality_settings <NEW_LINE> <DEDENT> @property <NEW_LINE> def username(self): <NEW_LINE> <INDENT> return self._username <NEW_LINE> <DEDENT> @username.setter <NEW_LINE> def username(self, new_username): <NEW_LINE> <INDENT> self._username = new_username <NEW_LINE> <DEDENT> @property <NEW_LINE> def fullname(self): <NEW_LINE> <INDENT> return self._fullname <NEW_LINE> <DEDENT> @fullname.setter <NEW_LINE> def fullname(self, new_fullname): <NEW_LINE> <INDENT> self._fullname = new_fullname <NEW_LINE> <DEDENT> @property <NEW_LINE> def secret_type(self): <NEW_LINE> <INDENT> return self._secret_type <NEW_LINE> <DEDENT> @secret_type.setter <NEW_LINE> def secret_type(self, new_type): <NEW_LINE> <INDENT> if new_type not in constants.SecretType: <NEW_LINE> <INDENT> raise RuntimeError("Unknown secret type: {}".format(new_type)) <NEW_LINE> <DEDENT> self._secret_type = new_type
A wrapper for a password check request. This in general means the password to be checked as well as its validation criteria such as minimum length, if it can be empty, etc.
6259902b9b70327d1c57fd6c
class EmailHandler(object): <NEW_LINE> <INDENT> def __init__(self, successor=None): <NEW_LINE> <INDENT> print("EmailHandler - set _successor ", type(successor)) <NEW_LINE> self._successor = successor <NEW_LINE> <DEDENT> def handle_mail(self, subject, mail): <NEW_LINE> <INDENT> print('HANDLE_REQUEST IN BASE CLASS ') <NEW_LINE> pass
an interface for handling mails
6259902b1f5feb6acb163bda
class Route(SubResource): <NEW_LINE> <INDENT> _validation = { 'next_hop_type': {'required': True}, } <NEW_LINE> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'address_prefix': {'key': 'properties.addressPrefix', 'type': 'str'}, 'next_hop_type': {'key': 'properties.nextHopType', 'type': 'str'}, 'next_hop_ip_address': {'key': 'properties.nextHopIpAddress', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } <NEW_LINE> def __init__(self, *, next_hop_type, id: str=None, address_prefix: str=None, next_hop_ip_address: str=None, provisioning_state: str=None, name: str=None, etag: str=None, **kwargs) -> None: <NEW_LINE> <INDENT> super(Route, self).__init__(id=id, **kwargs) <NEW_LINE> self.address_prefix = address_prefix <NEW_LINE> self.next_hop_type = next_hop_type <NEW_LINE> self.next_hop_ip_address = next_hop_ip_address <NEW_LINE> self.provisioning_state = provisioning_state <NEW_LINE> self.name = name <NEW_LINE> self.etag = etag
Route resource. All required parameters must be populated in order to send to Azure. :param id: Resource ID. :type id: str :param address_prefix: The destination CIDR to which the route applies. :type address_prefix: str :param next_hop_type: Required. The type of Azure hop the packet should be sent to. Possible values are: 'VirtualNetworkGateway', 'VnetLocal', 'Internet', 'VirtualAppliance', and 'None'. Possible values include: 'VirtualNetworkGateway', 'VnetLocal', 'Internet', 'VirtualAppliance', 'None' :type next_hop_type: str or ~azure.mgmt.network.v2017_03_01.models.RouteNextHopType :param next_hop_ip_address: The IP address packets should be forwarded to. Next hop values are only allowed in routes where the next hop type is VirtualAppliance. :type next_hop_ip_address: str :param provisioning_state: The provisioning state of the resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :type provisioning_state: str :param name: The name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str
6259902b50485f2cf55dbf65
class CustomFieldSelection(Base): <NEW_LINE> <INDENT> __tablename__ = "customfieldselection" <NEW_LINE> __table_args__ = {"schema": dbname, "keep_existing": True} <NEW_LINE> encodedKey = Column(String, primary_key=True) <NEW_LINE> id = Column(String) <NEW_LINE> value = Column(String) <NEW_LINE> score = Column(Integer) <NEW_LINE> selectionindex = Column(Integer) <NEW_LINE> customfieldkey = Column(String, ForeignKey(CustomField.encodedKey)) <NEW_LINE> customField = relationship(CustomField, back_populates="customFieldSelection") <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return "<CustomFieldSet(id={}, value={})>".format(self.id, self.value) <NEW_LINE> <DEDENT> except UnicodeEncodeError: <NEW_LINE> <INDENT> return "<CustomFieldSet(id={}, value={})>".format( self.id, self.value.encode("utf8") )
CustomFieldValue table.
6259902bc432627299fa3fde
class UniversalParser(object): <NEW_LINE> <INDENT> parser = cparser <NEW_LINE> def __init__(self, parser): <NEW_LINE> <INDENT> self.parser = parser <NEW_LINE> <DEDENT> def parse_args(self): <NEW_LINE> <INDENT> self.args = self.parser.parse_args() <NEW_LINE> for arg in var(self.args): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> setattr(arg, eval(str(getattr(self.args, arg)))) <NEW_LINE> <DEDENT> except TypeError as err: <NEW_LINE> <INDENT> setattr(arg, getattr(self.args, arg)) <NEW_LINE> <DEDENT> <DEDENT> return self.args <NEW_LINE> <DEDENT> def add_argument(self, name, default): <NEW_LINE> <INDENT> if isinstance(default, bool): <NEW_LINE> <INDENT> self.parser.add_argument('--'+name, default=default, action='store_false' if default else 'store_true') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('Adding ' , name) <NEW_LINE> self.parser.add_argument('--'+name, default=str(default), type=str)
Store everything as a string except bool arguments so that you can evaluate them
6259902bd6c5a102081e3111
class NamespaceInjector(SONManipulator): <NEW_LINE> <INDENT> def transform_incoming(self, son, collection): <NEW_LINE> <INDENT> son["_ns"] = collection.name() <NEW_LINE> return son
A son manipulator that adds the _ns field.
6259902b796e427e5384f767
class ApplicationGatewayFrontendPort(SubResource): <NEW_LINE> <INDENT> _validation = { 'etag': {'readonly': True}, 'type': {'readonly': True}, 'provisioning_state': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'port': {'key': 'properties.port', 'type': 'int'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, id: Optional[str] = None, name: Optional[str] = None, port: Optional[int] = None, **kwargs ): <NEW_LINE> <INDENT> super(ApplicationGatewayFrontendPort, self).__init__(id=id, **kwargs) <NEW_LINE> self.name = name <NEW_LINE> self.etag = None <NEW_LINE> self.type = None <NEW_LINE> self.port = port <NEW_LINE> self.provisioning_state = None
Frontend port of an application gateway. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :param name: Name of the frontend port that is unique within an Application Gateway. :type name: str :ivar etag: A unique read-only string that changes whenever the resource is updated. :vartype etag: str :ivar type: Type of the resource. :vartype type: str :param port: Frontend port. :type port: int :ivar provisioning_state: The provisioning state of the frontend port resource. Possible values include: "Succeeded", "Updating", "Deleting", "Failed". :vartype provisioning_state: str or ~azure.mgmt.network.v2019_12_01.models.ProvisioningState
6259902b5e10d32532ce40f9
class UpdateTrackingList(): <NEW_LINE> <INDENT> def __init__(self, productURL, chatId): <NEW_LINE> <INDENT> print("Enter: UpdateTrackingList class") <NEW_LINE> self.productDetails = ProductInfo(productURL, chatId) <NEW_LINE> <DEDENT> def addToTrackingList(self): <NEW_LINE> <INDENT> print("Enter: Add to tracking list") <NEW_LINE> if self.productDetails.chatId not in PRODUCTLIST: <NEW_LINE> <INDENT> startScraping = ScrapeAmazon(self.productDetails) <NEW_LINE> x = threading.Thread(target=startScraping.startTracking, name=self.productDetails.chatId) <NEW_LINE> x.daemon=True <NEW_LINE> PRODUCTLIST[self.productDetails.chatId] = self.productDetails <NEW_LINE> print("Before: Thread starts ") <NEW_LINE> x.start() <NEW_LINE> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("User already exists") <NEW_LINE> return False
Update the changes in tracking list
6259902b3eb6a72ae038b650
class NetworkAdapterDoesNotExistException(MCVirtException): <NEW_LINE> <INDENT> pass
The network adapter does not exist
6259902bd4950a0f3b111633
class Crc32Fixup(Fixup): <NEW_LINE> <INDENT> def __init__(self, ref): <NEW_LINE> <INDENT> Fixup.__init__(self) <NEW_LINE> self.ref = ref <NEW_LINE> <DEDENT> def fixup(self): <NEW_LINE> <INDENT> self.context.defaultValue = "0" <NEW_LINE> stuff = self.context.findDataElementByName(self.ref).getValue() <NEW_LINE> if stuff is None: <NEW_LINE> <INDENT> raise Exception("Error: Crc32Fixup was unable to locate " "[{}]".format(self.ref)) <NEW_LINE> <DEDENT> crc = zlib.crc32(stuff) <NEW_LINE> if crc < 0: <NEW_LINE> <INDENT> crc = ~crc ^ 0xffffffff <NEW_LINE> <DEDENT> return crc
Standard CRC32 as defined by ISO 3309. Used by PNG, ZIP, etc.
6259902bd10714528d69ee82
class SimulationMetadata: <NEW_LINE> <INDENT> def __init__(self, path: Path, format: str): <NEW_LINE> <INDENT> self.path = Path(path) <NEW_LINE> self.format = format <NEW_LINE> if self.path.is_dir(): <NEW_LINE> <INDENT> self.path = self.path / f"{format}.out" <NEW_LINE> <DEDENT> self.data_path = self.path.parent <NEW_LINE> self.read_vars(self.path, format) <NEW_LINE> if format == "vtk": <NEW_LINE> <INDENT> if self.file_mode == "single": <NEW_LINE> <INDENT> self.vtk_offsets = vtk_offsets(self.path.parent / "data.0000.vtk") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.vtk_offsets = {} <NEW_LINE> for var in self.vars: <NEW_LINE> <INDENT> self.vtk_offsets.update( vtk_offsets(self.path.parent / f"{var}.0000.vtk") ) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def read_vars(self, path: Path, format: str) -> None: <NEW_LINE> <INDENT> with path.open() as f: <NEW_LINE> <INDENT> lines = f.readlines() <NEW_LINE> self.length = len(lines) <NEW_LINE> self.t = np.empty(self.length, float) <NEW_LINE> self.sim_dt = np.empty(self.length, float) <NEW_LINE> self.nstep = np.empty(self.length, int) <NEW_LINE> file_mode, endianness, *self.vars = lines[0].split()[4:] <NEW_LINE> self.file_mode = "single" if file_mode == "single_file" else "multiple" <NEW_LINE> self.charsize = 8 if format == "dbl" else 4 <NEW_LINE> endianness = "<" if endianness == "little" else ">" <NEW_LINE> if format == "vtk": <NEW_LINE> <INDENT> endianness = ">" <NEW_LINE> <DEDENT> self.binformat = "{}f{}".format(endianness, self.charsize) <NEW_LINE> for i, line in enumerate(lines): <NEW_LINE> <INDENT> self.t[i], self.sim_dt[i], self.nstep[i] = line.split()[1:4] <NEW_LINE> <DEDENT> self.dt = self.t[1:] - self.t[:-1] <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return f"{type(self).__name__}('{self.path}','{self.format}')"
Pluto simulation metadata reader and parser Read metadata from `format.out` files (e.g. `dbl.out`, `flt.out`). Attributes: path (Path): path to outputfile file_mode (str): PLUTO output in `"single"` or `"multiple"` files. vtk_offsets (:obj:`dict` of :obj:`int`): Byte offsets of data in VTK file t (:obj:`numpy.ndarray` of `numpy.float64`): simulation time of outputs dt (:obj:`numpy.ndarray` of `numpy.float64`): simulation time difference of outputs sim_dt (:obj:`numpy.ndarray` of `numpy.float64`): simulation timestep at outputs nstep (:obj:`numpy.ndarray` of `numpy.float64`): simulation step at outputs file_mode (str): `"single"` or `"multiple"`, PLUTO output mode for format vars (:obj:`list` of :obj:`str`): Variables available in output charsize (int): size of floating point number in bytes (4 or 8) binformat (str): binary format descriptor
6259902b9b70327d1c57fd6e
class SshCounterAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> list_display = ('name','script') <NEW_LINE> search_fields = ('name','script')
The **SshCounterAdmin** class represents the **SshCounter** model administration page
6259902b66673b3332c313dc
@ddt.ddt <NEW_LINE> @skip_unless_lms <NEW_LINE> class TestRegisterRetiredUsername(TestCase): <NEW_LINE> <INDENT> INVALID_ACCT_ERR_MSG = ('An account with the Public Username', 'already exists.') <NEW_LINE> INVALID_ERR_MSG = ('It looks like', 'belongs to an existing account. Try again with a different username.') <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> super(TestRegisterRetiredUsername, self).setUp() <NEW_LINE> self.url = reverse('user_api_registration') <NEW_LINE> self.url_params = { 'username': 'username', 'email': 'foo_bar' + '@bar.com', 'name': 'foo bar', 'password': '123', 'terms_of_service': 'true', 'honor_code': 'true', } <NEW_LINE> <DEDENT> def _validate_exiting_username_response(self, orig_username, response, start_msg=INVALID_ACCT_ERR_MSG[0], end_msg=INVALID_ACCT_ERR_MSG[1]): <NEW_LINE> <INDENT> assert response.status_code == 409 <NEW_LINE> obj = json.loads(response.content.decode('utf-8')) <NEW_LINE> username_msg = obj['username'][0]['user_message'] <NEW_LINE> assert username_msg.startswith(start_msg) <NEW_LINE> assert username_msg.endswith(end_msg) <NEW_LINE> assert orig_username in username_msg <NEW_LINE> <DEDENT> def test_retired_username(self): <NEW_LINE> <INDENT> user = UserFactory() <NEW_LINE> orig_username = user.username <NEW_LINE> user.username = get_retired_username_by_username(orig_username) <NEW_LINE> user.save() <NEW_LINE> self.url_params['username'] = orig_username <NEW_LINE> response = self.client.post(self.url, self.url_params) <NEW_LINE> self._validate_exiting_username_response(orig_username, response, self.INVALID_ERR_MSG[0], self.INVALID_ERR_MSG[1]) <NEW_LINE> <DEDENT> def test_username_close_to_retired_format_active(self): <NEW_LINE> <INDENT> self.url_params['username'] = settings.RETIRED_USERNAME_PREFIX <NEW_LINE> response = self.client.post(self.url, self.url_params) <NEW_LINE> self._validate_exiting_username_response(settings.RETIRED_USERNAME_PREFIX, response)
Tests to ensure that retired usernames can no longer be used in registering new accounts.
6259902b796e427e5384f769
class FlowFilter(filters.FilterSet): <NEW_LINE> <INDENT> time_stamp = django_filters.DateTimeFilter(name="time_stamp", lookup_expr='gte') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = LectureFlow <NEW_LINE> fields = ['time_stamp']
Gives the possibility to only return votes after a time eg.: http://localhost:8000/lecture/3/flow/?time_stamp=2017-03-13%2017:10:10 returns only votes after 2017-03-13%2016:10:10
6259902b8a43f66fc4bf3170
class UserInfo(AbstractUserInfo): <NEW_LINE> <INDENT> gender_choice = ( (1, '男'), (2, '女'), ) <NEW_LINE> gender = models.IntegerField(verbose_name='性别', choices=gender_choice, default=1) <NEW_LINE> depart = models.ForeignKey(verbose_name='部门', to='Department') <NEW_LINE> email = models.EmailField(verbose_name='邮箱') <NEW_LINE> phone = models.CharField(verbose_name='手机', max_length=32) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.username
用户表
6259902b15baa72349462f85
class BitcoinFeefilter(BitcoinMessage): <NEW_LINE> <INDENT> cmd = "feefilter" <NEW_LINE> fields_desc = [ XLELongField("feerate", 0), ]
Added in protocol version 70013. The feefilter message is a request to the receiving peer to not relay any transaction inv messages to the sending peer where the fee rate for the transaction is below the fee rate specified in the feefilter message.
6259902b8a349b6b43687227
class Controller(rest.RestController): <NEW_LINE> <INDENT> nodes = node.NodesController() <NEW_LINE> ports = port.PortsController() <NEW_LINE> chassis = chassis.ChassisController() <NEW_LINE> drivers = driver.DriversController() <NEW_LINE> @expose.expose(V1) <NEW_LINE> def get(self): <NEW_LINE> <INDENT> return V1.convert() <NEW_LINE> <DEDENT> def _check_version(self, version, headers=None): <NEW_LINE> <INDENT> if headers is None: <NEW_LINE> <INDENT> headers = {} <NEW_LINE> <DEDENT> if version.major != BASE_VERSION: <NEW_LINE> <INDENT> raise exc.HTTPNotAcceptable(_( "Mutually exclusive versions requested. Version %(ver)s " "requested but not supported by this service. The supported " "version range is: [%(min)s, %(max)s].") % {'ver': version, 'min': MIN_VER_STR, 'max': MAX_VER_STR}, headers=headers) <NEW_LINE> <DEDENT> if version < MIN_VER or version > MAX_VER: <NEW_LINE> <INDENT> raise exc.HTTPNotAcceptable(_( "Version %(ver)s was requested but the minor version is not " "supported by this service. The supported version range is: " "[%(min)s, %(max)s].") % {'ver': version, 'min': MIN_VER_STR, 'max': MAX_VER_STR}, headers=headers) <NEW_LINE> <DEDENT> <DEDENT> @pecan.expose() <NEW_LINE> def _route(self, args): <NEW_LINE> <INDENT> v = base.Version(pecan.request.headers, MIN_VER_STR, MAX_VER_STR) <NEW_LINE> pecan.response.headers[base.Version.min_string] = MIN_VER_STR <NEW_LINE> pecan.response.headers[base.Version.max_string] = MAX_VER_STR <NEW_LINE> self._check_version(v, pecan.response.headers) <NEW_LINE> pecan.response.headers[base.Version.string] = str(v) <NEW_LINE> pecan.request.version = v <NEW_LINE> return super(Controller, self)._route(args)
Version 1 API controller root.
6259902b8c3a8732951f7545
class GreaterThanOp(UnaryRule): <NEW_LINE> <INDENT> grammar = omit(re.compile(r"after|>", re.IGNORECASE)), attr('op', SimpleValue)
Greater than operator. Supports queries like author-count > 2000 or date after 10-2000.
6259902b30c21e258be997f9
class BookInstance(models.Model): <NEW_LINE> <INDENT> id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="Уникальный ID для конкретной книги во всей библиотеке") <NEW_LINE> book = models.ForeignKey("Book", on_delete=models.SET_NULL, null=True) <NEW_LINE> imprint = models.CharField(max_length=200) <NEW_LINE> due_back = models.DateField(null=True, blank=True) <NEW_LINE> LOAN_STATUS = ( ('m', 'Maintenance'), ('o', 'On loan'), ('a', 'Available'), ('r', 'Reserved'), ) <NEW_LINE> status = models.CharField(max_length=1, choices=LOAN_STATUS, blank=True, default='d', help_text="Статус книги") <NEW_LINE> borrower = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> ordering = ["due_back"] <NEW_LINE> permissions = (("can_mark_returned", "Set book as returned"),) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "{0} ({1})".format(self.id, self.book.title) <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_overdue(self): <NEW_LINE> <INDENT> if self.due_back and date.today() > self.due_back: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False
Модель представляет определенную копию книги (которая может найдена в библиотеке)
6259902b1f5feb6acb163bde
class SymbolExpression(AtomExpression): <NEW_LINE> <INDENT> def evaluate(self, environment, debug): <NEW_LINE> <INDENT> if debug: <NEW_LINE> <INDENT> return self.track_result(environment.retrieve_definition(self).copy()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.track_result(environment.retrieve_definition(self))
A symbol. (Any atom which isn't a number).
6259902bec188e330fdf9881
@view_defaults( context=IRootPool, name='password_reset', ) <NEW_LINE> class PasswordResetView: <NEW_LINE> <INDENT> def __init__(self, context: IRootPool, request: IRequest): <NEW_LINE> <INDENT> self.context = context <NEW_LINE> self.request = request <NEW_LINE> <DEDENT> @api_view(request_method='OPTIONS') <NEW_LINE> def options(self) -> dict: <NEW_LINE> <INDENT> return {'POST': {}} <NEW_LINE> <DEDENT> @api_view( request_method='POST', schema=POSTPasswordResetRequestSchema, accept='application/json', ) <NEW_LINE> def post(self) -> dict: <NEW_LINE> <INDENT> reset = self.request.validated['path'] <NEW_LINE> password = self.request.validated['password'] <NEW_LINE> reset.reset_password(password) <NEW_LINE> return _login_user(self.request)
Reset a user password.
6259902b6fece00bbaccc99d
class Query(object): <NEW_LINE> <INDENT> def __init__(self, query=None): <NEW_LINE> <INDENT> self.params = {} <NEW_LINE> if query: <NEW_LINE> <INDENT> self.parse(query) <NEW_LINE> <DEDENT> <DEDENT> def parse(self, query): <NEW_LINE> <INDENT> if isinstance(query, dict): <NEW_LINE> <INDENT> self.params = {k:urllib.unquote_plus(v) for k, v in query.iteritems()} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.params = parse_qs(query) <NEW_LINE> <DEDENT> <DEDENT> def add(self, args=None): <NEW_LINE> <INDENT> if args: <NEW_LINE> <INDENT> for param, value in args.iteritems(): <NEW_LINE> <INDENT> self.params[param] = value <NEW_LINE> <DEDENT> <DEDENT> return self <NEW_LINE> <DEDENT> def set(self, query=None): <NEW_LINE> <INDENT> if query: <NEW_LINE> <INDENT> self.parse(query) <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> def remove(self, query=None): <NEW_LINE> <INDENT> if query == True: <NEW_LINE> <INDENT> self.parse('') <NEW_LINE> <DEDENT> elif isinstance(query, list): <NEW_LINE> <INDENT> for key in query: <NEW_LINE> <INDENT> self.params.pop(key, None) <NEW_LINE> <DEDENT> <DEDENT> return self <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> params = {str(key):str(val) for key, val in self.params.iteritems()} <NEW_LINE> return urllib.urlencode(params) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "%s('%s')" % (self.__class__.__name__, str(self))
Represents a URL query comprised of zero or more unique parameters and their respective values. http://tools.ietf.org/html/rfc3986#section-3.4 Repeated URL parameters, like 'a=1&a=2', are deprecated to their first value, 'a=1'. This is a tradeoff in favor of ease of use over the rarely needed flexibility of repeated query parameters. As a result, interacting with query parameters can be performed with strings instead of lists of strings. if furl('...').args['meat'] == 'pumps': ... instead of val = furl('...').args['meat'] if len(val) == 1 and val[0] == 'pumps': ... In the future, support for repeated URL parameters could be added, possibly with a a constructor argument like repeated_params=True. Attributes: params: Dictionary of query parameter key:value pairs. Parameters in self.params are maintained URL decoded, 'a b' not 'a+b'.
6259902bd53ae8145f919452
class TApplicationException(TException): <NEW_LINE> <INDENT> UNKNOWN = 0 <NEW_LINE> UNKNOWN_METHOD = 1 <NEW_LINE> INVALID_MESSAGE_TYPE = 2 <NEW_LINE> WRONG_METHOD_NAME = 3 <NEW_LINE> BAD_SEQUENCE_ID = 4 <NEW_LINE> MISSING_RESULT = 5 <NEW_LINE> INTERNAL_ERROR = 6 <NEW_LINE> PROTOCOL_ERROR = 7 <NEW_LINE> def __init__(self, type=UNKNOWN, message=None): <NEW_LINE> <INDENT> TException.__init__(self, message) <NEW_LINE> self.type = type <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> if self.message: <NEW_LINE> <INDENT> return self.message <NEW_LINE> <DEDENT> elif self.type == self.UNKNOWN_METHOD: <NEW_LINE> <INDENT> return 'Unknown method' <NEW_LINE> <DEDENT> elif self.type == self.INVALID_MESSAGE_TYPE: <NEW_LINE> <INDENT> return 'Invalid message type' <NEW_LINE> <DEDENT> elif self.type == self.WRONG_METHOD_NAME: <NEW_LINE> <INDENT> return 'Wrong method name' <NEW_LINE> <DEDENT> elif self.type == self.BAD_SEQUENCE_ID: <NEW_LINE> <INDENT> return 'Bad sequence ID' <NEW_LINE> <DEDENT> elif self.type == self.MISSING_RESULT: <NEW_LINE> <INDENT> return 'Missing result' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 'Default (unknown) TApplicationException' <NEW_LINE> <DEDENT> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRING: <NEW_LINE> <INDENT> self.message = iprot.readString(); <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 2: <NEW_LINE> <INDENT> if ftype == TType.I32: <NEW_LINE> <INDENT> self.type = iprot.readI32(); <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> oprot.writeStructBegin('TApplicationException') <NEW_LINE> if self.message != None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('message', TType.STRING, 1) <NEW_LINE> oprot.writeString(self.message) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.type != None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('type', TType.I32, 2) <NEW_LINE> oprot.writeI32(self.type) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd()
Application level thrift exceptions.
6259902b66673b3332c313de
@dataclass <NEW_LINE> class ActionResult: <NEW_LINE> <INDENT> result: Any
Library unified action result object.
6259902b23e79379d538d4fa
class PerlSubIdentify(PerlPackage): <NEW_LINE> <INDENT> homepage = "http://search.cpan.org/~rgarcia/Sub-Identify-0.14/lib/Sub/Identify.pm" <NEW_LINE> url = "http://search.cpan.org/CPAN/authors/id/R/RG/RGARCIA/Sub-Identify-0.14.tar.gz" <NEW_LINE> version('0.14', '014f19e72698b6a2cbcb54adc9691825')
Retrieve names of code references
6259902b287bf620b6272be1
@namespace('/chat') <NEW_LINE> class ChatNamespace(BaseNamespace, RoomsMixin, BroadcastMixin): <NEW_LINE> <INDENT> user_list = [] <NEW_LINE> def initialize(self): <NEW_LINE> <INDENT> log.info("Chat session started") <NEW_LINE> <DEDENT> def on_file(self, msg): <NEW_LINE> <INDENT> user = self.socket.session['nick'] <NEW_LINE> log.info('User <%s> sending <%s>', user, msg['imageName']) <NEW_LINE> self.broadcast_event('user file', user, msg) <NEW_LINE> return True <NEW_LINE> <DEDENT> def on_says(self, msg): <NEW_LINE> <INDENT> user = self.socket.session['nick'] <NEW_LINE> log.info('<%s> says: \'%s\'', user, msg) <NEW_LINE> self.broadcast_event('receive msg', user, msg) <NEW_LINE> return True <NEW_LINE> <DEDENT> def on_join(self, user): <NEW_LINE> <INDENT> if not user: <NEW_LINE> <INDENT> self.broadcast_event('user connected', '', ChatNamespace.user_list) <NEW_LINE> return True <NEW_LINE> <DEDENT> log.info('User <%s> connected', user) <NEW_LINE> ChatNamespace.user_list.append(user) <NEW_LINE> self.socket.session['nick'] = user <NEW_LINE> self.broadcast_event('user connected', user, ChatNamespace.user_list) <NEW_LINE> <DEDENT> def recv_disconnect(self): <NEW_LINE> <INDENT> if 'nick' in self.socket.session: <NEW_LINE> <INDENT> log.info('User <%s> disconnected', self.socket.session['nick']) <NEW_LINE> user = self.socket.session['nick'] <NEW_LINE> if user in ChatNamespace.user_list: <NEW_LINE> <INDENT> ChatNamespace.user_list.remove(user) <NEW_LINE> <DEDENT> self.broadcast_event('user disconnected', user) <NEW_LINE> self.disconnect(silent=True)
Implement API for websocket channels
6259902b6e29344779b01640
class HistoryEntry(TableBase): <NEW_LINE> <INDENT> __tablename__ = 'history_entries' <NEW_LINE> id = IDColumn() <NEW_LINE> __table_args__ = (UniqueConstraint('commit', 'status'), ) <NEW_LINE> commit = Column( Unicode(), nullable=False) <NEW_LINE> status = Column( ForeignKey(Status.ident), nullable=False) <NEW_LINE> date = Column( Unicode(), nullable=False) <NEW_LINE> num_packages = Column( Integer(), nullable=False) <NEW_LINE> status_obj = relationship( 'Status', backref=backref('history'))
Stores the database's history.
6259902b73bcbd0ca4bcb282
class Placeholder(object): <NEW_LINE> <INDENT> pass
A placeholder used instead of a state or a history browser.
6259902bd18da76e235b7946
class DupeFinderBase(FWSerializable): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def verify(self, spec1, spec2): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def query(self, spec): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @serialize_fw <NEW_LINE> def to_dict(self): <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_dict(cls, m_dict): <NEW_LINE> <INDENT> return cls()
This serves an Abstract class for implementing Duplicate Finders
6259902b0a366e3fb87dd9d8
class Profile(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=50) <NEW_LINE> sic_code = models.CharField(max_length=10, blank=True, null=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = 'Profile' <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.name
Company description type and associated SIC code
6259902b8a43f66fc4bf3174
class Node: <NEW_LINE> <INDENT> def __init__(self, state, parent, cost): <NEW_LINE> <INDENT> self.state = state <NEW_LINE> self.parent = parent <NEW_LINE> self.cost = cost
A node represents a particular point in search space, contained within the tree of state spaces to search for a goal state.
6259902b6fece00bbaccc9a0
class TestCreateS3KeyResponseKeys(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testCreateS3KeyResponseKeys(self): <NEW_LINE> <INDENT> pass
CreateS3KeyResponseKeys unit test stubs
6259902bd4950a0f3b111636
class fetchgroup_indom(object): <NEW_LINE> <INDENT> def __init__(self, pmtype, num): <NEW_LINE> <INDENT> stss_t = c_int * num <NEW_LINE> values_t = pmAtomValue * num <NEW_LINE> icodes_t = c_int * num <NEW_LINE> inames_t = c_char_p * num <NEW_LINE> self.sts = c_int() <NEW_LINE> self.stss = stss_t() <NEW_LINE> self.pmtype = pmtype <NEW_LINE> self.values = values_t() <NEW_LINE> self.icodes = icodes_t() <NEW_LINE> self.inames = inames_t() <NEW_LINE> self.num = c_uint() <NEW_LINE> <DEDENT> def __call__(self): <NEW_LINE> <INDENT> vv = [] <NEW_LINE> if self.sts.value < 0: <NEW_LINE> <INDENT> raise pmErr(self.sts.value) <NEW_LINE> <DEDENT> for i in range(self.num.value): <NEW_LINE> <INDENT> def decode_one(self, i): <NEW_LINE> <INDENT> if self.stss[i] < 0: <NEW_LINE> <INDENT> raise pmErr(self.stss[i]) <NEW_LINE> <DEDENT> return self.values[i].dref(self.pmtype) <NEW_LINE> <DEDENT> vv.append((self.icodes[i], self.inames[i].decode('utf-8') if self.inames[i] else None, (lambda i: (lambda: decode_one(self, i)))(i))) <NEW_LINE> <DEDENT> return vv
An internal class to receive value/status for an indom of items. It may be called as if it were a function object to create an list of tuples containing instance-code/-name/value information. Each value is a function object that decodes the embedded pmAtomValue, which was set at the most recent fetch() call.
6259902b8c3a8732951f7549
class StandardManager(OptimizerManager): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._optimizer = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def hparam(self): <NEW_LINE> <INDENT> return self._hparam <NEW_LINE> <DEDENT> @property <NEW_LINE> def optimizer(self): <NEW_LINE> <INDENT> if self._optimizer is not None: <NEW_LINE> <INDENT> return self._optimizer <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise AttributeError("No optimizer was instantiated")
Second layer of meta class that implements generic access to optimizer and hparam
6259902b8c3a8732951f754a
@config(compat="windows", category="exploit") <NEW_LINE> class ImpersonateModule(PupyModule): <NEW_LINE> <INDENT> max_clients=1 <NEW_LINE> dependencies=["pupwinutils.security"] <NEW_LINE> def init_argparse(self): <NEW_LINE> <INDENT> self.arg_parser = PupyArgumentParser(prog="impersonate", description=self.__doc__) <NEW_LINE> self.arg_parser.add_argument("-l", "--list", action='store_true', help="list available Sids") <NEW_LINE> self.arg_parser.add_argument("-i", "--impersonate", metavar="SID", help="impersonate a sid") <NEW_LINE> self.arg_parser.add_argument("-m", "--migrate", action="store_true", help="spawn a new process and migrate into it") <NEW_LINE> self.arg_parser.add_argument("-r", "--rev2self", action='store_true', help="call rev2self") <NEW_LINE> <DEDENT> def run(self, args): <NEW_LINE> <INDENT> if args.list: <NEW_LINE> <INDENT> l=obtain(self.client.conn.modules["pupwinutils.security"].ListSids()) <NEW_LINE> self.rawlog(self.formatter.table_format([{"pid": x[0], "process":x[1], "sid" : x[2], "username":x[3]} for x in l], wl=["pid", "process", "username", "sid"])) <NEW_LINE> <DEDENT> elif args.impersonate: <NEW_LINE> <INDENT> if args.migrate: <NEW_LINE> <INDENT> proc_pid=self.client.conn.modules["pupwinutils.security"].create_proc_as_sid(args.impersonate) <NEW_LINE> migrate(self, proc_pid, keep=True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.client.impersonated_dupHandle=self.client.conn.modules["pupwinutils.security"].impersonate_sid_long_handle(args.impersonate, close=False) <NEW_LINE> <DEDENT> self.success("Sid %s impersonated !"%args.impersonate) <NEW_LINE> <DEDENT> elif args.rev2self: <NEW_LINE> <INDENT> self.client.conn.modules["pupwinutils.security"].rev2self() <NEW_LINE> self.client.impersonated_dupHandle=None <NEW_LINE> self.success("rev2self called") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.error("no option supplied")
list/impersonate process tokens
6259902bd10714528d69ee85
class Scale(object): <NEW_LINE> <INDENT> def __init__(self, attribute_code='weight', default_weight=None): <NEW_LINE> <INDENT> self.attribute = attribute_code <NEW_LINE> self.default_weight = default_weight <NEW_LINE> <DEDENT> def weigh_product(self, product): <NEW_LINE> <INDENT> weight = None <NEW_LINE> try: <NEW_LINE> <INDENT> weight = product.attribute_values.get( attribute__code=self.attribute).value <NEW_LINE> <DEDENT> except ObjectDoesNotExist: <NEW_LINE> <INDENT> if product.parent: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> weight = product.parent.attribute_values.get( attribute__code=self.attribute).value <NEW_LINE> <DEDENT> except ObjectDoesNotExist: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if weight is None: <NEW_LINE> <INDENT> if self.default_weight is None: <NEW_LINE> <INDENT> raise ValueError( "No attribute %s found for product %s" % ( self.attribute, product)) <NEW_LINE> <DEDENT> weight = self.default_weight <NEW_LINE> <DEDENT> return D(weight) if weight is not None else D('0.0') <NEW_LINE> <DEDENT> def weigh_basket(self, basket): <NEW_LINE> <INDENT> weight = D('0.0') <NEW_LINE> for line in basket.lines.all(): <NEW_LINE> <INDENT> weight += self.weigh_product(line.product) * line.quantity <NEW_LINE> <DEDENT> return weight
For calculating the weight of a product or basket
6259902b63f4b57ef008656b
class ImageExtracter(object): <NEW_LINE> <INDENT> def __init__(self, filename, interval=0): <NEW_LINE> <INDENT> self.__captor = cv2.VideoCapture(filename) <NEW_LINE> if not self.__captor.isOpened(): <NEW_LINE> <INDENT> raise ValueError(f'{colorama.Fore.RED}cannot open video {filename}') <NEW_LINE> <DEDENT> self.__eof = False <NEW_LINE> self.__currentFrameIndex = -1 <NEW_LINE> self.__interval = interval <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __next__(self): <NEW_LINE> <INDENT> if self.__eof: <NEW_LINE> <INDENT> raise StopIteration <NEW_LINE> <DEDENT> ret, frame = self.__captor.read() <NEW_LINE> if not ret: <NEW_LINE> <INDENT> self.__eof = True <NEW_LINE> raise StopIteration <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.__currentFrameIndex += 1 <NEW_LINE> return frame
图像提取器
6259902b50485f2cf55dbf6d
class Car: <NEW_LINE> <INDENT> NUMBER_OF_WHEELS = 4 <NEW_LINE> def __init__(self, name): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.distance = 0
A car description
6259902b73bcbd0ca4bcb284
class TestCheckpoint: <NEW_LINE> <INDENT> def test_with_return(self): <NEW_LINE> <INDENT> class TestClass(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.resume = False <NEW_LINE> <DEDENT> @checkpoint <NEW_LINE> def dont_wrap_me_bro(self): <NEW_LINE> <INDENT> return "I told you not to do this. Now look what happened." <NEW_LINE> <DEDENT> <DEDENT> with pytest.raises(ValueError) as exc: <NEW_LINE> <INDENT> TestClass().dont_wrap_me_bro() <NEW_LINE> <DEDENT> assert 'checkpointed functions may not return stuff' in str(exc.value)
Test the checkpoint() decorator.
6259902b66673b3332c313e2
class Correction: <NEW_LINE> <INDENT> def __init__(self, of): <NEW_LINE> <INDENT> self.of = of <NEW_LINE> <DEDENT> def correct(self, x): <NEW_LINE> <INDENT> return np.minimum(np.maximum(x, self.of.a), self.of.b)
Baseline mutation correction strategy - "sticks" the solution to domain boundaries
6259902bbe8e80087fbc006d
class SaleItem(models.Model): <NEW_LINE> <INDENT> name = models.TextField() <NEW_LINE> description = models.TextField(max_length=500) <NEW_LINE> low_price = models.DecimalField(max_digits=10, decimal_places=2) <NEW_LINE> high_price = models.DecimalField(max_digits=10, decimal_places=2) <NEW_LINE> artisan_name = models.ForeignKey(User) <NEW_LINE> area = models.ForeignKey(Area, null=True) <NEW_LINE> photo = models.TextField(null=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name
DESCRIPTION: Keeps track of the items sold by artisans at each area. NOTES: artisan - must be a registered user.
6259902b8c3a8732951f754b
class SeleniumCommandInfo(object): <NEW_LINE> <INDENT> swagger_types = { 'id': 'str', 'name': 'str', 'target': 'str', 'value': 'str', 'targets': 'list[TargetListData]' } <NEW_LINE> attribute_map = { 'id': 'id', 'name': 'name', 'target': 'target', 'value': 'value', 'targets': 'targets' } <NEW_LINE> def __init__(self, id=None, name=None, target=None, value=None, targets=None): <NEW_LINE> <INDENT> self._id = None <NEW_LINE> self._name = None <NEW_LINE> self._target = None <NEW_LINE> self._value = None <NEW_LINE> self._targets = None <NEW_LINE> self.discriminator = None <NEW_LINE> if id is not None: <NEW_LINE> <INDENT> self.id = id <NEW_LINE> <DEDENT> if name is not None: <NEW_LINE> <INDENT> self.name = name <NEW_LINE> <DEDENT> if target is not None: <NEW_LINE> <INDENT> self.target = target <NEW_LINE> <DEDENT> if value is not None: <NEW_LINE> <INDENT> self.value = value <NEW_LINE> <DEDENT> if targets is not None: <NEW_LINE> <INDENT> self.targets = targets <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def id(self): <NEW_LINE> <INDENT> return self._id <NEW_LINE> <DEDENT> @id.setter <NEW_LINE> def id(self, id): <NEW_LINE> <INDENT> self._id = id <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @name.setter <NEW_LINE> def name(self, name): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> <DEDENT> @property <NEW_LINE> def target(self): <NEW_LINE> <INDENT> return self._target <NEW_LINE> <DEDENT> @target.setter <NEW_LINE> def target(self, target): <NEW_LINE> <INDENT> self._target = target <NEW_LINE> <DEDENT> @property <NEW_LINE> def value(self): <NEW_LINE> <INDENT> return self._value <NEW_LINE> <DEDENT> @value.setter <NEW_LINE> def value(self, value): <NEW_LINE> <INDENT> self._value = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def targets(self): <NEW_LINE> <INDENT> return self._targets <NEW_LINE> <DEDENT> @targets.setter <NEW_LINE> def targets(self, targets): <NEW_LINE> <INDENT> self._targets = targets <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> if issubclass(SeleniumCommandInfo, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, SeleniumCommandInfo): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
6259902bd99f1b3c44d06697
class XegerError(Exception): <NEW_LINE> <INDENT> def __init__(self, value): <NEW_LINE> <INDENT> self.value = value <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return repr(self.value)
Exception type for reporting Xeger generation errors
6259902bc432627299fa3fe8
class RandomElastic: <NEW_LINE> <INDENT> def __init__(self,params): <NEW_LINE> <INDENT> self.params=params <NEW_LINE> self.last_grid=None <NEW_LINE> self.params_p=np.array([x[2] for x in self.params]) <NEW_LINE> self.params_p=self.params_p/np.sum(self.params_p) <NEW_LINE> <DEDENT> def get_params_random(self): <NEW_LINE> <INDENT> if len(self.params)<1: <NEW_LINE> <INDENT> return(-1,-1) <NEW_LINE> <DEDENT> elif len(self.params)==1: <NEW_LINE> <INDENT> return(self.params[0][0],self.params[0][1]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> i=np.random.choice(range(len(self.params)),p=self.params_p) <NEW_LINE> return(self.params[i][0],self.params[i][1]) <NEW_LINE> <DEDENT> <DEDENT> def update_last_grid(self,image): <NEW_LINE> <INDENT> N, C, H, W = image.data.shape <NEW_LINE> if self.last_grid is None or self.last_grid.data.shape!=torch.Size([N, H, W, 2]): <NEW_LINE> <INDENT> self.last_grid=grid(image.data.shape) <NEW_LINE> if image.is_cuda: <NEW_LINE> <INDENT> self.last_grid=self.last_grid.cuda() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __call__(self,image,gt_labels): <NEW_LINE> <INDENT> alpha,sigma=self.get_params_random() <NEW_LINE> if alpha<=0 or sigma<=0: <NEW_LINE> <INDENT> return(image,gt_labels) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> shape = image.data.shape <NEW_LINE> gkhs2=2*gaussian_kernel_half_size(sigma) <NEW_LINE> convshape=torch.Size([1,shape[1],shape[2]+gkhs2,shape[3]+gkhs2]) <NEW_LINE> dx=Variable(torch.Tensor(convshape).uniform_(-2/shape[2],2/shape[3]),requires_grad=False) <NEW_LINE> dy=Variable(torch.Tensor(convshape).uniform_(-2/shape[2],2/shape[3]),requires_grad=False) <NEW_LINE> fh=gaussian_filter_1d(sigma,True) <NEW_LINE> fv=gaussian_filter_1d(sigma,False) <NEW_LINE> if image.is_cuda: <NEW_LINE> <INDENT> dx=dx.cuda() <NEW_LINE> dy=dy.cuda() <NEW_LINE> fh=fh.cuda() <NEW_LINE> fv=fv.cuda() <NEW_LINE> <DEDENT> dx=torch.nn.functional.conv2d(dx, fh) <NEW_LINE> dx=torch.nn.functional.conv2d(dx, fv) <NEW_LINE> dx.mul_(alpha) <NEW_LINE> dy=torch.nn.functional.conv2d(dy, fh) <NEW_LINE> dy=torch.nn.functional.conv2d(dy, fv) <NEW_LINE> dy.mul_(alpha) <NEW_LINE> distortion=torch.cat([dx[0].unsqueeze(-1),dy[0].unsqueeze(-1)],-1) <NEW_LINE> self.update_last_grid(image) <NEW_LINE> grid=torch.add(self.last_grid,distortion) <NEW_LINE> reflect_grid(grid) <NEW_LINE> retimage=grid_sample(image, grid) <NEW_LINE> retgt_labels=grid_sample(gt_labels, grid) <NEW_LINE> return(retimage,retgt_labels)
Elastic deformation of images as described in [Simard2003] Simard, Steinkraus and Platt, "Best Practices for Convolutional Neural Networks applied to Visual Document Analysis", in Proc. of the International Conference on Document Analysis and Recognition, 2003. Copied from https://gist.github.com/chsasank/4d8f68caf01f041a6453e67fb30f8f5a
6259902b6e29344779b01644
class PageType: <NEW_LINE> <INDENT> FrontCover = "FrontCover" <NEW_LINE> InnerCover = "InnerCover" <NEW_LINE> Roundup = "Roundup" <NEW_LINE> Story = "Story" <NEW_LINE> Advertisement = "Advertisement" <NEW_LINE> Editorial = "Editorial" <NEW_LINE> Letters = "Letters" <NEW_LINE> Preview = "Preview" <NEW_LINE> BackCover = "BackCover" <NEW_LINE> Other = "Other" <NEW_LINE> Deleted = "Deleted"
These page info classes are exactly the same as the CIX scheme, since it's unique
6259902b6fece00bbaccc9a3
class SiteAnnotationForm(forms.Form): <NEW_LINE> <INDENT> def clean(self): <NEW_LINE> <INDENT> return self.cleaned_data
Form asking the curator to fill the information regarding each site. In particular, the user can: - visualize again site information, including chromosome, - toggle the graphical view (off by default) - edit the qualitative values - specify which techniques were used to determine this site - define the site as repressed, activated or whether the effect of TF on the site is unknown (not-determined) Each site and its set of fields that can be edited are represented as a form (one form per site instance). The abstraction to work multiple forms in one page is achieved via Django FormSets (https://docs.djangoproject.com/en/1.6/topics/forms/formsets/).
6259902b56b00c62f0fb38b5
class FederatedType(Type): <NEW_LINE> <INDENT> def __init__(self, member, placement, all_equal=False): <NEW_LINE> <INDENT> if not isinstance(placement, placement_literals.PlacementLiteral): <NEW_LINE> <INDENT> raise NotImplementedError( 'At the moment, only specifying placement literals is implemented.') <NEW_LINE> <DEDENT> py_typecheck.check_type(all_equal, bool) <NEW_LINE> self._member = to_type(member) <NEW_LINE> self._placement = placement <NEW_LINE> self._all_equal = all_equal <NEW_LINE> <DEDENT> @property <NEW_LINE> def member(self): <NEW_LINE> <INDENT> return self._member <NEW_LINE> <DEDENT> @property <NEW_LINE> def placement(self): <NEW_LINE> <INDENT> return self._placement <NEW_LINE> <DEDENT> @property <NEW_LINE> def all_equal(self): <NEW_LINE> <INDENT> return self._all_equal <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'FederatedType({}, {}, {})'.format( repr(self._member), repr(self._placement), repr(self._all_equal)) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> if self._all_equal: <NEW_LINE> <INDENT> return '{}@{}'.format(str(self._member), str(self._placement)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return '{{{}}}@{}'.format(str(self._member), str(self._placement)) <NEW_LINE> <DEDENT> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return (isinstance(other, FederatedType) and self._member == other.member and self._placement == other.placement and self._all_equal == other.all_equal)
An implementation of `tff.Type` representing federated types in TFF.
6259902b5e10d32532ce40fe
class TransformPoincareDisk(Transform): <NEW_LINE> <INDENT> def __init__(self, base, R=1.): <NEW_LINE> <INDENT> super(TransformPoincareDisk, self).__init__(base) <NEW_LINE> self.R = R <NEW_LINE> <DEDENT> def to_base(self, ndata): <NEW_LINE> <INDENT> Lab = ndata.copy() <NEW_LINE> Lab[:, 1:] = 0 <NEW_LINE> x = ndata[:, 1] <NEW_LINE> y = ndata[:, 2] <NEW_LINE> r = np.sqrt(x**2 + y**2) <NEW_LINE> for i in range(np.shape(Lab)[0]): <NEW_LINE> <INDENT> if r[i] > 0: <NEW_LINE> <INDENT> Lab[i, 1:] = ndata[i, 1:] * 2 * self.R * np.arctanh(r[i]) / r[i] <NEW_LINE> <DEDENT> <DEDENT> return Lab <NEW_LINE> <DEDENT> def from_base(self, ndata): <NEW_LINE> <INDENT> Lxy = ndata.copy() <NEW_LINE> Lxy[:, 1:] = 0 <NEW_LINE> a = ndata[:, 1] <NEW_LINE> b = ndata[:, 2] <NEW_LINE> C = np.sqrt(a**2 + b**2) <NEW_LINE> for i in range(np.shape(Lxy)[0]): <NEW_LINE> <INDENT> if C[i] > 0: <NEW_LINE> <INDENT> Lxy[i, 1:] = ndata[i, 1:] * np.tanh(C[i] / (2 * self.R)) / C[i] <NEW_LINE> <DEDENT> <DEDENT> return Lxy <NEW_LINE> <DEDENT> def jacobian_base(self, data): <NEW_LINE> <INDENT> Lab = data.get_flattened(self.base) <NEW_LINE> a = Lab[:, 1] <NEW_LINE> b = Lab[:, 2] <NEW_LINE> C = np.sqrt(a**2 + b**2) <NEW_LINE> tanhC2R = np.tanh(C / (2. * self.R)) <NEW_LINE> tanhC2C = misc.safe_div(tanhC2R, C) <NEW_LINE> dCda = misc.safe_div(a, C) <NEW_LINE> dCdb = misc.safe_div(b, C) <NEW_LINE> dtanhdC = misc.safe_div(C / (2. * self.R) * (1 - tanhC2R**2) - tanhC2R, C**2) <NEW_LINE> jac = self.empty_matrix(Lab) <NEW_LINE> for i in range(np.shape(jac)[0]): <NEW_LINE> <INDENT> jac[i, 0, 0] = 1 <NEW_LINE> if C[i] == 0: <NEW_LINE> <INDENT> jac[i, 1, 1] = .5 <NEW_LINE> jac[i, 2, 2] = .5 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> jac[i, 1, 1] = tanhC2C[i] + a[i] * dtanhdC[i] * dCda[i] <NEW_LINE> jac[i, 1, 2] = a[i] * dtanhdC[i] * dCdb[i] <NEW_LINE> jac[i, 2, 1] = b[i] * dtanhdC[i] * dCda[i] <NEW_LINE> jac[i, 2, 2] = tanhC2C[i] + b[i] * dtanhdC[i] * dCdb[i] <NEW_LINE> <DEDENT> <DEDENT> return jac
Transform from Cartesian coordinates to Poincare disk coordinates. The coordinate transform only changes the radius (chroma, typically), and does so in a way that preserves the radial distance with respect to the Euclidean metric and the Poincare disk metric in the source and target spaces, respectively.
6259902b9b70327d1c57fd78
class Obstacle: <NEW_LINE> <INDENT> def __init__(self, screen): <NEW_LINE> <INDENT> self.change = 4 <NEW_LINE> self.y = random.randrange(0, 560) <NEW_LINE> self.x = 999 <NEW_LINE> self.img = pygame.image.load(os.path.join("resources", "Obstacle.png")) <NEW_LINE> self.size = self.img.get_size() <NEW_LINE> self.screen = screen <NEW_LINE> self.perim = [] <NEW_LINE> <DEDENT> def move(self): <NEW_LINE> <INDENT> self.x -= self.change <NEW_LINE> if self.x <= 1: <NEW_LINE> <INDENT> self.x = 999 <NEW_LINE> self.y = random.randrange(0, 560) <NEW_LINE> <DEDENT> <DEDENT> def blit(self): <NEW_LINE> <INDENT> self.corners = [(self.x, self.y), (self.x, self.y + self.size[1]), (self.x + self.size[0], self.y + self.size[1]), (self.x + self.size[0], self.y)] <NEW_LINE> self.screen.blit(self.img, (self.x, self.y))
Contains all the functions and variables specific to the boxes
6259902b287bf620b6272be7
class AuthenticationRequired(ElasticException): <NEW_LINE> <INDENT> pass
Cluster requires authentication.
6259902b711fe17d825e1495
class UserChangeForm(forms.ModelForm): <NEW_LINE> <INDENT> password = ReadOnlyPasswordHashField() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = User <NEW_LINE> fields = ('username', 'email', 'first_name', 'last_name', 'password', 'is_active', 'is_superuser') <NEW_LINE> <DEDENT> def clean_password(self): <NEW_LINE> <INDENT> return self.initial["password"]
A form for updating users. Includes all the fields on the user, but replaces the password field with admin's password hash display field.
6259902b66673b3332c313e6
class FileStorage: <NEW_LINE> <INDENT> __file_path = "file.json" <NEW_LINE> __objects = {} <NEW_LINE> def all(self, cls=None): <NEW_LINE> <INDENT> state_obj = {} <NEW_LINE> if cls is None: <NEW_LINE> <INDENT> return self.__objects <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for k, v in self.__objects.items(): <NEW_LINE> <INDENT> if v.__class__ == cls: <NEW_LINE> <INDENT> state_obj[k] = v <NEW_LINE> <DEDENT> <DEDENT> return state_obj <NEW_LINE> <DEDENT> <DEDENT> def new(self, obj): <NEW_LINE> <INDENT> if obj: <NEW_LINE> <INDENT> key = "{}.{}".format(type(obj).__name__, obj.id) <NEW_LINE> self.__objects[key] = obj <NEW_LINE> <DEDENT> <DEDENT> def save(self): <NEW_LINE> <INDENT> my_dict = {} <NEW_LINE> for key, value in self.__objects.items(): <NEW_LINE> <INDENT> my_dict[key] = value.to_dict() <NEW_LINE> <DEDENT> with open(self.__file_path, 'w', encoding="UTF-8") as f: <NEW_LINE> <INDENT> json.dump(my_dict, f) <NEW_LINE> <DEDENT> <DEDENT> def reload(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(self.__file_path, 'r', encoding="UTF-8") as f: <NEW_LINE> <INDENT> for key, value in (json.load(f)).items(): <NEW_LINE> <INDENT> value = eval(value["__class__"])(**value) <NEW_LINE> self.__objects[key] = value <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except FileNotFoundError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def delete(self, obj=None): <NEW_LINE> <INDENT> my_dict = {} <NEW_LINE> for k, v in self.__objects.items(): <NEW_LINE> <INDENT> if v is obj: <NEW_LINE> <INDENT> del self.__objects[k] <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> with open(self.__file_path, 'w', encoding="UTF-8") as f: <NEW_LINE> <INDENT> json.dump(my_dict, f) <NEW_LINE> <DEDENT> <DEDENT> def close(self): <NEW_LINE> <INDENT> self.reload()
This class serializes instances to a JSON file and deserializes JSON file to instances Attributes: __file_path: path to the JSON file __objects: objects will be stored
6259902bbf627c535bcb24ae
class CustomerRequirement(models.Model): <NEW_LINE> <INDENT> customer = models.ForeignKey(Customer,verbose_name=_('Customer')) <NEW_LINE> requirement = models.ForeignKey(Requirement,verbose_name=_('Requirement')) <NEW_LINE> role = models.ForeignKey(DanceRole,null=True,blank=True,verbose_name=_('Dance role'),help_text=_('Role must be specified only for requirements for which roles are enforced.')) <NEW_LINE> met = models.BooleanField(_('Meets Requirement'),default=True,help_text=_('If unchecked, then the customer explicitly does not meet the requirement, regardless of whether they meet its parameters.')) <NEW_LINE> comments = models.TextField(_('Comments/Notes'),null=True,blank=True) <NEW_LINE> submissionDate = models.DateTimeField(_('Submission date'),auto_now_add=True) <NEW_LINE> modifiedDate = models.DateTimeField(_('Last modified date'),auto_now=True) <NEW_LINE> def clean(self): <NEW_LINE> <INDENT> if self.requirement.roleEnforced and not self.role: <NEW_LINE> <INDENT> raise ValidationError(_('Since roles are enforced for this requirement, you must specify the customer\'s dance role.')) <NEW_LINE> <DEDENT> <DEDENT> class Meta: <NEW_LINE> <INDENT> unique_together = ('customer','requirement','role') <NEW_LINE> verbose_name = _('Customer-level requirement record') <NEW_LINE> verbose_name_plural = _('Customer-level requirement records')
This class allows for override of requirements on a per-customer basis.
6259902bbe8e80087fbc0071
class ImageResizingFilter(ImageFilter): <NEW_LINE> <INDENT> _log_attributes = ('size', 'maintain_aspect_ratio', 'resample') <NEW_LINE> VERSION = '1.0' <NEW_LINE> def __init__(self, size, maintain_aspect_ratio=False, resample='bicubic'): <NEW_LINE> <INDENT> self.size = size <NEW_LINE> self.maintain_aspect_ratio = maintain_aspect_ratio <NEW_LINE> resampling_mapping = { 'nearest': Image.NEAREST, 'bilinear': Image.BILINEAR, 'bicubic': Image.BICUBIC, 'lanczos': Image.LANCZOS, 'box': Image.BOX, 'hamming': Image.HAMMING, } <NEW_LINE> if resample.lower() not in resampling_mapping.keys(): <NEW_LINE> <INDENT> raise ValueError( "Unknown resampling method '{}'. Allowed values are '{}'" .format(resample, "', '".join(resampling_mapping.keys()))) <NEW_LINE> <DEDENT> self.resample = resampling_mapping[resample] <NEW_LINE> super().__init__() <NEW_LINE> <DEDENT> def _filter(self, stim): <NEW_LINE> <INDENT> pillow_img = Image.fromarray(stim.data) <NEW_LINE> if not self.maintain_aspect_ratio: <NEW_LINE> <INDENT> new_img = np.array( pillow_img.resize(self.size, resample=self.resample)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> orig_size = pillow_img.size <NEW_LINE> ratio = max(self.size) / max(orig_size) <NEW_LINE> inter_size = (np.array(orig_size) * ratio).astype(np.int32) <NEW_LINE> inter_img = pillow_img.resize(inter_size, resample=self.resample) <NEW_LINE> new_img = Image.new('RGB', self.size) <NEW_LINE> upper_left = ( (self.size[0] - inter_size[0]) // 2, (self.size[1] - inter_size[1]) // 2) <NEW_LINE> new_img.paste(inter_img, box=upper_left) <NEW_LINE> new_img = np.array(new_img) <NEW_LINE> <DEDENT> return ImageStim(stim.filename, data=new_img)
Resizes an image, while optionally maintaining aspect ratio. Args: size (tuple of two ints): new size of the image. maintain_aspect_ratio (boolean): if true, resize the image while maintaining aspect ratio, and pad the rest with zero values. Otherwise, potentially distort the image during resizing to fit the new size. resample str: resampling method. One of 'nearest', 'bilinear', 'bicubic', 'lanczos', 'box', and 'hamming'. See https://pillow.readthedocs.io/en/5.1.x/handbook/concepts.html#concept-filters for more information.
6259902b3eb6a72ae038b65c
@inside_spirv_testsuite('SpirvOptFlags') <NEW_LINE> class TestLoopPeelingThresholdArgsInvalidNumber(expect.ErrorMessageSubstr): <NEW_LINE> <INDENT> spirv_args = ['--loop-peeling-threshold=a10f'] <NEW_LINE> expected_error_substr = 'must have a positive integer argument'
Tests invalid arguments to --loop-peeling-threshold.
6259902bec188e330fdf988b
class HelloViewSet(viewsets.ViewSet): <NEW_LINE> <INDENT> serializer_class = serializers.HelloSerializer <NEW_LINE> def list(self, request): <NEW_LINE> <INDENT> a_viewset = [ 'Uses actions(list, create, retrieve, update, partial_update)', 'automatically maps to URLs using routers', 'provides more functionality with less code' ] <NEW_LINE> return Response({'message':'Hello!', 'a_viewset':a_viewset}) <NEW_LINE> <DEDENT> def create(self, request): <NEW_LINE> <INDENT> serializer = serializers.HelloSerializer(data=request.data) <NEW_LINE> if serializer.is_valid(): <NEW_LINE> <INDENT> name = serializer.data.get('name') <NEW_LINE> message = 'Hello {0}'.format(name) <NEW_LINE> return Response({'message':message}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> <DEDENT> def retrieve(self, request, pk=None): <NEW_LINE> <INDENT> return Response({'http_method':'GET'}) <NEW_LINE> <DEDENT> def update(self, request, pk=None): <NEW_LINE> <INDENT> return Response({'http_method':'PUT'}) <NEW_LINE> <DEDENT> def partial_update(self, request, pk=None): <NEW_LINE> <INDENT> return Response({'http_method':'PATCH'}) <NEW_LINE> <DEDENT> def destroy(self, request, pk=None): <NEW_LINE> <INDENT> return Response({'http_method':'DELETE'})
Test API ViewSet
6259902b711fe17d825e1496
class Workspace: <NEW_LINE> <INDENT> def __init__(self, params_file: pathlib.Path) -> None: <NEW_LINE> <INDENT> params = json.loads(params_file.read_text(encoding='utf-8')) <NEW_LINE> workspace_name = 'phst_rules_elisp' <NEW_LINE> srcs = [] <NEW_LINE> tempdir = pathlib.Path(tempfile.mkdtemp(prefix='pylint-')) <NEW_LINE> for file in params['srcs']: <NEW_LINE> <INDENT> dest = tempdir / workspace_name / file['rel'] <NEW_LINE> dest.parent.mkdir(parents=True, exist_ok=True) <NEW_LINE> shutil.copyfile(file['src'], dest) <NEW_LINE> if not file['ext'] and not dest.name.endswith('_pb2.py'): <NEW_LINE> <INDENT> srcs.append(dest) <NEW_LINE> <DEDENT> <DEDENT> if not srcs: <NEW_LINE> <INDENT> raise FileNotFoundError('no source files found') <NEW_LINE> <DEDENT> for dirpath, _, _ in os.walk(tempdir): <NEW_LINE> <INDENT> dirpath = pathlib.Path(dirpath) <NEW_LINE> if dirpath != tempdir: <NEW_LINE> <INDENT> (dirpath / '__init__.py').touch() <NEW_LINE> <DEDENT> <DEDENT> self.srcs = frozenset(srcs) <NEW_LINE> self.path = [str(tempdir)] + [str(tempdir / d) for d in params['path']] <NEW_LINE> self.tempdir = tempdir <NEW_LINE> self._output = pathlib.Path(params['out']) <NEW_LINE> <DEDENT> def success(self) -> None: <NEW_LINE> <INDENT> shutil.rmtree(self.tempdir) <NEW_LINE> self.tempdir = None <NEW_LINE> self._output.touch()
Represents a temporary workspace for Pylint and Pytype.
6259902b8a43f66fc4bf317c
class Topic(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.TopicId = None <NEW_LINE> self.TopicName = None <NEW_LINE> self.ProductId = None <NEW_LINE> self.MsgLife = None <NEW_LINE> self.MsgSize = None <NEW_LINE> self.MsgCount = None <NEW_LINE> self.Deleted = None <NEW_LINE> self.Path = None <NEW_LINE> self.CreateTime = None <NEW_LINE> self.UpdateTime = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.TopicId = params.get("TopicId") <NEW_LINE> self.TopicName = params.get("TopicName") <NEW_LINE> self.ProductId = params.get("ProductId") <NEW_LINE> self.MsgLife = params.get("MsgLife") <NEW_LINE> self.MsgSize = params.get("MsgSize") <NEW_LINE> self.MsgCount = params.get("MsgCount") <NEW_LINE> self.Deleted = params.get("Deleted") <NEW_LINE> self.Path = params.get("Path") <NEW_LINE> self.CreateTime = params.get("CreateTime") <NEW_LINE> self.UpdateTime = params.get("UpdateTime")
Topic
6259902b796e427e5384f775
class ProxyViewGetOnlyTest(APITestCase): <NEW_LINE> <INDENT> class TestView(ProxyViewGetOnly): <NEW_LINE> <INDENT> source = 'api/test' <NEW_LINE> <DEDENT> def setUp(self): <NEW_LINE> <INDENT> self.view = self.TestView() <NEW_LINE> <DEDENT> def test_blocked_methods(self): <NEW_LINE> <INDENT> response = self.view.delete(request=None) <NEW_LINE> self.assertEqual(response.status_code, HTTP_405_METHOD_NOT_ALLOWED) <NEW_LINE> response = self.view.options(request=None) <NEW_LINE> self.assertEqual(response.status_code, HTTP_405_METHOD_NOT_ALLOWED) <NEW_LINE> response = self.view.patch(request=None) <NEW_LINE> self.assertEqual(response.status_code, HTTP_405_METHOD_NOT_ALLOWED) <NEW_LINE> response = self.view.post(request=None) <NEW_LINE> self.assertEqual(response.status_code, HTTP_405_METHOD_NOT_ALLOWED) <NEW_LINE> response = self.view.put(request=None) <NEW_LINE> self.assertEqual(response.status_code, HTTP_405_METHOD_NOT_ALLOWED) <NEW_LINE> <DEDENT> def test_allowed_method(self): <NEW_LINE> <INDENT> with self.assertRaises(AttributeError): <NEW_LINE> <INDENT> self.view.get(request=None)
Test the HTTP methods of the ProxyViewGetOnly view.
6259902b6fece00bbaccc9a8
class TimeoutException(Exception): <NEW_LINE> <INDENT> pass
It took too long to compile and execute.
6259902b30c21e258be99805
class CheckBox(ToggleButtonBehavior, Widget): <NEW_LINE> <INDENT> def _get_active(self): <NEW_LINE> <INDENT> return self.state == 'down' <NEW_LINE> <DEDENT> def _set_active(self, value): <NEW_LINE> <INDENT> self.state = 'down' if value else 'normal' <NEW_LINE> <DEDENT> active = AliasProperty( _get_active, _set_active, bind=('state', ), cache=True) <NEW_LINE> background_checkbox_normal = StringProperty( 'atlas://data/images/defaulttheme/checkbox_off') <NEW_LINE> background_checkbox_down = StringProperty( 'atlas://data/images/defaulttheme/checkbox_on') <NEW_LINE> background_checkbox_disabled_normal = StringProperty( 'atlas://data/images/defaulttheme/checkbox_disabled_off') <NEW_LINE> background_checkbox_disabled_down = StringProperty( 'atlas://data/images/defaulttheme/checkbox_disabled_on') <NEW_LINE> background_radio_normal = StringProperty( 'atlas://data/images/defaulttheme/checkbox_radio_off') <NEW_LINE> background_radio_down = StringProperty( 'atlas://data/images/defaulttheme/checkbox_radio_on') <NEW_LINE> background_radio_disabled_normal = StringProperty( 'atlas://data/images/defaulttheme/checkbox_radio_disabled_off') <NEW_LINE> background_radio_disabled_down = StringProperty( 'atlas://data/images/defaulttheme/checkbox_radio_disabled_on') <NEW_LINE> color = ListProperty([1, 1, 1, 1]) <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.fbind('state', self._on_state) <NEW_LINE> super(CheckBox, self).__init__(**kwargs) <NEW_LINE> <DEDENT> def _on_state(self, instance, value): <NEW_LINE> <INDENT> if self.group and self.state == 'down': <NEW_LINE> <INDENT> self._release_group(self) <NEW_LINE> <DEDENT> <DEDENT> def on_group(self, *largs): <NEW_LINE> <INDENT> super(CheckBox, self).on_group(*largs) <NEW_LINE> if self.active: <NEW_LINE> <INDENT> self._release_group(self)
CheckBox class, see module documentation for more information.
6259902bd164cc6175821f6b
@ns_function.route('/') <NEW_LINE> @ns_function.doc(security='apikey', responses=default_responses) <NEW_LINE> class Functions(Resource): <NEW_LINE> <INDENT> @accept('application/vnd.mycodo.v1+json') <NEW_LINE> @ns_function.marshal_with(function_list_fields) <NEW_LINE> @flask_login.login_required <NEW_LINE> def get(self): <NEW_LINE> <INDENT> if not utils_general.user_has_permission('view_settings'): <NEW_LINE> <INDENT> abort(403) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> list_data = get_from_db(FunctionSchema, CustomController) <NEW_LINE> list_channels = get_from_db(FunctionChannelSchema, FunctionChannel) <NEW_LINE> if list_data: <NEW_LINE> <INDENT> return {'function settings': list_data, 'function channels': list_channels}, 200 <NEW_LINE> <DEDENT> <DEDENT> except Exception: <NEW_LINE> <INDENT> abort(500, message='An exception occurred', error=traceback.format_exc())
Function information.
6259902bd99f1b3c44d0669d
class LIST_OT_NewItem(bpy.types.Operator): <NEW_LINE> <INDENT> bl_idname = "my_list.new_item" <NEW_LINE> bl_label = "Add a new item" <NEW_LINE> def execute(self, context): <NEW_LINE> <INDENT> context.scene.my_list.add() <NEW_LINE> return{'FINISHED'}
Add a new item to the list
6259902b6fece00bbaccc9a9
class RectangularRoom(object): <NEW_LINE> <INDENT> def __init__(self, width, height): <NEW_LINE> <INDENT> self.width = width <NEW_LINE> self.height = height <NEW_LINE> self.numTilesCleaned = 0 <NEW_LINE> self.tiles = [[False for j in range(width)] for i in range(height)] <NEW_LINE> self.numCleanedTiles = 0 <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> import copy <NEW_LINE> return str(copy.deepcopy(self.tiles)) <NEW_LINE> <DEDENT> def cleanTileAtPosition(self, pos): <NEW_LINE> <INDENT> col = math.floor(pos.getX()) <NEW_LINE> row = math.floor(pos.getY()) <NEW_LINE> if not self.isTileCleaned(col,row): <NEW_LINE> <INDENT> self.tiles[row][col] = True <NEW_LINE> self.numCleanedTiles += 1 <NEW_LINE> <DEDENT> <DEDENT> def isTileCleaned(self, m, n): <NEW_LINE> <INDENT> return self.tiles[n][m] == True <NEW_LINE> <DEDENT> def getNumTiles(self): <NEW_LINE> <INDENT> return self.width * self.height <NEW_LINE> <DEDENT> def getNumCleanedTiles(self): <NEW_LINE> <INDENT> return self.numCleanedTiles <NEW_LINE> <DEDENT> def getRandomPosition(self): <NEW_LINE> <INDENT> return Position(random.random() * self.width, random.random() * self.height) <NEW_LINE> <DEDENT> def isPositionInRoom(self, pos): <NEW_LINE> <INDENT> x = pos.getX() <NEW_LINE> y = pos.getY() <NEW_LINE> return 0<=x<self.width and 0<=y<self.height
A RectangularRoom represents a rectangular region containing clean or dirty tiles. A room has a width and a height and contains (width * height) tiles. At any particular time, each of these tiles is either clean or dirty.
6259902bd53ae8145f91945e
class WaitForMsgState(smach.State): <NEW_LINE> <INDENT> def __init__(self, topic, msg_type, msg_cb=None, output_keys=None, latch=False, timeout=None, u_execute=None, outcomes=['succeeded','aborted','preempted']): <NEW_LINE> <INDENT> if output_keys is None: <NEW_LINE> <INDENT> output_keys = [] <NEW_LINE> <DEDENT> smach.State.__init__(self, outcomes=outcomes, output_keys=output_keys) <NEW_LINE> self.latch = latch <NEW_LINE> self.timeout = timeout <NEW_LINE> self.mutex = threading.Lock() <NEW_LINE> self.msg = None <NEW_LINE> self.msg_cb = msg_cb <NEW_LINE> self.subscriber = rospy.Subscriber(topic, msg_type, self._callback, queue_size=1) <NEW_LINE> <DEDENT> def _callback(self, msg): <NEW_LINE> <INDENT> self.mutex.acquire() <NEW_LINE> self.msg = msg <NEW_LINE> self.mutex.release() <NEW_LINE> <DEDENT> def waitForMsg(self): <NEW_LINE> <INDENT> rospy.loginfo('Waiting for message...') <NEW_LINE> if self.timeout is not None: <NEW_LINE> <INDENT> timeout_time = rospy.Time.now() + rospy.Duration.from_sec(self.timeout) <NEW_LINE> <DEDENT> while self.timeout is None or rospy.Time.now() < timeout_time: <NEW_LINE> <INDENT> self.mutex.acquire() <NEW_LINE> if self.msg is not None: <NEW_LINE> <INDENT> rospy.loginfo('Got message.') <NEW_LINE> message = self.msg <NEW_LINE> if not self.latch: <NEW_LINE> <INDENT> self.msg = None <NEW_LINE> <DEDENT> self.mutex.release() <NEW_LINE> return message <NEW_LINE> <DEDENT> self.mutex.release() <NEW_LINE> if self.preempt_requested(): <NEW_LINE> <INDENT> self.service_preempt() <NEW_LINE> rospy.loginfo('waitForMsg is preempted!') <NEW_LINE> return 'preempted' <NEW_LINE> <DEDENT> rospy.sleep(.1) <NEW_LINE> <DEDENT> rospy.loginfo('Timeout on waiting for message!') <NEW_LINE> return None <NEW_LINE> <DEDENT> def execute(self, ud): <NEW_LINE> <INDENT> msg = self.waitForMsg() <NEW_LINE> if msg is not None: <NEW_LINE> <INDENT> if msg == 'preempted': <NEW_LINE> <INDENT> return 'preempted' <NEW_LINE> <DEDENT> if self.msg_cb is not None: <NEW_LINE> <INDENT> cb_result = self.msg_cb(msg, ud) <NEW_LINE> if cb_result is not None: <NEW_LINE> <INDENT> return cb_result <NEW_LINE> <DEDENT> <DEDENT> return 'succeeded' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 'aborted'
This class acts as a generic message listener with blocking, timeout, latch and flexible usage. It is meant to be extended with a case specific class that initializes this one appropriately and contains the msg_cb (or overrides execute if really needed). Its waitForMsg method implements the core functionality: waiting for the message, returning the message itself or None on timeout. Its execute method wraps the waitForMsg and returns succeeded or aborted, depending on the returned message beeing existent or None. Additionally, in the successfull case, the msg_cb, if given, will be called with the message and the userdata, so that a self defined method can convert message data to smach userdata. Those userdata fields have to be passed via 'output_keys'. If the state outcome should depend on the message content, the msg_cb can dictate the outcome: If msg_cb returns a value it should be one of the outcomes. If msg_cb is not existing, execute will behave as explained above. If thats still not enough, execute() might be overridden. latch: If True waitForMsg will return the last received message, so one message might be returned indefinite times. timeout: Seconds to wait for a message, defaults to None, disabling timeout output_keys: Userdata keys that the message callback needs to write to. Obtained from: https://github.com/felix-kolbe/uashh-rvl-ros-pkg/blob/29f03b13b490c9a477f41e047387443bdbea6e16/uashh_smach/src/util.py#L64
6259902b50485f2cf55dbf76
class Admin2OfSchool(KLPDetailAPIView): <NEW_LINE> <INDENT> serializer_class = BoundaryWithParentSerializer <NEW_LINE> bbox_filter_field = 'boundarycoord__coord' <NEW_LINE> def get_object(self): <NEW_LINE> <INDENT> school_id = self.kwargs.get('pk') <NEW_LINE> school = get_object_or_404(School.objects.all(), id=school_id) <NEW_LINE> return SchoolDetails.objects.get(school_id=school.id).admin2
Returns the block/project for the given school
6259902b66673b3332c313ea
class EditorController: <NEW_LINE> <INDENT> def __init__(self, model, x, y, w, h, painter): <NEW_LINE> <INDENT> self.model = model <NEW_LINE> self.model.set_port(x, y, w, h, painter) <NEW_LINE> self.active_state = ActiveStateContainer(self.model) <NEW_LINE> <DEDENT> def change_state(self, new_state): <NEW_LINE> <INDENT> self.active_state.change_state(new_state) <NEW_LINE> <DEDENT> def set_object_type(self, object): <NEW_LINE> <INDENT> self.model.set_object_type(object) <NEW_LINE> <DEDENT> def set_pen_props(self, pen_color, pen_width): <NEW_LINE> <INDENT> self.model.set_pen_props(pen_color, pen_width) <NEW_LINE> <DEDENT> def set_brush_prop(self, brush_prop): <NEW_LINE> <INDENT> self.model.set_brush_prop(brush_prop) <NEW_LINE> <DEDENT> def mouse_clicked(self, x, y): <NEW_LINE> <INDENT> self.active_state.mouse_clicked(x, y) <NEW_LINE> <DEDENT> def mouse_realised(self, x, y): <NEW_LINE> <INDENT> self.active_state.mouse_realised(x, y) <NEW_LINE> <DEDENT> def mouse_move(self, x, y): <NEW_LINE> <INDENT> self.active_state.mouse_move(x, y) <NEW_LINE> <DEDENT> def ctrl_on(self): <NEW_LINE> <INDENT> self.active_state.ctrl_on() <NEW_LINE> <DEDENT> def ctrl_off(self): <NEW_LINE> <INDENT> self.active_state.ctrl_off() <NEW_LINE> <DEDENT> def group(self): <NEW_LINE> <INDENT> self.model.group() <NEW_LINE> <DEDENT> def ungroup(self): <NEW_LINE> <INDENT> self.model.ungroup() <NEW_LINE> <DEDENT> def ungroup_state(self): <NEW_LINE> <INDENT> self.active_state.ungroup_state() <NEW_LINE> <DEDENT> def clear(self): <NEW_LINE> <INDENT> self.model.clear() <NEW_LINE> <DEDENT> def clear_obj(self): <NEW_LINE> <INDENT> self.model.clear_obj()
Класс контроллер
6259902b21a7993f00c66f78
class Board(EntityBase, EntityFactoryBase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def from_json(cls, json_obj): <NEW_LINE> <INDENT> board = Board() <NEW_LINE> board.id = json_obj['id'] <NEW_LINE> board.name = json_obj['name'] <NEW_LINE> board.description = json_obj.get('desc','') <NEW_LINE> board.closed = json_obj['closed'] <NEW_LINE> board.url = json_obj['url'] <NEW_LINE> return board
Class representing a Trello board entity.
6259902b30c21e258be99806
class MouseEnterCallback(PointerXYCallback): <NEW_LINE> <INDENT> on_events = ['mouseenter']
Returns the mouse x/y-position on mouseenter event, i.e. when mouse enters the plot canvas.
6259902b8a349b6b43687234
@dataclass <NEW_LINE> class TransformerStd: <NEW_LINE> <INDENT> std_type: str <NEW_LINE> name: str <NEW_LINE> parallel: int <NEW_LINE> def update_pandapower( self, net: pandapowerNet, source: str, target: str, ): <NEW_LINE> <INDENT> hv_bus = pp.get_element_index(net, "bus", source) <NEW_LINE> lv_bus = pp.get_element_index(net, "bus", target) <NEW_LINE> pp.create_transformer( net, name=self.name, hv_bus=hv_bus, lv_bus=lv_bus, std_type=self.std_type, parallel=self.parallel, )
Essential transformer parameters.
6259902b6fece00bbaccc9aa
class PacketPokerAnteRequest(PacketPokerAnte): <NEW_LINE> <INDENT> pass
=========== ======================================================================================================================================================================================================= Semantics the player "serial" is required to pay the an ante of "amount" for game"game_id". Direction server => client Context a :class:`PACKET_POKER_POSITION <pokerpackets.networkpackets.PacketPokerPosition>` packet is sent by the server before this packet. The answer may be a :class:`PACKET_POKER_SIT_OUT <pokerpackets.networkpackets.PacketPokerSitOut>` (to refuse to pay the ante), :class:`PACKET_POKER_ANTE <pokerpackets.networkpackets.PacketPokerAnte>` (to pay the ante). amount amount to pay for the ante. serial integer uniquely identifying a player. game_id integer uniquely identifying a game. =========== =======================================================================================================================================================================================================
6259902be76e3b2f99fd9a08
class TemplateFormatter: <NEW_LINE> <INDENT> def __init__(self, template, **kwargs): <NEW_LINE> <INDENT> self.template = template <NEW_LINE> self.context_getters = { "host": lambda _: platform.node(), } <NEW_LINE> self.context_getters.update(kwargs) <NEW_LINE> <DEDENT> def make_context(self, metric_name): <NEW_LINE> <INDENT> return {key: value(metric_name) for key, value in self.context_getters.items()} <NEW_LINE> <DEDENT> def __call__(self, name): <NEW_LINE> <INDENT> context = self.make_context(name) <NEW_LINE> return self.template.format(name=name, **context)
Formatter based on a template string :param template: A template string that will be rendered for each metric Additionnal keyword arguments must be callable, they will be called during rendering with the metric name and should return a string. The template must use the modern python formatting syntax, but does not support ordered placeholders. The formatting data will consist of the result of the functions given during instanciation, plus special variables: * name: The name of the metric * host: The system's node name Consider the following example: >>> formatter = TemplateFormatter("systems.{host}.worker{worker}.{name}", worker=get_worker_id) On a machine named *foobar* and assuming a *get_worker_id* function that return an id, the metric "processing_time" would be formatted like "systems.foobar.worker3.processing_time".
6259902b3eb6a72ae038b660
class MirraApp(main.App): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.caption = "mirra example complex" <NEW_LINE> self.size = 640, 480 <NEW_LINE> self.pos = 100,100 <NEW_LINE> self.fullScreen = 0 <NEW_LINE> self.frameRate = 15 <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> self.text = Text('dummy text', 20, 20, 99, 'timesroman', 10) <NEW_LINE> self.circle = Circle(350, 350, 3, 200, (0.5, 0.1, 0)) <NEW_LINE> self.circle.blend = 0.3 <NEW_LINE> self.circle.interactiveState = 2 <NEW_LINE> <DEDENT> def step(self): <NEW_LINE> <INDENT> w = self.size[0] <NEW_LINE> f = (1.0/w)*self.circle.loc[0] <NEW_LINE> self.circle.blend = f <NEW_LINE> blend= self.circle.blend <NEW_LINE> loc = self.circle.loc <NEW_LINE> r,g,b,a = self.circle.color <NEW_LINE> z = self.circle.z <NEW_LINE> i = self.circle.interactiveState <NEW_LINE> string = 'blend:'+str(blend)+' | loc:' + str(loc) +' | color: '+str(r)+", "+str(g)+", "+str(b)+", "+str(a)+' | z loc:' + str(z)+' | interactivestate:' + str(i) <NEW_LINE> self.text.text = string
main appplication class, handles window contains events and graphics manager. Subclasses main.App and extends its public methods
6259902b8c3a8732951f7553
@_plugin_type <NEW_LINE> class InstrumentFile: <NEW_LINE> <INDENT> _FILETYPES = [] <NEW_LINE> def __init__(self, fp, file: str): <NEW_LINE> <INDENT> self.instruments = {} <NEW_LINE> self.file = file <NEW_LINE> try: <NEW_LINE> <INDENT> self.fp = fp <NEW_LINE> self._load_file() <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> del self.fp <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def _get_filetypes(cls) -> _typing.List[FileTypeInfo]: <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def accept(cls, preview: bytes, path: str) -> bool: <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def _add_instrument(self, inst_id: InstrumentId, instrument: _AdlibInstrument): <NEW_LINE> <INDENT> _logging.debug(f"({int(inst_id.instrument_type)}, {inst_id.bank}, {inst_id.program}): {instrument}") <NEW_LINE> self.instruments[inst_id] = instrument <NEW_LINE> <DEDENT> def _load_file(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def load_file(cls, f) -> "InstrumentFile": <NEW_LINE> <INDENT> if type(f) is str: <NEW_LINE> <INDENT> filename = f <NEW_LINE> fp = open(filename, "rb") <NEW_LINE> exclusive_fp = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> fp = f <NEW_LINE> filename = fp.name <NEW_LINE> exclusive_fp = False <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> _logging.info(f'Loading "{filename}".') <NEW_LINE> preview = fp.read(32) <NEW_LINE> for subclass in cls._PLUGINS: <NEW_LINE> <INDENT> if subclass.accept(preview, filename): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> fp.seek(0) <NEW_LINE> instance = subclass(fp, filename) <NEW_LINE> _logging.info(f'Loaded "{filename}" using {subclass.__name__}.') <NEW_LINE> return instance <NEW_LINE> <DEDENT> except (ValueError, IOError, OSError) as ex: <NEW_LINE> <INDENT> _logging.error(f'Error while loading "{filename}" using {subclass.__name__}: {ex}') <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> if exclusive_fp: <NEW_LINE> <INDENT> fp.close() <NEW_LINE> <DEDENT> <DEDENT> raise ValueError(f'Failed to load "{filename}" as {cls.__name__}.') <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_filetypes(cls) -> _typing.List["FileTypeInfo"]: <NEW_LINE> <INDENT> return [c.info for c in cls._FILETYPES]
The base class for instrument file types.
6259902b9b70327d1c57fd7e
class MatplotlibSurfactantViewer(AbstractMatplotlibViewer): <NEW_LINE> <INDENT> def __init__(self, distanceVar, surfactantVar=None, levelSetValue=0., title=None, smooth=0, zoomFactor=1., animate=False, limits={}, **kwlimits): <NEW_LINE> <INDENT> kwlimits.update(limits) <NEW_LINE> AbstractMatplotlibViewer.__init__(self, vars=[], title=title, **kwlimits) <NEW_LINE> self.distanceVar = distanceVar <NEW_LINE> if surfactantVar is None: <NEW_LINE> <INDENT> self.surfactantVar = numerix.zeros(len(self.distanceVar), 'd') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.surfactantVar = surfactantVar <NEW_LINE> <DEDENT> self.smooth = smooth <NEW_LINE> self.zoomFactor = zoomFactor <NEW_LINE> self.animate = animate <NEW_LINE> if animate: <NEW_LINE> <INDENT> self._initialCondition = None <NEW_LINE> <DEDENT> if distanceVar.mesh.dim != 2: <NEW_LINE> <INDENT> raise MeshDimensionError('The MatplotlibSurfactantViewer only works for 2D meshes.') <NEW_LINE> <DEDENT> <DEDENT> def _plot(self): <NEW_LINE> <INDENT> mesh = self.distanceVar.mesh <NEW_LINE> shape = mesh.shape <NEW_LINE> X, Y = mesh.cellCenters <NEW_LINE> maxX = max(X) <NEW_LINE> X = X.reshape(shape, order="FORTRAN") <NEW_LINE> Y = Y.reshape(shape, order="FORTRAN") <NEW_LINE> Z = self.distanceVar.value.reshape(shape, order="FORTRAN") <NEW_LINE> zmin, zmax = self._autoscale(vars=(self.surfactantVar,), datamin=self._getLimit(('datamin', 'zmin')), datamax=self._getLimit(('datamax', 'zmax'))) <NEW_LINE> import pylab <NEW_LINE> import matplotlib <NEW_LINE> CS = pylab.contour(X, Y, Z, (0.,)) <NEW_LINE> zc = CS.collections[0] <NEW_LINE> verts = numerix.array(zc.get_verts()) <NEW_LINE> IDs = numerix.array([mesh._getNearestCellID(vert[..., numerix.newaxis]) for vert in verts]) <NEW_LINE> colors = pylab.cm.jet(( self.surfactantVar[IDs] - zmin) / (zmax - zmin)) <NEW_LINE> segments = list(zip(verts[:-1], verts[1:])) <NEW_LINE> LC = matplotlib.collections.LineCollection(segments, colors=colors) <NEW_LINE> verts = numerix.array((-verts[..., 0], verts[..., 1])).swapaxes(0, 1) <NEW_LINE> segments = list(zip(verts[:-1], verts[1:])) <NEW_LINE> LC = matplotlib.collections.LineCollection(segments, colors=colors) <NEW_LINE> CS.ax.set_xlim((-maxX, maxX))
The `MatplotlibSurfactantViewer` creates a viewer with the Matplotlib_ python plotting package that displays a `DistanceVariable`. .. _Matplotlib: http://matplotlib.sourceforge.net/
6259902b507cdc57c63a5da3
class _IndexCondition(Condition): <NEW_LINE> <INDENT> def __init__(self, index_or_name: Union[index.Index, str]): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> if isinstance(index_or_name, index.Index): <NEW_LINE> <INDENT> self.name = index_or_name.name <NEW_LINE> self.index = index_or_name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.name = index_or_name <NEW_LINE> self.index = None <NEW_LINE> <DEDENT> <DEDENT> def bind(self, model_class: Type[Any]) -> None: <NEW_LINE> <INDENT> super().bind(model_class) <NEW_LINE> self.index = self.model_class.indexes[self.name] <NEW_LINE> <DEDENT> def _validate(self, model_class: Type[Any]) -> None: <NEW_LINE> <INDENT> if self.name not in model_class.indexes: <NEW_LINE> <INDENT> raise error.ValidationError('{} is not an index on {}'.format( self.name, model_class.table)) <NEW_LINE> <DEDENT> if self.index and self.index != model_class.indexes[self.name]: <NEW_LINE> <INDENT> raise error.ValidationError('{} does not belong to {}'.format( self.index.name, model_class.table))
Base class for conditions based on an Index.
6259902bec188e330fdf988f
class SingleAckGraphWalkerImpl(object): <NEW_LINE> <INDENT> def __init__(self, walker): <NEW_LINE> <INDENT> self.walker = walker <NEW_LINE> self._sent_ack = False <NEW_LINE> <DEDENT> def ack(self, have_ref): <NEW_LINE> <INDENT> if not self._sent_ack: <NEW_LINE> <INDENT> self.walker.send_ack(have_ref) <NEW_LINE> self._sent_ack = True <NEW_LINE> <DEDENT> <DEDENT> def next(self): <NEW_LINE> <INDENT> command, sha = self.walker.read_proto_line(_GRAPH_WALKER_COMMANDS) <NEW_LINE> if command in (None, 'done'): <NEW_LINE> <INDENT> if not self._sent_ack: <NEW_LINE> <INDENT> self.walker.send_nak() <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> elif command == 'have': <NEW_LINE> <INDENT> return sha <NEW_LINE> <DEDENT> <DEDENT> __next__ = next
Graph walker implementation that speaks the single-ack protocol.
6259902b711fe17d825e1498
class IntegrationServiceEnvironment(Resource): <NEW_LINE> <INDENT> _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'properties': {'key': 'properties', 'type': 'IntegrationServiceEnvironmentProperties'}, 'sku': {'key': 'sku', 'type': 'IntegrationServiceEnvironmentSku'}, } <NEW_LINE> def __init__( self, *, location: Optional[str] = None, tags: Optional[Dict[str, str]] = None, properties: Optional["IntegrationServiceEnvironmentProperties"] = None, sku: Optional["IntegrationServiceEnvironmentSku"] = None, **kwargs ): <NEW_LINE> <INDENT> super(IntegrationServiceEnvironment, self).__init__(location=location, tags=tags, **kwargs) <NEW_LINE> self.properties = properties <NEW_LINE> self.sku = sku
The integration service environment. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The resource id. :vartype id: str :ivar name: Gets the resource name. :vartype name: str :ivar type: Gets the resource type. :vartype type: str :param location: The resource location. :type location: str :param tags: A set of tags. The resource tags. :type tags: dict[str, str] :param properties: The integration service environment properties. :type properties: ~azure.mgmt.logic.models.IntegrationServiceEnvironmentProperties :param sku: The sku. :type sku: ~azure.mgmt.logic.models.IntegrationServiceEnvironmentSku
6259902be76e3b2f99fd9a0a
class WordEnd(_PositionToken): <NEW_LINE> <INDENT> def __init__(self, wordChars = printables): <NEW_LINE> <INDENT> super(WordEnd,self).__init__() <NEW_LINE> self.wordChars = set(wordChars) <NEW_LINE> self.skipWhitespace = False <NEW_LINE> self.errmsg = "Not at the end of a word" <NEW_LINE> <DEDENT> def parseImpl(self, instring, loc, doActions=True ): <NEW_LINE> <INDENT> instrlen = len(instring) <NEW_LINE> if instrlen>0 and loc<instrlen: <NEW_LINE> <INDENT> if (instring[loc] in self.wordChars or instring[loc-1] not in self.wordChars): <NEW_LINE> <INDENT> raise ParseException(instring, loc, self.errmsg, self) <NEW_LINE> <DEDENT> <DEDENT> return loc, []
Matches if the current position is at the end of a Word, and is not followed by any character in a given set of ``wordChars`` (default= ``printables``). To emulate the ```` behavior of regular expressions, use ``WordEnd(alphanums)``. ``WordEnd`` will also match at the end of the string being parsed, or at the end of a line.
6259902b30c21e258be99809
class SingleGrid(Grid): <NEW_LINE> <INDENT> empties = set() <NEW_LINE> def __init__(self, width: int, height: int, torus: bool) -> None: <NEW_LINE> <INDENT> super().__init__(width, height, torus) <NEW_LINE> <DEDENT> def position_agent( self, agent: Agent, x: Union[int, str] = "random", y: Union[int, str] = "random" ) -> None: <NEW_LINE> <INDENT> if x == "random" or y == "random": <NEW_LINE> <INDENT> if len(self.empties) == 0: <NEW_LINE> <INDENT> raise Exception("ERROR: Grid full") <NEW_LINE> <DEDENT> coords = agent.random.choice(sorted(self.empties)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> coords = (x, y) <NEW_LINE> <DEDENT> agent.pos = coords <NEW_LINE> self._place_agent(coords, agent) <NEW_LINE> <DEDENT> def _place_agent(self, pos: Coordinate, agent: Agent) -> None: <NEW_LINE> <INDENT> if self.is_cell_empty(pos): <NEW_LINE> <INDENT> super()._place_agent(pos, agent) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception("Cell not empty")
Grid where each cell contains exactly at most one object.
6259902b1d351010ab8f4b15
class PyFlworError(Exception): <NEW_LINE> <INDENT> pass
Base pyflwor Exception
6259902b287bf620b6272beb
class TestDestinyDefinitionsDirectorDestinyActivityGraphNodeDefinition(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testDestinyDefinitionsDirectorDestinyActivityGraphNodeDefinition(self): <NEW_LINE> <INDENT> pass
DestinyDefinitionsDirectorDestinyActivityGraphNodeDefinition unit test stubs
6259902bb57a9660fecd2a80
class CooldownMeasurement(State): <NEW_LINE> <INDENT> def __init__(self, fsm): <NEW_LINE> <INDENT> super(CooldownMeasurement, self).__init__(fsm) <NEW_LINE> self.cooldown_csv = self.fsm.data['FilePaths']['cooldown_csv'] <NEW_LINE> <DEDENT> def enter(self): <NEW_LINE> <INDENT> self.log.info('===> Measure cool down state enter') <NEW_LINE> super(CooldownMeasurement, self).enter(0, 0) <NEW_LINE> <DEDENT> def execute(self): <NEW_LINE> <INDENT> self.log.info('Measure cool down execute') <NEW_LINE> result = 'to_cooldown' <NEW_LINE> values = self.fsm.reader.get_cooldown_values(self.cooldown_csv) <NEW_LINE> if float(values[1]) > float(values[2]): <NEW_LINE> <INDENT> result = 'to_error' <NEW_LINE> self.log.error('current pPreVac: {0} mbar, pPreVac_max: {1} mbar'.format(values[0], values[1])) <NEW_LINE> <DEDENT> elif float(values[3]) > float(values[4]): <NEW_LINE> <INDENT> result = 'to_error' <NEW_LINE> self.log.error('current pVac: {0} mbar, pVac_max: {1} mbar'.format(values[3], values[4])) <NEW_LINE> <DEDENT> elif float(values[5]) >= float(values[6]): <NEW_LINE> <INDENT> result = 'to_cooldown' <NEW_LINE> self.log.info('current temperature: {0} K, stage 1 temperature: {1} K'.format(values[5], values[6])) <NEW_LINE> self.log.info('current pPreVac: {0} mbar, pPreVac_max: {1} mbar'.format(values[0], values[1])) <NEW_LINE> self.log.info('current pVac: {0} mbar, pVac_max: {1} mbar'.format(values[3], values[4])) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if float(values[3]) > float(values[7]): <NEW_LINE> <INDENT> result = 'to_cooldown' <NEW_LINE> self.log.info('Pressure in isolation chamber {0} is higher as {1}' .format(values[3], values[7])) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result = 'to_error' <NEW_LINE> self.log.info('Das Ziel wurde erreicht. Es ist keine Fehlermeldung. Folgt Erweiterung...') <NEW_LINE> <DEDENT> self.log.info('current temperature: {0} K, stage 1 temperature: {1} K'.format(values[5], values[6])) <NEW_LINE> self.log.info('current pPreVac: {0} mbar, pPreVac_max: {1} mbar'.format(values[0], values[1])) <NEW_LINE> self.log.info('current pVac: {0} mbar, pVac_max: {1} mbar'.format(values[3], values[4])) <NEW_LINE> <DEDENT> self.log.info('State: {0}'.format(result)) <NEW_LINE> self.fsm.to_transition(result) <NEW_LINE> <DEDENT> def exit(self): <NEW_LINE> <INDENT> self.log.info('<=== Measure cool down exit')
measure pressure and temperature
6259902b21bff66bcd723c61
class SubOption(): <NEW_LINE> <INDENT> def __init__(self, title=None, call=None, info=None): <NEW_LINE> <INDENT> self.title = title <NEW_LINE> self.call = call <NEW_LINE> self.info = info
A menu corresponding to a suboption within menu of a single option in the options menu; contains information such as the
6259902b73bcbd0ca4bcb290
class HistoryServerClient(object): <NEW_LINE> <INDENT> DEFAULT_PORT = 19888 <NEW_LINE> def __init__(self, host, port=DEFAULT_PORT, start_time=None, timeout=30): <NEW_LINE> <INDENT> self.history_server_api_url = 'http://%s:%s/ws/v1/history/mapreduce/jobs' % (host, port) <NEW_LINE> self.api_params = {'finishedTimeBegin': str(start_time)} if start_time else {} <NEW_LINE> self.timeout = timeout <NEW_LINE> self.session = requests.Session() <NEW_LINE> retries = Retry(total=5, backoff_factor=0.1, status_forcelist=[500, 502, 503, 504]) <NEW_LINE> for prefix in ['http://', 'https://']: <NEW_LINE> <INDENT> self.session.adapters[prefix].max_retries = retries <NEW_LINE> <DEDENT> <DEDENT> def get_jobs(self): <NEW_LINE> <INDENT> logger = logging.getLogger(__name__) <NEW_LINE> jobs_response = self.session.get(self.history_server_api_url, params=self.api_params, timeout=self.timeout) <NEW_LINE> jobs_response.raise_for_status() <NEW_LINE> jobs_json = jobs_response.json()["jobs"] <NEW_LINE> if jobs_json is None: <NEW_LINE> <INDENT> logger.warn("No jobs object returned from %s", self.history_server_api_url) <NEW_LINE> return [] <NEW_LINE> <DEDENT> return jobs_json["job"] <NEW_LINE> <DEDENT> def get_job(self, job_id): <NEW_LINE> <INDENT> job_url = "%s/%s" % (self.history_server_api_url, job_id) <NEW_LINE> try: <NEW_LINE> <INDENT> response = self.session.get(job_url, timeout=self.timeout) <NEW_LINE> <DEDENT> except RequestException: <NEW_LINE> <INDENT> logging.getLogger(__name__).exception("Invalid job returned for id %s", job_id) <NEW_LINE> return {} <NEW_LINE> <DEDENT> json = response.json() <NEW_LINE> if "job" in json: <NEW_LINE> <INDENT> return json["job"] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logging.getLogger(__name__).warn("Invalid job returned for id %s, status code %s: %s", job_id, response.status_code, response.content) <NEW_LINE> return {} <NEW_LINE> <DEDENT> <DEDENT> def __call__(self, job_id): <NEW_LINE> <INDENT> return self.get_job(job_id)
Client for History Server
6259902b8a349b6b43687238
class ManifestV1Renderer(JSONRenderer): <NEW_LINE> <INDENT> media_type = "application/vnd.docker.distribution.manifest.v1+prettyjws"
防止 docker 只传 Manifest Type 的请求,然后导致 416 发生
6259902b30c21e258be9980a
class FormFloat(QLineEdit): <NEW_LINE> <INDENT> def __init__(self, default=None, maxw=None, significant_digits=3): <NEW_LINE> <INDENT> super().__init__('') <NEW_LINE> self.significant_digits = significant_digits <NEW_LINE> if default is not None: <NEW_LINE> <INDENT> self.set_value(default) <NEW_LINE> <DEDENT> if maxw is not None: <NEW_LINE> <INDENT> self.setMaximumWidth(maxw) <NEW_LINE> <DEDENT> <DEDENT> def get_value(self, default=0): <NEW_LINE> <INDENT> text = self.text() <NEW_LINE> if text == 'N/A': <NEW_LINE> <INDENT> return NaN <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> text = float(text) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> lg.debug('Cannot convert "' + str(text) + '" to float.' + 'Using default ' + str(default)) <NEW_LINE> text = default <NEW_LINE> self.set_value(text) <NEW_LINE> <DEDENT> return text <NEW_LINE> <DEDENT> def set_value(self, value): <NEW_LINE> <INDENT> if value == '' or value is None or value == 'N/A': <NEW_LINE> <INDENT> text = '' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> text = ('{:.' + str(self.significant_digits) + 'f}').format(value) <NEW_LINE> <DEDENT> self.setText(text) <NEW_LINE> <DEDENT> def connect(self, funct): <NEW_LINE> <INDENT> self.textEdited.connect(funct)
Subclass QLineEdit for float to have a more consistent API across widgets. Parameters ---------- significant_digits : int number of significant digits
6259902b15baa72349462f97
class Suite(Base): <NEW_LINE> <INDENT> __tablename__ = 'suite' <NEW_LINE> archive = sqlalchemy.orm.relation('Archive', backref='suites')
Model for a suite This class represents a suite in an `Archive`.
6259902be76e3b2f99fd9a0c
class UserList(APIView): <NEW_LINE> <INDENT> permission_classes = (IsAuthenticated, ) <NEW_LINE> def get(self, request, format=None): <NEW_LINE> <INDENT> users = CustomUser.objects.all() <NEW_LINE> serializer = UserItemSerializer(users, many=True) <NEW_LINE> return Response({'users': serializer.data})
List all users
6259902bac7a0e7691f734e8
class GLU(Module): <NEW_LINE> <INDENT> __constants__ = ['dim'] <NEW_LINE> def __init__(self, dim=-1): <NEW_LINE> <INDENT> super(GLU, self).__init__() <NEW_LINE> self.dim = dim <NEW_LINE> <DEDENT> def forward(self, input): <NEW_LINE> <INDENT> return F.glu(input, self.dim) <NEW_LINE> <DEDENT> def extra_repr(self): <NEW_LINE> <INDENT> return 'dim={}'.format(self.dim)
Applies the gated linear unit function :math:`{GLU}(a, b)= a \otimes \sigma(b)` where :math:`a` is the first half of the input matrices and :math:`b` is the second half. Args: dim (int): the dimension on which to split the input. Default: -1 Shape: - Input: :math:`(\ast_1, N, \ast_2)` where `*` means, any number of additional dimensions - Output: :math:`(\ast_1, M, \ast_2)` where :math:`M=N/2` Examples:: >>> m = nn.GLU() >>> input = torch.randn(4, 2) >>> output = m(input)
6259902b3eb6a72ae038b664
class BaseVariables(object): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def get_all_variables(cls): <NEW_LINE> <INDENT> methods = inspect.getmembers(cls) <NEW_LINE> return [ { 'name': m[0], 'label': m[1].label, 'field_type': m[1].field_type.name, 'options': m[1].options, 'params': m[1].params, 'public': m[1].public, } for m in methods if getattr(m[1], 'is_rule_variable', False) ]
Classes that hold a collection of variables to use with the rules engine should inherit from this.
6259902bd164cc6175821f71
class UserAuthenticationView(APIView): <NEW_LINE> <INDENT> serializer_class = UserAuthenticationSerializer <NEW_LINE> def post(self,request,*args,**kwargs): <NEW_LINE> <INDENT> serializer=self.serializer_class(data=self.request.data) <NEW_LINE> if serializer.is_valid(): <NEW_LINE> <INDENT> user=serializer.validated_data['user'] <NEW_LINE> return Response({'token':user.auth_token.key},status=status.HTTP_200_OK) <NEW_LINE> <DEDENT> return Response(serializer.errors,status=status.HTTP_401_UNAUTHORIZED)
Authentication View.
6259902cd10714528d69ee8c
class InteriorNode(Node): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self._in_nodes = None <NEW_LINE> self._num_ready_in_nodes = 0 <NEW_LINE> <DEDENT> def _gather_shapes_dtypes_for_build(self): <NEW_LINE> <INDENT> assert self._in_nodes, 'Tried to build an internal node with no inputs.' <NEW_LINE> in_shapes = [] <NEW_LINE> in_dtypes = [] <NEW_LINE> for node in self._in_nodes: <NEW_LINE> <INDENT> shape = node.out_shape() <NEW_LINE> if shape is None: <NEW_LINE> <INDENT> return False, None, None <NEW_LINE> <DEDENT> in_shapes.append(shape) <NEW_LINE> dtype = node.out_dtype() <NEW_LINE> if dtype is None: <NEW_LINE> <INDENT> return False, None, None <NEW_LINE> <DEDENT> in_dtypes.append(dtype) <NEW_LINE> <DEDENT> return True, in_shapes, in_dtypes <NEW_LINE> <DEDENT> def in_nodes(self): <NEW_LINE> <INDENT> return self._in_nodes <NEW_LINE> <DEDENT> def to_spec_or_specs(self): <NEW_LINE> <INDENT> raise NotImplementedError
A non-input node (the normal case).
6259902c1d351010ab8f4b17
class BadReferenceError(PatternError): <NEW_LINE> <INDENT> errmsg = "This reference-name has no definition (yet)."
Raised if a pattern refers to a subexpression name not defined in the context of the analysis. args are the offending reference and the span within the pattern (offset/length pair) where it appears.
6259902c9b70327d1c57fd82
class GetWeeklyArtistChart(Choreography): <NEW_LINE> <INDENT> def __init__(self, temboo_session): <NEW_LINE> <INDENT> Choreography.__init__(self, temboo_session, '/Library/LastFm/User/GetWeeklyArtistChart') <NEW_LINE> <DEDENT> def new_input_set(self): <NEW_LINE> <INDENT> return GetWeeklyArtistChartInputSet() <NEW_LINE> <DEDENT> def _make_result_set(self, result, path): <NEW_LINE> <INDENT> return GetWeeklyArtistChartResultSet(result, path) <NEW_LINE> <DEDENT> def _make_execution(self, session, exec_id, path): <NEW_LINE> <INDENT> return GetWeeklyArtistChartChoreographyExecution(session, exec_id, path)
Create a new instance of the GetWeeklyArtistChart Choreography. A TembooSession object, containing a valid set of Temboo credentials, must be supplied.
6259902c507cdc57c63a5da7
class Pgdspider(Package): <NEW_LINE> <INDENT> homepage = "http://www.cmpg.unibe.ch/software/PGDSpider" <NEW_LINE> url = "http://www.cmpg.unibe.ch/software/PGDSpider/PGDSpider_2.1.1.2.zip" <NEW_LINE> version('2.1.1.2', sha256='a630ef9f3ef0c36be0d613867c5293378d77b52396ac701bc7b9ec5d3ba7f2e1') <NEW_LINE> depends_on('java', type=('build', 'run')) <NEW_LINE> depends_on('bcftools') <NEW_LINE> depends_on('bwa') <NEW_LINE> depends_on('samtools') <NEW_LINE> def install(self, spec, prefix): <NEW_LINE> <INDENT> mkdirp(prefix.bin) <NEW_LINE> jar_file = 'PGDSpider{0}-cli.jar'.format(self.version.up_to(1)) <NEW_LINE> install(jar_file, prefix.bin) <NEW_LINE> script_sh = join_path(os.path.dirname(__file__), "pgdspider.sh") <NEW_LINE> script = prefix.bin.pgdspider <NEW_LINE> install(script_sh, script) <NEW_LINE> set_executable(script) <NEW_LINE> java = self.spec['java'].prefix.bin.java <NEW_LINE> kwargs = {'ignore_absent': False, 'backup': False, 'string': False} <NEW_LINE> filter_file('^java', java, script, **kwargs) <NEW_LINE> filter_file('pgdspider.jar', join_path(prefix.bin, jar_file), script, **kwargs)
"PGDSpider is a powerful automated data conversion tool for population genetic and genomics programs
6259902cd4950a0f3b11163d