def handler(event, context): props = properties.load( event, { 'ConfigurationBucket': properties.String(), 'ConfigurationKey': properties.String(), 'ResourceGroupName': properties.String() }) data = { 'ConfigurationBucket': props.ConfigurationBucket, 'ConfigurationKey': '{}/resource-group/{}'.format(props.ConfigurationKey, props.ResourceGroupName), 'TemplateURL': 'https://s3.amazonaws.com/{}/{}/resource-group/{}/resource-template.json' .format(props.ConfigurationBucket, props.ConfigurationKey, props.ResourceGroupName) } physical_resource_id = 'CloudCanvas:LambdaConfiguration:{stack_name}:{resource_group_name}'.format( stack_name=discovery_utils.get_stack_name_from_stack_arn( event['StackId']), resource_group_name=props.ResourceGroupName) custom_resource_response.succeed(event, context, data, physical_resource_id)
def handler(event, context): props = properties.load( event, { 'ConfigurationBucket': properties.String(), 'ConfigurationKey': properties.String(), 'DeploymentName': properties.String() }) data = { 'ConfigurationBucket': props.ConfigurationBucket, 'ConfigurationKey': '{}/deployment/{}'.format(props.ConfigurationKey, props.DeploymentName), 'DeploymentTemplateURL': 'https://s3.amazonaws.com/{}/{}/deployment/{}/deployment-template.json' .format(props.ConfigurationBucket, props.ConfigurationKey, props.DeploymentName), 'AccessTemplateURL': 'https://s3.amazonaws.com/{}/{}/deployment-access-template-{}.json'. format(props.ConfigurationBucket, props.ConfigurationKey, props.DeploymentName), 'DeploymentName': props.DeploymentName } physical_resource_id = 'CloudCanvas:DeploymentConfiguration:{}:{}'.format( discovery_utils.get_stack_name_from_stack_arn(event['StackId']), props.DeploymentName) custom_resource_response.succeed(event, context, data, physical_resource_id)
class StringOpts(properties.HasProperties): mystring = properties.String('My string') mystringstrip = properties.String('My stripped string', strip=' ') mystringupper = properties.String('My upper string', change_case='upper') mystringlower = properties.String('My lower string', change_case='lower')
class BaseConversation(BaseModel): """This represents a basic conversation, meant to be subclassed.""" number = properties.Integer( 'The conversation number displayed in the UI. This number can be used ' 'in combination with the id to construct a URI to the conversation on ' 'the Help Scout website. Example: ' '``https://secure.helpscout.net/conversation/<id>/<number>/``', required=True, ) subject = properties.String( 'The subject of the conversation.', required=True, ) status = properties.StringChoice( 'Status of the conversation.', choices=['active', 'pending', 'closed', 'spam'], default='pending', required=True, ) thread_count = properties.Integer( 'This count represents the number of published threads found on the ' 'conversation (it does not include line items, drafts or threads held ' 'for review by Traffic Cop).', required=True, ) preview = properties.String( 'Conversation preview.', ) modified_at = properties.DateTime( 'UTC time when a user last modified this conversation.', )
class ManyProperties(properties.HasProperties): mystr = properties.String( 'my string', required=False, ) myarr = properties.Array( 'my array', required=False, ) myinst = properties.Instance( 'my HP1', instance_class=HP1, required=False, ) mylist = properties.List( 'my list of HP1', prop=HP1, required=False, default=properties.utils.undefined ) myunion = properties.Union( 'string or HP1', props=(HP1, properties.String('')), required=False, )
class Address(BaseModel): """This represents an address.""" lines = properties.List( 'Address line strings', prop=properties.String('Address line string', ), ) city = properties.String( 'City', required=True, ) state = properties.String( 'State', required=True, ) postal_code = properties.String( 'Postal Code', required=True, ) country = properties.String( 'Country', required=True, ) created_at = properties.DateTime( 'UTC time when this address was created.', ) modified_at = properties.DateTime( 'UTC time when this address was modified.', )
class SimulationDC(BaseSimulation): src_a = properties.Vector3( "a electrode location", required=True ) src_b = properties.Vector3( "return electrode location", required=True ) fields_filename = properties.String( "filename for the fields", default="fieldsDC.npy" ) formulation = properties.String( "field that we are solving for", default="phi" ) def __init__(self, **kwargs): super(SimulationDC, self).__init__(**kwargs) self._prob = DC.Problem3D_CC( self.meshGenerator.mesh, sigmaMap=self.physprops.wires.sigma, bc_type='Dirichlet', Solver=Pardiso ) self._src = DC.Src.Dipole([], self.src_a, self.src_b) self._survey = DC.Survey([self._src]) self._prob.pair(self._survey)
class SaveEveryIteration(InversionDirective): """SaveEveryIteration This directive saves an array at each iteration. The default direcroty is the current directoy and the models are saved as `InversionModel-YYYY-MM-DD-HH-MM-iter.npy` """ directory = properties.String("directory to save results in", default=".") name = properties.String("root of the filename to be saved", default="InversionModel") @properties.validator('directory') def _ensure_abspath(self, change): val = change['value'] fullpath = os.path.abspath(os.path.expanduser(val)) if not os.path.isdir(fullpath): os.mkdir(fullpath) @property def fileName(self): if getattr(self, '_fileName', None) is None: from datetime import datetime self._fileName = '{0!s}-{1!s}'.format( self.name, datetime.now().strftime('%Y-%m-%d-%H-%M')) return self._fileName
class DomainCondition(properties.HasProperties): """This represents one condition of a domain query.""" field = properties.String( 'Field to search on', required=True, ) value = properties.String( 'String Value', required=True, ) @property def field_name(self): """Return the name of the API field.""" return BaseModel._to_camel_case(self.field) def __init__(self, field, value, **kwargs): """Initialize a new generic query condition. Args: field (str): Field name to search on. This should be the Pythonified name as in the internal models, not the name as provided in the API e.g. ``first_name`` for the Customer's first name instead of ``firstName``. value (mixed): The value of the field. """ return super(DomainCondition, self).__init__(field=field, value=value, **kwargs) @classmethod def from_tuple(cls, query): """Create a condition from a query tuple. Args: query (tuple or list): Tuple or list that contains a query domain in the format of ``(field_name, field_value, field_value_to)``. ``field_value_to`` is only applicable in the case of a date search. Returns: DomainCondition: An instance of a domain condition. The specific type will depend on the data type of the first value provided in ``query``. """ field, query = query[0], query[1:] try: cls = TYPES[type(query[0])] except KeyError: # We just fallback to the base class if unknown type. pass return cls(field, *query) def __str__(self): """Return a string usable as a query part in an API request.""" return '%s:"%s"' % (self.field_name, self.value)
class SimulationDC(BaseSimulation): """ A wrapper to run a DC Forward Simulation :param CasingSimulations.model.WholeSpace modelParameters: casing parameters object :param CasingSimulations.mesh.BaseMeshGenerator mesh: a CasingSimulation mesh generator object """ src_a = properties.Vector3Array("a electrode location", required=True) src_b = properties.Vector3Array("return electrode location", required=True) fields_filename = properties.String("filename for the fields", default="fieldsDC.npy") formulation = properties.String("field that we are solving for", default="phi") physics = "DC" def __init__(self, **kwargs): super(SimulationDC, self).__init__(**kwargs) self._prob = DC.Problem3D_CC(self.meshGenerator.mesh, sigmaMap=self.physprops.wires.sigma, bc_type='Dirichlet', Solver=Solver) self._srcList = [ DC.Src.Dipole([], self.src_a[i, :], self.src_b[i, :]) for i in range(self.src_a.shape[0]) ] # self._src = DC.Src.Dipole([], self.src_a, self.src_b) self._survey = DC.Survey(self._srcList) self._prob.pair(self._survey)
class Field(BaseModel): """The field object represents a user's response to a custom field in the context of a single conversation.""" field_id = properties.Integer( 'The field definition identifier; note that multiple conversations ' 'will each have values for the same field identifier.', ) name = properties.String( 'The name of the field; note that this may change if a field is ' 'renamed, but the ``field_id`` will not.', required=True, ) value = properties.String('The value the user specified for the field.', ) type = properties.StringChoice( 'Type of the custom field.', choices=[ 'SINGLE_LINE', 'MULTI_LINE', 'DATE', 'NUMBER', 'DROPDOWN', ], ) label = properties.String( 'String representation of the custom field\'s value. Unlike ' '``value`` it contains the actual dropdown option value for ' '``DROPDOWN`` custom field.', )
class ManyProperties(properties.HasProperties): mystr = properties.String( 'my string', serializer=reverse, deserializer=reverse, ) myarr = properties.Array( 'my array', serializer=to_string, deserializer=from_string, ) myinst = properties.Instance( 'my HP1', instance_class=HP1, serializer=serialize_a_only, deserializer=deserialize_from_a, ) mylist = properties.List( 'my list of HP1', prop=HP1, serializer=sum_of_a, deserializer=from_sum, ) myunion = properties.Union( 'string or HP1', props=(HP1, properties.String('')), serializer=just_the_classname, deserializer=reverse, )
class SearchCustomer(Person): """This represents a customer as returned by a search.""" photo_type = properties.StringChoice( 'Type of photo.', choices=[ 'unknown', 'gravatar', 'twitter', 'facebook', 'googleprofile', 'googleplus', 'linkedin', ], ) gender = properties.StringChoice( 'Gender of this customer.', choices=['female', 'male', 'unknown'], default='unknown', required=True, ) age = properties.String('Age (or age range) of this customer.', ) organization = properties.String( 'Company/Organization the customer identifies with.', ) job_title = properties.String('Job title at company/organization.', ) location = properties.String('Location', ) emails = properties.List( 'Email addresses for the customer.', prop=properties.String(''), )
def handler(event, context): '''Entry point for the Custom::AccessControl resource handler.''' props = properties.load( event, { 'ConfigurationBucket': properties.String(), # Currently not used 'ConfigurationKey': properties.String() } ) # Depend on unique upload id in key to force Cloud Formation to call handler # Validate RequestType request_type = event['RequestType'] if request_type not in ['Create', 'Update', 'Delete']: raise RuntimeError('Unexpected request type: {}'.format(request_type)) # Get stack_info for the AccessControl resource's stack. stack_arn = event['StackId'] stack = stack_info.get_stack_info(stack_arn) # Physical ID is always the same. physical_resource_id = aws_utils.get_stack_name_from_stack_arn( stack_arn) + '-' + event['LogicalResourceId'] # The AccessControl resource has no output values. data = {} # Accumlate problems encountered so we can give a full report. problems = ProblemList() # Apply access control as determined by the Cloud Canvas stack type. if stack.stack_type == stack.STACK_TYPE_RESOURCE_GROUP: were_changes = _apply_resource_group_access_control( request_type, stack, problems) elif stack.stack_type == stack.STACK_TYPE_DEPLOYMENT_ACCESS: were_changes = _apply_deployment_access_control( request_type, stack, problems) elif stack.stack_type == stack.STACK_TYPE_PROJECT: were_changes = _apply_project_access_control(request_type, stack, problems) else: raise RuntimeError( 'The Custom::AccessControl resource can only be used in resource group, deployment access, or project stack templates.' ) # If there were any problems, provide an error message with all the details. if problems: raise RuntimeError( 'Found invalid AccessControl metadata:\n {}'.format(problems)) # If there were changes, wait a few seconds for them to propagate if were_changes: print 'Delaying {} seconds for change propagation'.format( PROPAGATION_DELAY_SECONDS) time.sleep(PROPAGATION_DELAY_SECONDS) # Successful execution. custom_resource_response.succeed(event, context, data, physical_resource_id)
class StrainGenetics(BaseModel): """Object that holds information about the genetics for the strain.""" names = properties.String( 'Genetics name. `More information <https://www.cannabisreports.com/' 'faq/cannabis-genetics/how-do-you-read-cannabis-genetics>`_.', ) link = properties.String( 'Link to the genetic listing in the Cannabis Reports API.', )
class Projection(properties.HasProperties): projection = properties.String('The coordinate projection') datum = properties.String('The projection datum') units = properties.String('The projection units') corner_point = properties.List('The corner points', prop=CornerPoint) grid_origin = properties.String('The grid origin') utm_proj_params = properties.Dictionary('The UTM projection parameters', required=False) ps_proj_params = properties.Dictionary('The PS projection parameters', required=False) albers_proj_params = properties.Dictionary('The Albers projection parameters', required=False) sin_proj_params = properties.Dictionary('The Sin projection parameters', required=False)
class BaseModelWithLinks(BaseModel): link = properties.String( 'Link to the record in the Cannabis Reports API.', ) qr = properties.String( 'Link to the QR code for this record.', ) url = properties.String( 'Link to the record listing on the Cannabis Reports website.', )
def handler(event, context): props = properties.load(event, { 'ConfigurationBucket': properties.String(), # Currently not used 'ConfigurationKey': properties.String(), # Depend on unique upload id in key to force Cloud Formation to call handler 'RoleLogicalId': properties.String(), 'MetadataKey': properties.String(), 'PhysicalResourceId': properties.String(), 'UsePropagationDelay': properties.String(), 'RequireRoleExists': properties.String(default='true'), 'ResourceGroupStack': properties.String(default=''), 'DeploymentStack': properties.String(default='')}) if props.ResourceGroupStack is '' and props.DeploymentStack is '': raise ValidationError('A value for the ResourceGroupStack property or the DeploymentStack property must be provided.') if props.ResourceGroupStack is not '' and props.DeploymentStack is not '': raise ValidationError('A value for only the ResourceGroupStack property or the DeploymentStack property can be provided.') use_propagation_delay = props.UsePropagationDelay.lower() == 'true' data = {} stack_infos = [] if props.ResourceGroupStack is not '': resource_group_info = stack_info.ResourceGroupInfo(props.ResourceGroupStack) # create a list of stack-infos, starting at the resource group level and working our way upward stack_infos = _build_stack_infos_list(resource_group_info) else: # DeploymentStack deployment_info = stack_info.DeploymentInfo(props.DeploymentStack) # create a list of stack-infos, starting at the deployment level and working our way upward stack_infos = _build_stack_infos_list(deployment_info) # go through each of the stack infos, trying to find the specified role for stack in stack_infos: role = stack.resources.get_by_logical_id(props.RoleLogicalId, expected_type='AWS::IAM::Role', optional=True) if role is not None: break role_physical_id = None if role is not None: role_physical_id = role.physical_id if role_physical_id is None: if props.RequireRoleExists.lower() == 'true': raise ValidationError('Could not find role \'{}\'.'.format(props.RoleLogicalId)) else: if type(stack_infos[0]) is stack_info.ResourceGroupInfo: _process_resource_group_stack(event['RequestType'], stack_infos[0], role_physical_id, props.MetadataKey, use_propagation_delay) else: for resource_group_info in stack_infos[0].resource_groups: _process_resource_group_stack(event['RequestType'], resource_group_info, role_physical_id, props.MetadataKey, use_propagation_delay) custom_resource_response.succeed(event, context, data, props.PhysicalResourceId)
class Attachment(AttachmentData): hash = properties.String('Unique hash.', ) mime_type = properties.String('Mime Type', ) file_name = properties.String( 'File Name', required=True, ) size = properties.Integer('Size of the attachment in bytes.', ) width = properties.Integer('Image width', ) height = properties.Integer('Image height', ) url = properties.String( 'Public-facing url where attachment can be downloaded.', )
class KeyValuePair(BaseModel): key = properties.String( 'Name used to identify the pair.', required=True, ) value = properties.String( 'Value that corresponds to the name.', required=True, ) def __init__(self, key, value, **kwargs): """Allow for positional key, val pairs.""" super(KeyValuePair, self).__init__(key=key, value=value, **kwargs)
class Project(ContentModel): """OMF Project for serializing to .omf file""" author = properties.String('Author', default='') revision = properties.String('Revision', default='') date = properties.DateTime('Date associated with the project data', required=False) units = properties.String('Spatial units of project', default='') elements = properties.List( 'Project Elements', prop=ProjectElement, default=list, ) origin = properties.Vector3('Origin point for all elements in the project', default=[0., 0., 0.])
class RasterMetaData(properties.HasProperties): """An object to contain all the information for a single swath. """ #https://landsat.usgs.gov/how-do-landsat-8-band-combinations-differ-landsat-7-or-landsat-5-satellite-data # Metadata data_provider = properties.String('The data provider') satellite = properties.String('The satellite from which data was aquired') instrument = properties.String('The instrument on the satellite') acquisition_date = properties.String('The date of acquisition', required=False) scene_center_time = properties.String('Center time', required=False) level1_production_date = properties.String('Production date', required=False) solar_angles = properties.Instance('The solar angles', SolarAngle, required=False) earth_sun_distance = properties.Float('The earth-sun distance', required=False) product_id = properties.String('Data product ID', required=False) lpgs_metadata_file = properties.String('metadata file', required=False) wrs = properties.Instance('WRS', WRS, required=False) # TODO modis = properties.Instance('Modis', Modis, required=False) corner = properties.List('The corner points', prop=Corner) # Spatial Reference bounding_coordinates = properties.Instance('The bounding coordinates', BoundingCoordinates) projection_information = properties.Instance('The projection', Projection) orientation_angle = properties.Float('The orientation angle', min=-360.0, max=360.0)
class TestModel(BaseModel): a_key = properties.String('A key') sub_instance = properties.Instance( 'Sub Instance', instance_class=BaseModel, ) list = properties.List( 'List', prop=properties.Instance('List Instance', instance_class=BaseModel), ) list_string = properties.List( 'List of Strings', prop=properties.String('String'), ) not_a_field = True
class MailboxRef(BaseModel): """The mailbox ref is a subset of the full Mailbox object.""" name = properties.String( 'Name of the Mailbox.', required=True, )
def test_with_None_and_default_object(self): target = properties.ObjectOrListOfObject(schema={'prop': properties.String()}, default={'prop': 'value'}) value = target('Test', None) self.assertEqual(len(value), 1) self.assertEqual(value[0].prop, 'value')
class Folder(BaseModel): name = properties.String( 'Folder name', required=True, ) type = properties.StringChoice( 'The type of folder.', choices=[ 'needsattention', 'drafts', 'assigned', 'open', 'closed', 'spam', 'mine', 'team', ], default='drafts', required=True, ) user_id = properties.Integer( 'If the folder type is ``MyTickets``, this represents the Help Scout ' 'user to which this folder belongs. Otherwise it is empty.', ) total_count = properties.Integer( 'Total number of conversations in this folder.', ) active_count = properties.Integer( 'Total number of conversations in this folder that are in an active ' 'state (vs pending).', ) modified_at = properties.DateTime( 'UTC time when this folder was modified.', )
class Strain(LineageModel): """Cannabis strains are the various cultivars available for the cannabis family. Thousands of years of human domestication and breeding of cannabis strains have resulted in a huge variety of attributes that we know and love today. `Wikipedia Definition <http://en.wikipedia.org/wiki/Cultivar>`_ Over time, strain names have been used by various companies in their attempts to recreate the results of other breeders. Cannabis Reports identifies strains not only by their name, but by their seed company as well, to ensure they are all properly represented. """ name = properties.String( 'Name of the cannabis strain.', ) seed_company = properties.Instance( 'Information about the seed company that created or provides the ' 'strain.', instance_class=SeedCompany, ) genetics = properties.Instance( 'Object that holds information about the genetics for the strain.', instance_class=StrainGenetics, ) children = properties.Instance( 'Object that holds information about the children for the strain.', instance_class=GeneralOverview, ) reviews = properties.Instance( 'Object that holds information about the reviews for the strain.', instance_class=GeneralOverview, )
class CustomField(BaseModel): """This represents optional data that can defined for specific mailbox and filled when creating or updating a Conversation.""" field_name = properties.String( 'The name of the field; note that this may change if a field ' 'is renamed, but the ``id`` will not.', required=True, ) field_type = properties.StringChoice( 'Type of the field.', choices=[ 'SINGLE_LINE', 'MULTI_LINE', 'DATA', 'NUMBER', 'DROPDOWN', ], default='SINGLE_LINE', required=True, ) required = properties.Bool('Flag for UI to mark the field as required.', ) order = properties.Integer( 'Relative order of the custom field. Can be ``null`` or a number ' 'between ``0`` and ``255``.', min=0, max=255, ) options = properties.List( 'Field options', prop=Option, )
class SillySingleton(properties.HasProperties): uid = properties.String('uid', change_case='upper') @classmethod def load(cls, value): return getattr(cls, 'ONLY_INSTANCE', None)
class Customer(SearchCustomer): """This represents a customer, which is a type of person.""" background = properties.String( 'This is the Notes field from the user interface.', ) address = properties.Instance( 'The address for this customer.', instance_class=Address, ) social_profiles = properties.List( 'Social profiles that represent this customer.', prop=SocialProfile, ) emails = properties.List( 'Email addresses for this customer.', prop=Email, ) phones = properties.List( 'Phone numbers for this customer.', prop=Phone, ) chats = properties.List( 'Chat addresses for this customer.', prop=Chat, ) websites = properties.List( 'Websites for this customer.', prop=Website, )