INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Check the consumed capacity against the limit and sleep
def _wait(self, args, now, cap, consumed_history, consumed_capacity): """ Check the consumed capacity against the limit and sleep """ for key in ['read', 'write']: if key in cap and cap[key] > 0: consumed_history[key].add(now, consumed_capacity[key]) consumed ...
Send a case creation to SalesForces to create a ticket. @param name of the person creating the case. @param email of the person creating the case. @param subject of the case. @param description of the case. @param businessImpact of the case. @param priority of the case. ...
def create_case(self, name, email, subject, description, businessImpact, priority, phone): """ Send a case creation to SalesForces to create a ticket. @param name of the person creating the case. @param email of the person creating the case. @param subject of the cas...
Get the day dates in between start and end formatted for query. This returns dates inclusive e.g. final day is (end_at, end_at+1 day)
def date_range_for_webtrends(cls, start_at=None, end_at=None): """ Get the day dates in between start and end formatted for query. This returns dates inclusive e.g. final day is (end_at, end_at+1 day) """ if start_at and end_at: start_date = cls.parse_standard_date_st...
Get the sum of spending for this category up to and including the given month.
def get_cumulative_spend(key): """ Get the sum of spending for this category up to and including the given month. """ query = ('ROUND(SUM(total_ex_vat), 2) AS total ' 'FROM {table} ' 'WHERE date <= "{year}-{month:02}-01" ' 'AND lot="{lot}" ' 'AND c...
Plot the ROI
def plot(self, value=None, pixel=None): """ Plot the ROI """ # DEPRECATED import ugali.utils.plotting map_roi = np.array(hp.UNSEEN \ * np.ones(hp.nside2npix(self.config.params['coords']['nside_pixel']))) if value is None: ...
Function for testing if coordintes in set of ROI pixels.
def inPixels(self,lon,lat,pixels): """ Function for testing if coordintes in set of ROI pixels. """ nside = self.config.params['coords']['nside_pixel'] return ugali.utils.healpix.in_pixels(lon,lat,pixels,nside)
Return the catalog pixels spanned by this ROI.
def getCatalogPixels(self): """ Return the catalog pixels spanned by this ROI. """ filenames = self.config.getFilenames() nside_catalog = self.config.params['coords']['nside_catalog'] nside_pixel = self.config.params['coords']['nside_pixel'] # All possible catalo...
The entry point of the application.
def main(args=None): """The entry point of the application.""" if args is None: args = sys.argv[1:] # Parse command-line args = docopt(__doc__, argv=args) # Parse arguments path, address = resolve(args['<path>'], args['<address>']) host, port = split_address(address) # Validat...
Create the index schema Parameters ---------- hash_key : :class:`~.DynamoKey` The hash key of the table
def schema(self, hash_key): """ Create the index schema Parameters ---------- hash_key : :class:`~.DynamoKey` The hash key of the table """ key_schema = [hash_key.hash_schema()] if self.range_key is not None: key_schema.append(sel...
Create an index that projects key attributes plus some others
def include(cls, name, range_key, includes): """ Create an index that projects key attributes plus some others """ return cls(cls.INCLUDE, name, range_key, includes)
Create an index from returned Dynamo data
def from_response(cls, response, attrs): """ Create an index from returned Dynamo data """ proj = response['Projection'] index = cls(proj['ProjectionType'], response['IndexName'], attrs[response['KeySchema'][1]['AttributeName']], proj.get('NonKeyAttributes...
Create an index that projects all attributes
def all(cls, name, hash_key, range_key=None, throughput=None): """ Create an index that projects all attributes """ return cls(cls.ALL, name, hash_key, range_key, throughput=throughput)
Create an index that projects only key attributes
def keys(cls, name, hash_key, range_key=None, throughput=None): """ Create an index that projects only key attributes """ return cls(cls.KEYS, name, hash_key, range_key, throughput=throughput)
Create an index that projects key attributes plus some others
def include(cls, name, hash_key, range_key=None, includes=None, throughput=None): """ Create an index that projects key attributes plus some others """ return cls(cls.INCLUDE, name, hash_key, range_key, includes, throughput=throughput)
Construct the schema definition for this index
def schema(self): """ Construct the schema definition for this index """ schema_data = super(GlobalIndex, self).schema(self.hash_key) schema_data['ProvisionedThroughput'] = self.throughput.schema() return schema_data
Create an index from returned Dynamo data
def from_response(cls, response, attrs): """ Create an index from returned Dynamo data """ proj = response['Projection'] hash_key = attrs.get(response['KeySchema'][0]['AttributeName']) range_key = None if len(response['KeySchema']) > 1: range_key = attrs[response['Key...
Create a Table from returned Dynamo data
def from_response(cls, response): """ Create a Table from returned Dynamo data """ hash_key = None range_key = None # KeySchema may not be in the response if the TableStatus is DELETING. if 'KeySchema' in response: attrs = dict(((d['AttributeName'], ...
Get all attrs necessary for the update (empty unless Create)
def get_attrs(self): """ Get all attrs necessary for the update (empty unless Create) """ if self.action != 'Create': return [] index = self.extra['index'] ret = [index.hash_key] if index.range_key is not None: ret.append(index.range_key) return re...
Get the serialized Dynamo format for the update
def serialize(self): """ Get the serialized Dynamo format for the update """ if self.action == 'Create': payload = self.extra['index'].schema() else: payload = { 'IndexName': self.index_name, } if self.action == 'Update': ...
Try to convert a string expression into a PrimitiveTree given a PrimitiveSet *pset*. The primitive set needs to contain every primitive present in the expression. :param string: String representation of a Python expression. :param pset: Primitive set from which primitives are selected. ...
def from_string(cls, string, pset): """Try to convert a string expression into a PrimitiveTree given a PrimitiveSet *pset*. The primitive set needs to contain every primitive present in the expression. :param string: String representation of a Python expression. :param pset: Pri...
:param variable_type_indices: A sequence of variable type indices where each entry defines the index of a variable type in the design matrix. For example a design matrix with two variable types will have indices [j,n] where variable type A spans 0 to j and variable type B spans j + 1 to n. :para...
def initialize_parameters(self, variable_type_indices, names, operation=None, begin_range_name=None, end_range_name=None, *args): """ :param variable_type_indices: A sequence of variable type indices where each entry defines the index of a variable type in the desig...
Returns existing instance of messenger. If one does not exist it will be created and returned. :param int interval: Number of miliseconds that represents interval when messages will be processed. Note that this parameter will be used only the first time when ...
def instance(cls, interval=5): ''' Returns existing instance of messenger. If one does not exist it will be created and returned. :param int interval: Number of miliseconds that represents interval when messages will be processed. Note that this param...
Sends provided message to all listeners. Message is only added to queue and will be processed on next tick. :param Message message: Message to send.
def send(self, message, *args, **kwargs): ''' Sends provided message to all listeners. Message is only added to queue and will be processed on next tick. :param Message message: Message to send. ''' self._messages.put((message, args, kwargs), False)
Adds hander for specified message. :param str message: Name of message to subscribe to. :param callable handler: Handler for this message type. Handler must receive single parameter and that parameter will be instance of sent message.
def subscribe(self, message, handler): ''' Adds hander for specified message. :param str message: Name of message to subscribe to. :param callable handler: Handler for this message type. Handler must receive single parameter and that parameter will b...
Removes handler from message listeners. :param str message: Name of message to unsubscribe handler from. :param callable handler: Callable that should be removed as handler for `message`.
def unsubscribe(self, message, handler): ''' Removes handler from message listeners. :param str message: Name of message to unsubscribe handler from. :param callable handler: Callable that should be removed as handler for `message`. ''' with self...
Event handler for timer that processes all queued messages.
def _execute(self, sender, event_args): ''' Event handler for timer that processes all queued messages. ''' with self._lock: while not self._messages.empty(): msg, args, kwargs = self._messages.get(False) for subscriber in self._subscribers[msg...
Emits this signal. As result, all handlers will be invoked.
def emit(self, *args, **kwargs): ''' Emits this signal. As result, all handlers will be invoked. ''' self._messanger.send(self, *args, **kwargs)
Raises event that property value has changed for provided property name. :param str property_name: Name of property whose value has changed.
def RaisePropertyChanged(self, property_name): ''' Raises event that property value has changed for provided property name. :param str property_name: Name of property whose value has changed. ''' args = PropertyChangedEventArgs(property_name) for handler in s...
Expand shell variables ("$VAR"), user directory symbols (~), and return absolute path >>> path0 = '~/whatever.txt' >>> path = expand_path(path0) >>> path.endswith(path0[2:]) True >>> len(path) > len(path0) True >>> '~' in path False >>> path.startswith(os.path.sep) True
def expand_path(path, follow_links=False): """ Expand shell variables ("$VAR"), user directory symbols (~), and return absolute path >>> path0 = '~/whatever.txt' >>> path = expand_path(path0) >>> path.endswith(path0[2:]) True >>> len(path) > len(path0) True >>> '~' in path False ...
Like os.walk, but takes `level` kwarg that indicates how deep the recursion will go. Notes: TODO: refactor `level`->`depth` References: http://stackoverflow.com/a/234329/623735 Args: path (str): Root path to begin file tree traversal (walk) level (int, optional): Dept...
def walk_level(path, level=1): """Like os.walk, but takes `level` kwarg that indicates how deep the recursion will go. Notes: TODO: refactor `level`->`depth` References: http://stackoverflow.com/a/234329/623735 Args: path (str): Root path to begin file tree traversal (walk) ...
Get the type (socket, file, dir, symlink, ...) for the provided path
def get_type(full_path): """Get the type (socket, file, dir, symlink, ...) for the provided path""" status = {'type': []} if os.path.ismount(full_path): status['type'] += ['mount-point'] elif os.path.islink(full_path): status['type'] += ['symlink'] if os.path.isfile(full_path): ...
Use python builtin equivalents to unix `stat` command and return dict containing stat data about a file
def get_stat(full_path): """Use python builtin equivalents to unix `stat` command and return dict containing stat data about a file""" status = {} status['size'] = os.path.getsize(full_path) status['accessed'] = datetime.datetime.fromtimestamp(os.path.getatime(full_path)) status['modified'] = dateti...
Retrieve the access, modify, and create timetags for a path along with its size Arguments: path (str): full path to the file or directory to be statused status (dict): optional existing status to be updated/overwritten with new status values try_open (bool): whether to try to open the file ...
def path_status(path, filename='', status=None, deep=False, verbosity=0): """ Retrieve the access, modify, and create timetags for a path along with its size Arguments: path (str): full path to the file or directory to be statused status (dict): optional existing status to be updated/overwritte...
Recursively generate files (and thier stats) in the indicated directory Filter by the indicated file name extension (ext) Args: path (str): Root/base path to search. ext (str or list of str): File name extension(s). Only file paths that ".endswith()" this string will be returned ...
def generate_files(path='', ext='', level=None, dirs=False, files=True, verbosity=0): """ Recursively generate files (and thier stats) in the indicated directory Filter by the indicated file name extension (ext) Args: path (str): Root/base path to search. ext (str or list of str): File n...
Update the modify (modify) and change (ctime) timestamps of a file, create if necessary >>> from pugnlp.constants import DATA_PATH >>> filepath = os.path.join(DATA_PATH, 'tmpfilefortouch.txt') >>> touch(filepath).endswith('tmpfilefortouch.txt') True >>> os.path.isfile(filepath) True >>> os....
def touch(filepath, times=None, mkdir=False): """ Update the modify (modify) and change (ctime) timestamps of a file, create if necessary >>> from pugnlp.constants import DATA_PATH >>> filepath = os.path.join(DATA_PATH, 'tmpfilefortouch.txt') >>> touch(filepath).endswith('tmpfilefortouch.txt') True...
mkdir_p(filepath) then touch(filepath) >>> from pugnlp.constants import DATA_PATH >>> filepath = os.path.join(DATA_PATH, 'tmpdirfortouch', 'tmpfilefortouch.txt') >>> touch_p(filepath).endswith(os.path.join('tmpdirfortouch', 'tmpfilefortouch.txt')) True >>> os.path.isfile(filepath) True >>> ...
def touch_p(filepath, times=None, mkdir=True): """ mkdir_p(filepath) then touch(filepath) >>> from pugnlp.constants import DATA_PATH >>> filepath = os.path.join(DATA_PATH, 'tmpdirfortouch', 'tmpfilefortouch.txt') >>> touch_p(filepath).endswith(os.path.join('tmpdirfortouch', 'tmpfilefortouch.txt')) ...
r"""Cat a file iterating/yielding one line at a time, shell will execute: `sudo cat $file_path` so if your shell doesn't have sudo or cat, no joy Input: file_path(str): glob stars are fine >> for line in sudo_yield_file_lines('/etc/NetworkManager/system-connections/*')
def sudo_yield_file_lines(file_path='/etc/NetworkManager/system-connections/*'): r"""Cat a file iterating/yielding one line at a time, shell will execute: `sudo cat $file_path` so if your shell doesn't have sudo or cat, no joy Input: file_path(str): glob stars are fine >> for line ...
Parse json contents of string or file object or file path and return python nested dict/lists
def read_json(file_or_path): """Parse json contents of string or file object or file path and return python nested dict/lists""" try: with (open(file_or_path, 'r') if isinstance(file_or_path, (str, bytes)) else file_or_path) as f: obj = json.load(f) except IOError: obj = json.loa...
Check if set of ra,dec combinations are in footprint. Careful, input files must be in celestial coordinates. filename : Either healpix map or mangle polygon file ra,dec : Celestial coordinates Returns: inside : boolean array of coordinates in footprint
def inFootprint(footprint,ra,dec): """ Check if set of ra,dec combinations are in footprint. Careful, input files must be in celestial coordinates. filename : Either healpix map or mangle polygon file ra,dec : Celestial coordinates Returns: inside : boolean array of coordinates in ...
Take a pre-existing maglim map and divide it into chunks consistent with the catalog pixels.
def split(config,dirname='split',force=False): """ Take a pre-existing maglim map and divide it into chunks consistent with the catalog pixels. """ config = Config(config) filenames = config.getFilenames() #healpix = filenames['pix'].compressed() # Check that things are ok basedir,basename...
Loop through pixels containing catalog objects and calculate the magnitude limit. This gets a bit convoluted due to all the different pixel resolutions...
def run(self,field=None,simple=False,force=False): """ Loop through pixels containing catalog objects and calculate the magnitude limit. This gets a bit convoluted due to all the different pixel resolutions... """ if field is None: fields = [1,2] else: ...
Applies the correct time index to configurations
def apply_time_to_configurations(self, configurations, data): """Applies the correct time index to configurations""" time_value = None if data.get('time'): time_value = data['time'] # Only single time values are supported. For extents, just grab the first value ...
Filters the given variable set based on request parameters
def get_variable_set(self, variable_set, data): """Filters the given variable set based on request parameters""" if data.get('dynamic_layers'): variable_set = [] # TODO elif data.get('layers'): op, layer_ids = data['layers'].split(':', 1) op = op.lower() ...
Returns default values for the get image form
def _get_form_defaults(self): """Returns default values for the get image form""" return { 'response_format': 'html', 'bbox': self.service.full_extent, 'size': '400,400', 'dpi': 200, 'image_projection': pyproj.Proj(str(self.service.projection)...
Returns an image in the request format
def format_image(self, image, image_format, **kwargs): """Returns an image in the request format""" image_format = image_format.lower() accept = self.request.META['HTTP_ACCEPT'].split(',') if FORCE_WEBP and 'image/webp' in accept: image_format = 'webp' elif image_fo...
Render image interface
def get_render_configurations(self, request, **kwargs): """Render image interface""" data = self.process_form_data(self._get_form_defaults(), kwargs) variable_set = self.get_variable_set(self.service.variable_set.order_by('index'), data) base_config = ImageConfiguration( ex...
Returns default values for the identify form
def _get_form_defaults(self): """Returns default values for the identify form""" return { 'response_format': 'html', 'geometry_type': 'esriGeometryPoint', 'projection': pyproj.Proj(str(self.service.projection)), 'return_geometry': True, 'maxim...
Retrieve a specific term and condition. @param name of the terms. @param revision of the terms, if none provided it will return the latest. @return The list of terms. @raise ServerError
def get_terms(self, name, revision=None): """ Retrieve a specific term and condition. @param name of the terms. @param revision of the terms, if none provided it will return the latest. @return The list of terms. @raise ServerError """ url = '{}ter...
Opens and returns the NetCDF dataset associated with a service, or returns a previously-opened dataset
def open_dataset(self, service): """Opens and returns the NetCDF dataset associated with a service, or returns a previously-opened dataset""" if not self.dataset: path = os.path.join(SERVICE_DATA_ROOT, service.data_path) self.dataset = netCDF4.Dataset(path, 'r') return s...
Returns (width, height) for the given variable
def get_grid_spatial_dimensions(self, variable): """Returns (width, height) for the given variable""" data = self.open_dataset(self.service).variables[variable.variable] dimensions = list(data.dimensions) return data.shape[dimensions.index(variable.x_dimension)], data.shape[dimensions.i...
Returns this bbox normalized to match the ratio of the given size.
def _normalize_bbox(self, bbox, size): """Returns this bbox normalized to match the ratio of the given size.""" bbox_ratio = float(bbox.width) / float(bbox.height) size_ratio = float(size[0]) / float(size[1]) if round(size_ratio, 4) == round(bbox_ratio, 4): return bbox ...
Returns an image in the request format
def format_image(self, image, image_format, **kwargs): """Returns an image in the request format""" if image_format in ('png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp'): if image_format != 'webp' and FORCE_WEBP: # Always return WebP when supported by the browser a...
Returns a response object for the given image. Can be overridden to return different responses.
def create_response(self, request, image, content_type): """Returns a response object for the given image. Can be overridden to return different responses.""" return HttpResponse(content=image, content_type=content_type)
Returns a response object for the request. Can be overridden to return different responses.
def create_response(self, request, content, content_type): """Returns a response object for the request. Can be overridden to return different responses.""" return HttpResponse(content=content, content_type=content_type)
Truncates the filename if necessary, saves the model, and returns a response
def process_temporary_file(self, tmp_file): """Truncates the filename if necessary, saves the model, and returns a response""" #Truncate filename if necessary if len(tmp_file.filename) > 100: base_filename = tmp_file.filename[:tmp_file.filename.rfind(".")] tmp_file.filen...
2D labeling at zmax
def createLabels2D(self): """ 2D labeling at zmax """ logger.debug(" Creating 2D labels...") self.zmax = np.argmax(self.values,axis=1) self.vmax = self.values[np.arange(len(self.pixels),dtype=int),self.zmax] kwargs=dict(pixels=self.pixels,values=self.vmax,nside=self.nside, ...
Label contiguous regions of a (sparse) HEALPix map. Works by mapping HEALPix array to a Mollweide projection and applying scipy.ndimage.label Assumes non-nested HEALPix map. Parameters: pixels : Pixel values associated to (sparse) HEALPix array values : (Spa...
def labelHealpix(pixels, values, nside, threshold=0, xsize=1000): """ Label contiguous regions of a (sparse) HEALPix map. Works by mapping HEALPix array to a Mollweide projection and applying scipy.ndimage.label Assumes non-nested HEALPix map. Parameters: ...
Create a population of n randomly placed satellites within a survey mask. Satellites are distributed uniformly in log(distance) (kpc), uniformly in log(stellar_mass) (M_sol), and uniformly in physical half-light radius log(r_physical) (kpc). The ranges can be set by the user. Returns the simulated area (de...
def satellitePopulation(mask, nside_pix, n, range_distance=[5., 500.], range_stellar_mass=[1.e1, 1.e6], range_r_physical=[1.e-3, 2.], plot=False): """ Create a population of n randomly placed satellites within a surv...
Characterize labelled candidates in a multi-dimensional HEALPix map. Parameters: values : (Sparse) HEALPix array of data values nside : HEALPix dimensionality pixels : Pixel values associated to (sparse) HEALPix array zvalues : Values of the z-dimension (usually...
def findObjects(pixels, values, nside, zvalues, rev, good): """ Characterize labelled candidates in a multi-dimensional HEALPix map. Parameters: values : (Sparse) HEALPix array of data values nside : HEALPix dimensionality pixels : Pixel values associated ...
Create a population of n randomly placed satellites within a survey mask or catalog specified in the config file. Satellites are distributed uniformly in distance modulus, uniformly in log(stellar_mass) (M_sol), and uniformly in log(r_physical) (kpc). The ranges can be set by the user. Returns the simulate...
def satellitePopulationOrig(config, n, range_distance_modulus=[16.5, 24.], range_stellar_mass=[1.e2, 1.e5], range_r_physical=[5.e-3, 1.], mode='mask', plot=False): """ Crea...
>>> _get_query_params({'query': {'a': 1, 'c': 3, 'b': 5}}) 'a=1 b=5 c=3'
def _get_query_params(query): """ >>> _get_query_params({'query': {'a': 1, 'c': 3, 'b': 5}}) 'a=1 b=5 c=3' """ query_params = OrderedDict(sorted(query['query'].items())) return ' '.join(['{}={}'.format(k, v) for k, v in query_params.items()])
From the parsed command-line arguments, generate a dictionary of additional fields to be inserted into JSON logs (logstash_formatter module)
def make_extra_json_fields(args): """ From the parsed command-line arguments, generate a dictionary of additional fields to be inserted into JSON logs (logstash_formatter module) """ extra_json_fields = { 'data_group': _get_data_group(args.query), 'data_type': _get_data_type(args.que...
Take a file-like object and yield OrderedDicts to be inserted into raw spending database.
def process_csv(f): """ Take a file-like object and yield OrderedDicts to be inserted into raw spending database. """ reader = unicodecsv.DictReader(f, encoding=_ENCODING) for row in reader: month, year = parse_month_year(row['Return Month']) yield OrderedDict([ ('cu...
>>> parse_month_year('01/10/2012') (10, 2012)
def parse_month_year(date_string): """ >>> parse_month_year('01/10/2012') (10, 2012) """ match = re.match('\d{2}/(?P<month>\d{2})/(?P<year>\d{4})$', date_string.lower()) if not match: raise ValueError("Not format 'dd/mm/yyyy': '{}'".format(date_string)) month = i...
>>> parse_price('£16,000.00') 16000.0 >>> parse_price('-£16,000.00') -16000.0
def parse_price(price_string): """ >>> parse_price('£16,000.00') 16000.0 >>> parse_price('-£16,000.00') -16000.0 """ return float(re.sub('[£,]', '', price_string)) match = re.match('(?P<amount>-?£[\d,]+(\.\d{2})?)', price_string) if not match: raise ValueError("Charge not in...
Check if a file exists
def file_found(filename,force): """Check if a file exists""" if os.path.exists(filename) and not force: logger.info("Found %s; skipping..."%filename) return True else: return False
Perform truncated selection with elitism. :param individuals: :param toolbox: :return:
def generate_next_population(individuals, toolbox): """ Perform truncated selection with elitism. :param individuals: :param toolbox: :return: """ individuals = [toolbox.clone(ind) for ind in individuals] individuals.sort(key=lambda x: x.error) offspring = [] pop_size = len(indi...
Optimize a population of individuals. :param population: :param toolbox: :param mut_prob: :param ngen: :param archive: :param stats: :param verbose: :param history: :return:
def optimize(population, toolbox, ngen, archive=None, stats=None, verbose=False, history=None): """ Optimize a population of individuals. :param population: :param toolbox: :param mut_prob: :param ngen: :param archive: :param stats: :param verbose: :param history: :return: ...
Attempt to cast the string `value` to an int, and failing that, a float, failing that, raise a ValueError.
def try_number(value): """ Attempt to cast the string `value` to an int, and failing that, a float, failing that, raise a ValueError. """ for cast_function in [int, float]: try: return cast_function(value) except ValueError: pass raise ValueError("Unable...
Convert session duration metrics from seconds to milliseconds.
def convert_durations(metric): """ Convert session duration metrics from seconds to milliseconds. """ if metric[0] == 'avgSessionDuration' and metric[1]: new_metric = (metric[0], metric[1] * 1000) else: new_metric = metric return new_metric
:param request: HttpRequest with attached api_info :type request: HttpRequest :type view_kwargs: dict[str, object] :type capture_errors: bool :rtype: dict[str, object]
def read_parameters(request, view_kwargs=None, capture_errors=False): # noqa: C901 """ :param request: HttpRequest with attached api_info :type request: HttpRequest :type view_kwargs: dict[str, object] :type capture_errors: bool :rtype: dict[str, object] """ if view_kwargs is None: ...
Extract the first date from 'key' matching YYYY-MM-DD or YYYY-MM, and convert to datetime.
def to_datetime(date_key): ''' Extract the first date from 'key' matching YYYY-MM-DD or YYYY-MM, and convert to datetime. ''' match = re.search(r'\d{4}-\d{2}(-\d{2})?', date_key) formatter = '%Y-%m' if len(match.group()) == 10: formatter += '-%d' ...
Convert a float to a 38-precision Decimal
def float_to_decimal(f): """ Convert a float to a 38-precision Decimal """ n, d = f.as_integer_ratio() numerator, denominator = Decimal(n), Decimal(d) return DECIMAL_CONTEXT.divide(numerator, denominator)
Returns True if the value is a Dynamo-formatted value
def is_dynamo_value(value): """ Returns True if the value is a Dynamo-formatted value """ if not isinstance(value, dict) or len(value) != 1: return False subkey = six.next(six.iterkeys(value)) return subkey in TYPES_REV
Encode a list for the DynamoDB format
def encode_list(dynamizer, value): """ Encode a list for the DynamoDB format """ encoded_list = [] dict(map(dynamizer.raw_encode, value)) for v in value: encoded_type, encoded_value = dynamizer.raw_encode(v) encoded_list.append({ encoded_type: encoded_value, }) re...
Encode a set for the DynamoDB format
def encode_set(dynamizer, value): """ Encode a set for the DynamoDB format """ inner_value = next(iter(value)) inner_type = dynamizer.raw_encode(inner_value)[0] return inner_type + 'S', [dynamizer.raw_encode(v)[1] for v in value]
Encode a dict for the DynamoDB format
def encode_dict(dynamizer, value): """ Encode a dict for the DynamoDB format """ encoded_dict = {} for k, v in six.iteritems(value): encoded_type, encoded_value = dynamizer.raw_encode(v) encoded_dict[k] = { encoded_type: encoded_value, } return 'M', encoded_dict
Run the encoder on a value
def raw_encode(self, value): """ Run the encoder on a value """ if type(value) in self.encoders: encoder = self.encoders[type(value)] return encoder(self, value) raise ValueError("No encoder for value '%s' of type '%s'" % (value, type(value)))
Run the encoder on a dict of values
def encode_keys(self, keys): """ Run the encoder on a dict of values """ return dict(((k, self.encode(v)) for k, v in six.iteritems(keys) if not is_null(v)))
Same as encode_keys but a no-op if already in Dynamo format
def maybe_encode_keys(self, keys): """ Same as encode_keys but a no-op if already in Dynamo format """ ret = {} for k, v in six.iteritems(keys): if is_dynamo_value(v): return keys elif not is_null(v): ret[k] = self.encode(v) return ...
Run the decoder on a dict of values
def decode_keys(self, keys): """ Run the decoder on a dict of values """ return dict(((k, self.decode(v)) for k, v in six.iteritems(keys)))
Decode a dynamo value into a python value
def decode(self, dynamo_value): """ Decode a dynamo value into a python value """ type, value = next(six.iteritems(dynamo_value)) if type == STRING: return value elif type == BINARY: return Binary(value) elif type == NUMBER: return Decimal(valu...
Write a paragraph of 5 sentences.
def get_paragraph(self): """ Write a paragraph of 5 sentences. """ self.text = '' for x in range(randint(5, 12)): sentence = self._write_sentence() self.text = self.text + sentence return self.text
>>> parse_job_line( \ "* * * *,myquery,mycredentials,mytoken,performanceplatform\\n") ('* * * *', 'myquery', 'mycredentials', 'mytoken', 'performanceplatform') >>> parse_job_line(" ") is None True >>> parse_job_line("# comment") is None True
def parse_job_line(line): """ >>> parse_job_line( \ "* * * *,myquery,mycredentials,mytoken,performanceplatform\\n") ('* * * *', 'myquery', 'mycredentials', 'mytoken', 'performanceplatform') >>> parse_job_line(" ") is None True >>> parse_job_line("# comment") is None Tr...
Should we skip the job based on its number If the machine has a number at the end of its hostname (n), and we have m machines in the pool - on machine 1, run job 1, 1 + m, 1+2m etc on machine 2, run job 2, 2 + m , 2 + 2m etc Else run all the jobs
def skip_job(counter): """ Should we skip the job based on its number If the machine has a number at the end of its hostname (n), and we have m machines in the pool - on machine 1, run job 1, 1 + m, 1+2m etc on machine 2, run job 2, 2 + m , 2 + 2m etc Else run all the jobs """ try: ...
Returns a crontab with jobs from job path It replaces jobs previously generated by this function It preserves jobs not generated by this function
def generate_crontab(current_crontab, path_to_jobs, path_to_app, unique_id): """Returns a crontab with jobs from job path It replaces jobs previously generated by this function It preserves jobs not generated by this function """ set_disable_envar = '' if os.environ.get('DISABLE_COLLECTORS') ==...
Maps parameters to form field names
def map_parameters(cls, params): """Maps parameters to form field names""" d = {} for k, v in six.iteritems(params): d[cls.FIELD_MAP.get(k.lower(), k)] = v return d
Function generator to create functions for converting from world coordinates to image coordinates
def world_to_image(bbox, size): """Function generator to create functions for converting from world coordinates to image coordinates""" px_per_unit = (float(size[0])/bbox.width, float(size[1])/bbox.height) return lambda x,y: ((x-bbox.xmin) * px_per_unit[0], size[1] - (y-bbox.ymin)*px_per_unit[1])
Returns a copy of this image warped to a target size and bounding box
def warp(self, target_bbox, target_size=None): """Returns a copy of this image warped to a target size and bounding box""" # Determine target size based on pixels per unit of the source image and the target bounding box reprojected # to the source projection. if not target_size: ...
Try to take the first department code, or fall back to string as passed
def try_get_department(department_or_code): """ Try to take the first department code, or fall back to string as passed """ try: value = take_first_department_code(department_or_code) except AssertionError: value = department_or_code if value in DEPARTMENT_MAPPING: value...
Fetch user data. Raise a ServerError if an error occurs in the request process. @param username the user's name. @param macaroons the encoded macaroons string.
def get_user(self, username, macaroons): """Fetch user data. Raise a ServerError if an error occurs in the request process. @param username the user's name. @param macaroons the encoded macaroons string. """ url = '{}u/{}'.format(self.url, username) return make_...
Retrieve the debug information from the identity manager.
def debug(self): """Retrieve the debug information from the identity manager.""" url = '{}debug/status'.format(self.url) try: return make_request(url, timeout=self.timeout) except ServerError as err: return {"error": str(err)}
Send user identity information to the identity manager. Raise a ServerError if an error occurs in the request process. @param username The logged in user. @param json_document The JSON payload for login.
def login(self, username, json_document): """Send user identity information to the identity manager. Raise a ServerError if an error occurs in the request process. @param username The logged in user. @param json_document The JSON payload for login. """ url = '{}u/{}'.fo...
Discharge the macarooon for the identity. Raise a ServerError if an error occurs in the request process. @param username The logged in user. @param macaroon The macaroon returned from the charm store. @return The resulting base64 encoded macaroon. @raises ServerError when makin...
def discharge(self, username, macaroon): """Discharge the macarooon for the identity. Raise a ServerError if an error occurs in the request process. @param username The logged in user. @param macaroon The macaroon returned from the charm store. @return The resulting base64 enco...
Set extra info for the given user. Raise a ServerError if an error occurs in the request process. @param username The username for the user to update. @param info The extra info as a JSON encoded string, or as a Python dictionary like object.
def set_extra_info(self, username, extra_info): """Set extra info for the given user. Raise a ServerError if an error occurs in the request process. @param username The username for the user to update. @param info The extra info as a JSON encoded string, or as a Python dict...
Discharge token for a user. Raise a ServerError if an error occurs in the request process. @param username The logged in user. @return The resulting base64 encoded discharged token.
def discharge_token(self, username): """Discharge token for a user. Raise a ServerError if an error occurs in the request process. @param username The logged in user. @return The resulting base64 encoded discharged token. """ url = '{}discharge-token-for-user?username={...
Get extra info for the given user. Raise a ServerError if an error occurs in the request process. @param username The username for the user who's info is being accessed.
def get_extra_info(self, username): """Get extra info for the given user. Raise a ServerError if an error occurs in the request process. @param username The username for the user who's info is being accessed. """ url = self._get_extra_info_url(username) return make_requ...
Reads an isochrone in the old Padova format (Girardi 2002, Marigo 2008) and determines the age (log10 yrs and Gyr), metallicity (Z and [Fe/H]), and creates arrays with the initial stellar mass and corresponding magnitudes for each step along the isochrone. http://stev.oapd.inaf.i...
def _parse(self,filename): """ Reads an isochrone in the old Padova format (Girardi 2002, Marigo 2008) and determines the age (log10 yrs and Gyr), metallicity (Z and [Fe/H]), and creates arrays with the initial stellar mass and corresponding magnitudes for each step along...
Do all required parameters have values?
def is_complete(self): """Do all required parameters have values?""" return all(p.name in self.values for p in self.parameters if p.required)
Cleans and returns the given value, or raises a ParameterNotValidError exception
def clean(self, value): """Cleans and returns the given value, or raises a ParameterNotValidError exception""" for parameter_obj in self.types: try: return parameter_obj.clean(value) except ParameterNotValidError: continue raise Parameter...