text
stringlengths
81
112k
Return the number of plants reached by the sprinkler. Returns a large penalty for sprinkler locations outside the map. def eval_fitness(self, chromosome): """ Return the number of plants reached by the sprinkler. Returns a large penalty for sprinkler locations outside the map. ...
Return a version of the ASCII map showing reached crop cells. def map_sprinkler(self, sx, sy, watered_crop='^', watered_field='_', dry_field=' ', dry_crop='x'): """ Return a version of the ASCII map showing reached crop cells. """ # convert strings (rows) to lists of characters for easi...
\ The index view, which basically just displays a button and increments a counter. def index(request, template_name="index.html"): """\ The index view, which basically just displays a button and increments a counter. """ if request.GET.get('ic-request'): counter, created = Counter.o...
Get the fitness score for a chromosome, using the cached value if available. def get_fitness(self, chromosome): """ Get the fitness score for a chromosome, using the cached value if available. """ fitness = self.fitness_cache.get(chromosome.dna) if fitness is None: fitness = self.e...
Simulate competition/survival of the fittest. The fitness of each chromosome is used to calculate a survival probability based on how it compares to the overall fitness range of the run and the fitness range of the current generation. The ``abs_fit_weight`` and ``rel_fit_weight...
Reproduces the population from a pool of surviving chromosomes until a target population size is met. Offspring are created by selecting a survivor. Survivors with higher fitness have a greater chance to be selected for reproduction. Genetic crossover events may occur for each o...
Call every chromosome's ``mutate`` method. p_mutate: probability of mutation in [0, 1] def mutate(self, chromosomes, p_mutate): """ Call every chromosome's ``mutate`` method. p_mutate: probability of mutation in [0, 1] """ assert 0 <= p_mutate <= 1...
Run a standard genetic algorithm simulation for a set number of generations (iterations), each consisting of the following ordered steps: 1. competition/survival of the fittest (``compete`` method) 2. reproduction (``reproduce`` method) 3. mutation (``mutate`` me...
Create 1 or more chromosomes with randomly generated DNA. gene_length: int (or sequence of ints) describing gene DNA length n: number of chromosomes to create (default=1); returns a list if n>1, else a single chromosome gene_class: subclass of ``ga.chromosomes.BaseGene`` to use for genes ...
Replace this chromosome's DNA with new DNA of equal length, assigning the new DNA to the chromosome's genes sequentially. For example, if a chromosome contains these genes... 1. 100100 2. 011011 ...and the new DNA is 111111000000, the genes become: ...
Exchange DNA with another chromosome of equal length at one or two common points. For example, consider chromosomes: 1. 11110000 2. 00001111 If the crossover point is 4, the exchange results in a new DNA arrangement: 1. 11111111 2. 00000000 ...
Check all genes in this chromosome for mutation. p_mutate: probability for mutation to occur def mutate(self, p_mutate): """ Check all genes in this chromosome for mutation. p_mutate: probability for mutation to occur """ assert 0 <= p_mutate <= 1 ...
Return a new instance of this chromosome by copying its genes. def copy(self): """ Return a new instance of this chromosome by copying its genes. """ genes = [g.copy() for g in self.genes] return type(self)(genes)
Assert that every DNA choice is represented by exactly one gene. def check_genes(self): """ Assert that every DNA choice is represented by exactly one gene. """ gene_dna_set = set([g.dna for g in self.genes]) assert gene_dna_set == self.dna_choices_set
Format a crash report and send it somewhere relevant. There are two types of crashes: fatal crashes (backend errors) or non-fatal ones (just reporting a glitch, but the api call did not fail) def report_error(title=None, data={}, caught=None, is_fatal=False): """Format a crash report and send it somewhere ...
Add generic stats to the error report def populate_error_report(data): """Add generic stats to the error report""" # Did pymacaron_core set a call_id and call_path? call_id, call_path = '', '' if hasattr(stack.top, 'call_id'): call_id = stack.top.call_id if hasattr(stack.top, 'call_path'):...
Return the crash_handler to pass to pymacaron_core, with optional error decoration def generate_crash_handler_decorator(error_decorator=None): """Return the crash_handler to pass to pymacaron_core, with optional error decoration""" def crash_handler(f): """Return a decorator that reports failed api ca...
Create a metric. def create(self, **kwargs): """Create a metric.""" url_str = self.base_url if 'tenant_id' in kwargs: url_str = url_str + '?tenant_id=%s' % kwargs['tenant_id'] del kwargs['tenant_id'] data = kwargs['jsonbody'] if 'jsonbody' in kwargs else kwargs ...
Parses the request result and returns the JSON object. Handles all errors. def get_json_results(self, response): ''' Parses the request result and returns the JSON object. Handles all errors. ''' try: # return the proper JSON object, or error code if request didn't go throug...
Returns a single list containing up to 'limit' Result objects Will keep requesting until quota is met Will also truncate extra results to return exactly the given quota def search_all(self, quota=50, format='json'): ''' Returns a single list containing up to 'limit' Result objects ...
Reformat parameters into dict of format expected by the API. def format_parameters(params): '''Reformat parameters into dict of format expected by the API.''' if not params: return {} # expect multiple invocations of --parameters but fall back # to ; delimited if only one --parameters is spec...
Delete a specific alarm. def delete(self, **kwargs): """Delete a specific alarm.""" url_str = self.base_url + '/%s' % kwargs['alarm_id'] resp = self.client.delete(url_str) return resp
History of a specific alarm. def history(self, **kwargs): """History of a specific alarm.""" url_str = self.base_url + '/%s/state-history' % kwargs['alarm_id'] del kwargs['alarm_id'] if kwargs: url_str = url_str + '?%s' % parse.urlencode(kwargs, True) resp = self.cli...
History list of alarm state. def history_list(self, **kwargs): """History list of alarm state.""" url_str = self.base_url + '/state-history/' if 'dimensions' in kwargs: dimstr = self.get_dimensions_url_string(kwargs['dimensions']) kwargs['dimensions'] = dimstr if...
Return version details of the running server api def do_version(): """Return version details of the running server api""" v = ApiPool.ping.model.Version( name=ApiPool().current_server_name, version=ApiPool().current_server_api.get_version(), container=get_container_version(), ) ...
Create metric. def do_metric_create(mc, args): '''Create metric.''' fields = {} fields['name'] = args.name if args.dimensions: fields['dimensions'] = utils.format_parameters(args.dimensions) fields['timestamp'] = args.time fields['value'] = args.value if args.value_meta: fie...
Create metric from raw json body. def do_metric_create_raw(mc, args): '''Create metric from raw json body.''' try: mc.metrics.create(**args.jsonbody) except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\n%s' % (he.message, he.details)) else: pr...
List names of metrics. def do_metric_name_list(mc, args): '''List names of metrics.''' fields = {} if args.dimensions: fields['dimensions'] = utils.format_dimensions_query(args.dimensions) if args.limit: fields['limit'] = args.limit if args.offset: fields['offset'] = args.of...
List metrics for this tenant. def do_metric_list(mc, args): '''List metrics for this tenant.''' fields = {} if args.name: fields['name'] = args.name if args.dimensions: fields['dimensions'] = utils.format_dimensions_query(args.dimensions) if args.limit: fields['limit'] = arg...
List names of metric dimensions. def do_dimension_name_list(mc, args): '''List names of metric dimensions.''' fields = {} if args.metric_name: fields['metric_name'] = args.metric_name if args.limit: fields['limit'] = args.limit if args.offset: fields['offset'] = args.offset ...
List names of metric dimensions. def do_dimension_value_list(mc, args): '''List names of metric dimensions.''' fields = {} fields['dimension_name'] = args.dimension_name if args.metric_name: fields['metric_name'] = args.metric_name if args.limit: fields['limit'] = args.limit if ...
List measurement statistics for the specified metric. def do_metric_statistics(mc, args): '''List measurement statistics for the specified metric.''' statistic_types = ['AVG', 'MIN', 'MAX', 'COUNT', 'SUM'] statlist = args.statistics.split(',') for stat in statlist: if stat.upper() not in statis...
Describe the notification. def do_notification_show(mc, args): '''Describe the notification.''' fields = {} fields['notification_id'] = args.id try: notification = mc.notifications.get(**fields) except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\...
List notifications for this tenant. def do_notification_list(mc, args): '''List notifications for this tenant.''' fields = {} if args.limit: fields['limit'] = args.limit if args.offset: fields['offset'] = args.offset if args.sort_by: sort_by = args.sort_by.split(',') ...
Delete notification. def do_notification_delete(mc, args): '''Delete notification.''' fields = {} fields['notification_id'] = args.id try: mc.notifications.delete(**fields) except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\n%s' % (he.message, he...
Update notification. def do_notification_update(mc, args): '''Update notification.''' fields = {} fields['notification_id'] = args.id fields['name'] = args.name fields['type'] = args.type fields['address'] = args.address if not _validate_notification_period(args.period, args.type.upper()):...
Create an alarm definition. def do_alarm_definition_create(mc, args): '''Create an alarm definition.''' fields = {} fields['name'] = args.name if args.description: fields['description'] = args.description fields['expression'] = args.expression if args.alarm_actions: fields['alar...
List alarm definitions for this tenant. def do_alarm_definition_list(mc, args): '''List alarm definitions for this tenant.''' fields = {} if args.name: fields['name'] = args.name if args.dimensions: fields['dimensions'] = utils.format_dimensions_query(args.dimensions) if args.severi...
Delete the alarm definition. def do_alarm_definition_delete(mc, args): '''Delete the alarm definition.''' fields = {} fields['alarm_id'] = args.id try: mc.alarm_definitions.delete(**fields) except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\n%s' ...
Update the alarm definition. def do_alarm_definition_update(mc, args): '''Update the alarm definition.''' fields = {} fields['alarm_id'] = args.id fields['name'] = args.name fields['description'] = args.description fields['expression'] = args.expression fields['alarm_actions'] = _arg_split_...
Patch the alarm definition. def do_alarm_definition_patch(mc, args): '''Patch the alarm definition.''' fields = {} fields['alarm_id'] = args.id if args.name: fields['name'] = args.name if args.description: fields['description'] = args.description if args.expression: fiel...
List alarms for this tenant. def do_alarm_list(mc, args): '''List alarms for this tenant.''' fields = {} if args.alarm_definition_id: fields['alarm_definition_id'] = args.alarm_definition_id if args.metric_name: fields['metric_name'] = args.metric_name if args.metric_dimensions: ...
Describe the alarm. def do_alarm_show(mc, args): '''Describe the alarm.''' fields = {} fields['alarm_id'] = args.id try: alarm = mc.alarms.get(**fields) except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\n%s' % (he.message, he.details)) else:...
Update the alarm state. def do_alarm_update(mc, args): '''Update the alarm state.''' fields = {} fields['alarm_id'] = args.id if args.state.upper() not in state_types: errmsg = ('Invalid state, not one of [' + ', '.join(state_types) + ']') print(errmsg) ...
Delete the alarm. def do_alarm_delete(mc, args): '''Delete the alarm.''' fields = {} fields['alarm_id'] = args.id try: mc.alarms.delete(**fields) except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\n%s' % (he.message, he.details)) else: ...
Count alarms. def do_alarm_count(mc, args): '''Count alarms.''' fields = {} if args.alarm_definition_id: fields['alarm_definition_id'] = args.alarm_definition_id if args.metric_name: fields['metric_name'] = args.metric_name if args.metric_dimensions: fields['metric_dimension...
Alarm state transition history. def do_alarm_history(mc, args): '''Alarm state transition history.''' fields = {} fields['alarm_id'] = args.id if args.limit: fields['limit'] = args.limit if args.offset: fields['offset'] = args.offset try: alarm = mc.alarms.history(**fiel...
List alarms state history. def do_alarm_history_list(mc, args): '''List alarms state history.''' fields = {} if args.dimensions: fields['dimensions'] = utils.format_parameters(args.dimensions) if args.starttime: _translate_starttime(args) fields['start_time'] = args.starttime ...
List notification types supported by monasca. def do_notification_type_list(mc, args): '''List notification types supported by monasca.''' try: notification_types = mc.notificationtypes.list() except (osc_exc.ClientException, k_exc.HttpError) as he: raise osc_exc.CommandError('%s\n%s' % (h...
A decorator for flask api methods that validates auth0 tokens, hence ensuring that the user is authenticated. Code coped from: https://github.com/auth0/auth0-python/tree/master/examples/flask-api def requires_auth(f): """A decorator for flask api methods that validates auth0 tokens, hence ensuring that...
A decorator that adds the authentication header to requests arguments def add_auth(f): """A decorator that adds the authentication header to requests arguments""" def add_auth_decorator(*args, **kwargs): token = get_user_token() if 'headers' not in kwargs: kwargs['headers'] = {} ...
Validate an auth0 token. Returns the token's payload, or an exception of the type: def load_auth_token(token, load=True): """Validate an auth0 token. Returns the token's payload, or an exception of the type:""" assert get_config().jwt_secret, "No JWT secret configured for pymacaron" assert get_con...
Validate auth0 tokens passed in the request's header, hence ensuring that the user is authenticated. Code copied from: https://github.com/auth0/auth0-python/tree/master/examples/flask-api Return a PntCommonException if failed to validate authentication. Otherwise, return the token's payload (Also store...
Generate a new JWT token for this user_id. Default expiration date is 1 year from creation time def generate_token(user_id, expire_in=None, data={}, issuer=None, iat=None): """Generate a new JWT token for this user_id. Default expiration date is 1 year from creation time""" assert user_id, "No user_id ...
Return the authenticated user's auth token def get_user_token(): """Return the authenticated user's auth token""" if not hasattr(stack.top, 'current_user'): return '' current_user = stack.top.current_user return current_user.get('token', '')
Return the issuer in which this user's token was created def get_token_issuer(): """Return the issuer in which this user's token was created""" try: current_user = stack.top.current_user return current_user.get('iss', get_config().jwt_issuer) except Exception: pass return get_co...
Returns a list of result objects, with the url for the next page MsCognitive search url. def _search(self, limit, format): ''' Returns a list of result objects, with the url for the next page MsCognitive search url. ''' limit = min(limit, self.MAX_SEARCH_PER_QUERY) payload = { ...
Create a notification. def create(self, **kwargs): """Create a notification.""" body = self.client.create(url=self.base_url, json=kwargs) return body
Get the details for a specific notification. def get(self, **kwargs): """Get the details for a specific notification.""" # NOTE(trebskit) should actually be find_one, but # monasca does not support expected response format url = '%s/%s' % (self.base_url, kwargs['notification_id']) ...
Delete a notification. def delete(self, **kwargs): """Delete a notification.""" url = self.base_url + '/%s' % kwargs['notification_id'] resp = self.client.delete(url=url) return resp
Create an alarm definition. def create(self, **kwargs): """Create an alarm definition.""" resp = self.client.create(url=self.base_url, json=kwargs) return resp
Update a specific alarm definition. def update(self, **kwargs): """Update a specific alarm definition.""" url_str = self.base_url + '/%s' % kwargs['alarm_id'] del kwargs['alarm_id'] resp = self.client.create(url=url_str, method='PUT', ...
Return calculated y-values for the domain of x-values in [1, num_x]. def compute_y(self, coefficients, num_x): """ Return calculated y-values for the domain of x-values in [1, num_x]. """ y_vals = [] for x in range(1, num_x + 1): y = sum([c * x ** i for i, c in enumerate(coefficien...
Return an error value by finding the absolute difference for each element in a list of solution-generated y-values versus expected values. Compounds error by 50% for each negative coefficient in the solution. solution_y: list of y-values produced by a solution coefficients: list of p...
Evaluate the polynomial equation using coefficients represented by a solution/chromosome, returning its error as the solution's fitness. return: fitness value def eval_fitness(self, chromosome): """ Evaluate the polynomial equation using coefficients represented by a solution/...
Read the current configuration of a myStrom device. def read_config(ip, mac): """Read the current configuration of a myStrom device.""" click.echo("Read configuration from %s" % ip) request = requests.get( 'http://{}/{}/{}/'.format(ip, URI, mac), timeout=TIMEOUT) print(request.json())
Write the current configuration of a myStrom button. def write_config(ip, mac, single, double, long, touch): """Write the current configuration of a myStrom button.""" click.echo("Write configuration to device %s" % ip) data = { 'single': single, 'double': double, 'long': long, ...
Write the configuration for Home Assistant to a myStrom button. def write_ha_config(ip, mac, hass, port, id): """Write the configuration for Home Assistant to a myStrom button.""" click.echo("Write configuration for Home Assistant to device %s..." % ip) action = "get://{1}:{2}/api/mystrom?{0}={3}" dat...
Reset the current configuration of a myStrom WiFi Button. def reset_config(ip, mac): """Reset the current configuration of a myStrom WiFi Button.""" click.echo("Reset configuration of button %s..." % ip) data = { 'single': "", 'double': "", 'long': "", 'touch': "", } ...
Switch the bulb on with the given color. def color(ip, mac, hue, saturation, value): """Switch the bulb on with the given color.""" bulb = MyStromBulb(ip, mac) bulb.set_color_hsv(hue, saturation, value)
Try fetching instance metadata at 'curl http://169.254.169.254/latest/meta-data/' to see if host is on an ec2 instance def is_ec2_instance(): """Try fetching instance metadata at 'curl http://169.254.169.254/latest/meta-data/' to see if host is on an ec2 instance""" # Note: this code assumes that dock...
Take a datetime, either as a string or a datetime.datetime object, and return the corresponding epoch def to_epoch(t): """Take a datetime, either as a string or a datetime.datetime object, and return the corresponding epoch""" if isinstance(t, str): if '+' not in t: t = t + '+00:00'...
Return the version of the docker container running the present server, or '' if not in a container def get_container_version(): """Return the version of the docker container running the present server, or '' if not in a container""" root_dir = os.path.dirname(os.path.realpath(sys.argv[0])) version_...
Return a generic name for this app, usefull when reporting to monitoring/logging frameworks def get_app_name(): """Return a generic name for this app, usefull when reporting to monitoring/logging frameworks""" conf = get_config() if is_ec2_instance(): return conf.app_name_live if hasattr(conf, 'app...
Run all examples. def run_all(plot=True, seed=None): """ Run all examples. """ if seed is not None: import random random.seed(seed) print("Running biggest_multiple.py") biggest_multiple.run(plot=plot) print("Running polynomials.py") polynomials.run(plot=plot) print("Runni...
Return a new instance of this gene class with random DNA, with characters chosen from ``GENETIC_MATERIAL_OPTIONS``. length: the number of characters in the randomized DNA **kwargs: forwarded to the ``cls`` constructor def create_random(cls, length, **kwargs): """ Retu...
Simulate mutation against a probability. p_mutate: probability for mutation to occur def mutate(self, p_mutate): """ Simulate mutation against a probability. p_mutate: probability for mutation to occur """ new_dna = [] for bit in self.dna: ...
Return a new instance of this gene with the same DNA. def copy(self): """ Return a new instance of this gene with the same DNA. """ return type(self)(self.dna, suppressed=self.suppressed, name=self.name)
Check that a DNA string only contains characters in ``GENETIC_MATERIAL_OPTIONS``. def _check_dna(self, dna): """ Check that a DNA string only contains characters in ``GENETIC_MATERIAL_OPTIONS``. """ valid_chars = set(self.GENETIC_MATERIAL_OPTIONS) assert all(char in valid_chars for char in dna)
Check each element for mutation, swapping "0" for "1" and vice-versa. def mutate(self, p_mutate): """ Check each element for mutation, swapping "0" for "1" and vice-versa. """ new_dna = [] for bit in self.dna: if random.random() < p_mutate: b...
Deeply merge two dictionaries, overriding existing keys in the base. :param base: The base dictionary which will be merged into. :param extra: The dictionary to merge into the base. Keys from this dictionary will take precedence. def deep_merge(base, extra): """ Deeply merge two dictionaries, ...
Returns an monitoring API client. def make_client(api_version, session=None, endpoint=None, service_type='monitoring'): """Returns an monitoring API client.""" client_cls = utils.get_client_class('monitoring', api_version, VERSION_MAP) c = client_cls( session=session, servi...
Dynamically creates subclass of MigratingCommand. Method takes name of the function, module it is part of and builds the subclass of :py:class:`MigratingCommand`. Having a subclass of :py:class:`cliff.command.Command` is mandatory for the osc-lib integration. :param name: name of the function ...
Returns or reuses session. Method takes care of providing instance of session object for the client. :param kwargs: all params (without api_version) client was initialized with :type kwargs: dict :returns: session object :rtype keystoneauth1.session.Session def _session(kwargs): """Retur...
Loads an instance of the class from a file. Parameters ---------- path : str Path to an HDF5 file. Examples -------- This is an abstract data type, but let us say that ``Foo`` inherits from ``Saveable``. To construct an object of this class from a fi...
Decorator to register a class. def register(cls, name): """Decorator to register a class.""" def register_decorator(reg_cls): def name_func(self): return name reg_cls.name = property(name_func) assert issubclass(reg_cls, cls), \ "Must ...
Constructs an instance of an object given its name. def construct(cls, name, *args, **kwargs): """ Constructs an instance of an object given its name. """ return cls.REGISTRY[name](*args, **kwargs)
Loads and returns a ConfigParser from ``~/.deepdish.conf``. def config(): """ Loads and returns a ConfigParser from ``~/.deepdish.conf``. """ conf = ConfigParser() # Set up defaults conf.add_section('io') conf.set('io', 'compression', 'zlib') conf.read(os.path.expanduser('~/.deepdish.c...
Resizes the image according to a factor. The image is pre-filtered with a Gaussian and then resampled with bilinear interpolation. This function uses scikit-image and essentially combines its `pyramid_reduce` with `pyramid_expand` into one function. Returns the same object if factor is 1, not a copy. ...
Takes an image and returns its grayscale version by averaging the color channels. if an alpha channel is present, it will simply be ignored. If a grayscale image is given, the original image is returned. Parameters ---------- image : ndarray, ndim 2 or 3 RGB or grayscale image. Return...
Crops an image in the center. Parameters ---------- size : tuple, (height, width) Finally size after cropping. def crop(im, size): """ Crops an image in the center. Parameters ---------- size : tuple, (height, width) Finally size after cropping. """ diff = [im....
Crops an image in the center. Parameters ---------- size : tuple, (height, width) Finally size after cropping. def crop_or_pad(im, size, value=0): """ Crops an image in the center. Parameters ---------- size : tuple, (height, width) Finally size after cropping. """...
Loads an image from file. Parameters ---------- path : str Path to image file. dtype : np.dtype Defaults to ``np.float64``, which means the image will be returned as a float with values between 0 and 1. If ``np.uint8`` is specified, the values will be between 0 and 255 a...
Load image using PIL/Pillow without any processing. This is particularly useful for palette images, which will be loaded using their palette index values as opposed to `load` which will convert them to RGB. Parameters ---------- path : str Path to image file. def load_raw(path): """ ...
Saves an image to file. If the image is type float, it will assume to have values in [0, 1]. Parameters ---------- path : str Path to which the image will be saved. im : ndarray (image) Image. def save(path, im): """ Saves an image to file. If the image is type float,...
Use an integral image to integrate over a given window. Parameters ---------- ii : ndarray Integral image. r0, c0 : int Top-left corner of block to be summed. r1, c1 : int Bottom-right corner of block to be summed. Returns ------- S : int Integral (sum) ...
Moves the contents of image without changing the image size. The missing values are given a specified fill value. Parameters ---------- img : array Image. offset : (vertical_offset, horizontal_offset) Tuple of length 2, specifying the offset along the two axes. fill_value : dtyp...
Returns a bounding box of the support. Parameters ---------- alpha : ndarray, ndim=2 Any one-channel image where the background has zero or low intensity. threshold : float The threshold that divides background from foreground. Returns ------- bounding_box : (top, left, bot...
Similar to `bounding_box`, except returns the bounding box as a binary map the same size as the input. Same parameters as `bounding_box`. Returns ------- binary_map : ndarray, ndim=2, dtype=np.bool_ Binary map with True if object and False if background. def bounding_box_as_binary_map(alp...
Takes a set of images and yields randomly chosen patches of specified size. Parameters ---------- images : iterable The images have to be iterable, and each element must be a Numpy array with at least two spatial 2 dimensions as the first and second axis. patch_shape : tuple, length 2 ...