text
stringlengths
81
112k
Euler method integration. This function wraps the Euler class. :param dfun: derivative function of the system. The differential system arranged as a series of first-order equations: \\dot{X} = dfun(t, x) :param xzero: the initial condition of the system ...
Verlet method integration. This function wraps the Verlet class. :param dfun: second derivative function of the system. The differential system arranged as a series of second-order equations: \ddot{X} = dfun(t, x) :param xzero: the initial condition of th...
Backward Euler method integration. This function wraps BackwardEuler. :param dfun: Derivative function of the system. The differential system arranged as a series of first-order equations: \dot{X} = dfun(t, x) :param xzero: The initial condition of the sy...
Add a request object def add_request(self, request): """ Add a request object """ # Duplicate request name? if request.name in self.requests: raise ValueError('redefinition of request "{0}"'.format(request.name)) self.requests[request.name] = request ...
Add a response header def add_header(self, key, value): """ Add a response header """ assert isinstance(key, str), 'header key must be of type str' assert isinstance(value, str), 'header value must be of type str' self.headers[key] = value
Send an HTTP response def response(self, status, content_type, content, headers=None): """ Send an HTTP response """ assert not isinstance(content, (str, bytes)), 'response content cannot be of type str or bytes' response_headers = [('Content-Type', content_type)] if he...
Send a plain-text response def response_text(self, status, text=None, content_type='text/plain', encoding='utf-8', headers=None): """ Send a plain-text response """ if text is None: if isinstance(status, str): text = status else: ...
Send a JSON response def response_json(self, status, response, content_type='application/json', encoding='utf-8', headers=None, jsonp=None): """ Send a JSON response """ encoder = JSONEncoder( check_circular=self.app.validate_output, allow_nan=False, ...
Reconstructs the request URL using the algorithm provided by PEP3333 def reconstruct_url(self, path_info=None, query_string=None, relative=False): """ Reconstructs the request URL using the algorithm provided by PEP3333 """ environ = self.environ if relative: url = ...
Read from files found in XDG-specified system-wide configuration paths, defaulting to ``/etc/xdg``. Depends on ``XDG_CONFIG_DIRS`` environment variable. :param name: application or configuration set name :param extension: file extension to look for :return: a `.Configuration` instance with values r...
Read from file found in XDG-specified configuration home directory, expanding to ``${HOME}/.config/name.extension`` by default. Depends on ``XDG_CONFIG_HOME`` or ``HOME`` environment variables. :param name: application or configuration set name :param extension: file extension to look for :return: ...
Read environment variables starting with ``NAME_``, where subsequent underscores are interpreted as namespaces. Underscores can be retained as namespaces by doubling them up, e.g. ``NAME_SPA__CE_KEY`` would be accessible in the resulting `.Configuration` as ``c.spa_ce.key``, where ``c`` is the `.Configu...
Read values from a file provided as a environment variable ``NAME_CONFIG_FILE``. :param name: environment variable prefix to look for (without the ``_CONFIG_FILE``) :param extension: *(unused)* :return: a `.Configuration`, possibly `.NotConfigured` def read_envvar_file(name, extension): ""...
Read values from a file located in a directory specified by a particular environment file. ``read_envvar_dir('HOME', 'example', 'yaml')`` would look for a file at ``/home/user/example.yaml``. When the environment variable isn't set or the file does not exist, `NotConfigured` will be returned. :para...
Generates loaders in the specified order. Arguments can be `.Locality` instances, producing the loader(s) available for that locality, `str` instances (used as file path templates) or `callable`s. These can be mixed: .. code-block:: python # define a load order using predefined user-local loc...
Read a `.Configuration` instance from file-like objects. :param fps: file-like objects (supporting ``.read()``) :param missing: policy to be used when a configured key is missing, either as a `.Missing` instance or a default value :return: a `.Configuration` instance providing values from *fps* ...
Read a `.Configuration` instance from named files. :param fnames: name of the files to ``open()`` :param default: `dict` or `.Configuration` to use when a file does not exist (default is to raise a `FileNotFoundError`) :param missing: policy to be used when a configured key is missing, either ...
Read a `.Configuration` instance from strings. :param strings: configuration contents :param missing: policy to be used when a configured key is missing, either as a `.Missing` instance or a default value :return: a `.Configuration` instance providing values from *strings* :rtype: `.Configurati...
Read a `.Configuration` instance by name, trying to read from files in increasing significance. The default load order is `.system`, `.user`, `.application`, `.environment`. Multiple names are combined with multiple loaders using names as the 'inner loop / selector', loading ``/etc/name1.yaml`` and ``/...
Acquire lock. Blocks until acquired if `block` is `True`, otherwise returns `False` if the lock could not be acquired. def acquire(self, block=True): """Acquire lock. Blocks until acquired if `block` is `True`, otherwise returns `False` if the lock could not be acquired.""" while True: # Tr...
Refresh an existing lock to prevent it from expiring. Uses a LUA (EVAL) script to ensure only a lock which we own is being overwritten. Returns True if refresh succeeded, False if not. def refresh(self): """Refresh an existing lock to prevent it from expiring. Uses a LUA (EVAL) script t...
Run process if nobody else is, otherwise wait until we're needed. Never returns. def run(self): """Run process if nobody else is, otherwise wait until we're needed. Never returns.""" log.info("Waiting for lock, currently held by %s", self.lock.who()) if self.lock.acquire(): log.inf...
Spawn process. def spawn(self, command): """Spawn process.""" if self.shell: args = command else: args = shlex.split(command) return subprocess.Popen(args, shell=self.shell)
Clean up, making sure the process is stopped before we pack up and go home. def cleanup(self): """Clean up, making sure the process is stopped before we pack up and go home.""" if self.process is None: # Process wasn't running yet, so nothing to worry about return if self.process.p...
Handles signals, surprisingly. def handle_signal(self, sig, frame): """Handles signals, surprisingly.""" if sig in [signal.SIGINT]: log.warning("Ctrl-C pressed, shutting down...") if sig in [signal.SIGTERM]: log.warning("SIGTERM received, shutting down...") self....
Main entry point for the validation engine. :param data: The incoming data, as a dictionary object. :param schema: The schema from which data will be validated against def validate(data, schema, defined_keys=False): """ Main entry point for the validation engine. :param data: The incoming data, a...
Traverses the dictionary, recursing onto itself if it sees appropriate key/value pairs that indicate that there is a need for more validation in a branch below us. def traverser(self, data, schema, tree): """ Traverses the dictionary, recursing onto itself if it sees appropriate...
The deepest validation we can make in any given circumstance for a key. Does not recurse, it will just receive both values and the tree, passing them on to the :fun:`enforce` function. def key_leaf(self, data, schema, tree): """ The deepest validation we can make in any given circumstan...
The deepest validation we can make in any given circumstance for a value. Does not recurse, it will just receive both values and the tree, passing them on to the :fun:`enforce` function. def value_leaf(self, data, schema, tree): """ The deepest validation we can make in any given circum...
Used to format `datetime.timedelta` objects. Works just like `strftime` >>> strfdelta(duration, '%H:%M:%S') param tdelta: Time duration which is an instance of datetime.timedelta param fmt: The pattern to format the timedelta with rtype: str def strfdelta(tdelta, fmt): """ Used to format `dat...
Returns the user's information :rtype: (str, int, str) def get_user_information(): """ Returns the user's information :rtype: (str, int, str) """ try: import pwd _username = pwd.getpwuid(os.getuid())[0] _userid = os.getuid() _uname = os.uname()[1] except Im...
Authenticate APP using token credentials: https://docs.microsoft.com/en-us/python/azure/python-sdk-azure-authenticate?view=azure-python :return: ~ServicePrincipalCredentials credentials def _login_azure_app_token(client_id=None, client_secret=None, tenant_id=None): """ Authenticate APP ...
Prepare a docker image that will run in the cloud, mounting the asset and executing the algorithm. :param asset_url :param algorithm_url :param resource_group_name: :param account_name: :param account_key: :param share_name_input: :param share_name_output: ...
Lists the container groups in the specified resource group. Arguments: aci_client {azure.mgmt.containerinstance.ContainerInstanceManagementClient} -- An authenticated container instance management client. resource_group {azure.mgmt.resource.resources.models.Resource...
Return a sequence of namedtuple objects from a fasta file with attributes (id, description, seq) given open file-like object ``handle`` def fastalite(handle): """Return a sequence of namedtuple objects from a fasta file with attributes (id, description, seq) given open file-like object ``handle`` ...
Return a sequence of namedtuple objects from a fastq file with attributes (id, description, seq, qual) given open file-like object ``handle``. This parser assumes that lines corresponding to sequences and quality scores are not wrapped. Raises ``ValueError`` for malformed records. See https://doi.o...
Yield extra tuples containing a field name and a callable that takes a row def cauldron_extras(self): """ Yield extra tuples containing a field name and a callable that takes a row """ for extra in super(Dimension, self).cauldron_extras: yield extra if self....
Make sure we have the right column suffixes. These will be appended to `id` when generating the query. def make_column_suffixes(self): """ Make sure we have the right column suffixes. These will be appended to `id` when generating the query. """ if self.column_suffixes: ...
Create a SQLAlchemy clause from a condition. def parse_condition( cond, selectable, aggregated=False, default_aggregation='sum' ): """Create a SQLAlchemy clause from a condition.""" if cond is None: return None else: if 'and' in cond: conditions = [ parse_co...
Tokenize a string by splitting it by + and - >>> tokenize('this + that') ['this', 'PLUS', 'that'] >>> tokenize('this+that') ['this', 'PLUS', 'that'] >>> tokenize('this+that-other') ['this', 'PLUS', 'that', 'MINUS', 'other'] def tokenize(s): """ Tokenize a string by splitting it by + and ...
Find a column in a column collection by name or _label def _find_in_columncollection(columns, name): """ Find a column in a column collection by name or _label""" for col in columns: if col.name == name or getattr(col, '_label', None) == name: return col return None
Find a column named `name` in selectable :param selectable: :param name: :return: A column object def find_column(selectable, name): """ Find a column named `name` in selectable :param selectable: :param name: :return: A column object """ from recipe import Recipe if isin...
Parse a field object from yaml into a sqlalchemy expression def parse_field(fld, selectable, aggregated=True, default_aggregation='sum'): """ Parse a field object from yaml into a sqlalchemy expression """ # An aggregation is a callable that takes a single field expression # None will perform no aggregatio...
Create an ingredient from an dictionary. This object will be deserialized from yaml def ingredient_from_dict(ingr_dict, selectable): """Create an ingredient from an dictionary. This object will be deserialized from yaml """ # TODO: This is deprecated in favor of # ingredient_from_validated_dict ...
Converts a validated field to sqlalchemy. Field references are looked up in selectable def parse_validated_field(fld, selectable): """ Converts a validated field to sqlalchemy. Field references are looked up in selectable """ aggr_fn = IngredientValidator.aggregation_lookup[fld['aggregation']] fie...
Create an ingredient from an dictionary. This object will be deserialized from yaml def ingredient_from_validated_dict(ingr_dict, selectable): """ Create an ingredient from an dictionary. This object will be deserialized from yaml """ validator = IngredientValidator(schema=ingr_dict['kind']) if ...
Given a SQLAlchemy Table, automatically generate a Shelf with metrics and dimensions based on its schema. def AutomaticShelf(table): """Given a SQLAlchemy Table, automatically generate a Shelf with metrics and dimensions based on its schema. """ if hasattr(table, '__table__'): table = table...
Given a SQLAlchemy Table object, return a Shelf description suitable for passing to Shelf.from_config. def introspect_table(table): """Given a SQLAlchemy Table object, return a Shelf description suitable for passing to Shelf.from_config. """ d = {} for c in table.columns: if isinstance(...
Pop an ingredient off of this shelf. def pop(self, k, d=_POP_DEFAULT): """Pop an ingredient off of this shelf.""" if d is _POP_DEFAULT: return self._ingredients.pop(k) else: return self._ingredients.pop(k, d)
Return the Dimensions on this shelf in the order in which they were used. def dimension_ids(self): """ Return the Dimensions on this shelf in the order in which they were used.""" return self._sorted_ingredients([ d.id for d in self.values() if isinstance(d, Dimension) ...
Return the Metrics on this shelf in the order in which they were used. def metric_ids(self): """ Return the Metrics on this shelf in the order in which they were used. """ return self._sorted_ingredients([ d.id for d in self.values() if isinstance(d, Metric) ])
Return the Metrics on this shelf in the order in which they were used. def filter_ids(self): """ Return the Metrics on this shelf in the order in which they were used. """ return self._sorted_ingredients([ d.id for d in self.values() if isinstance(d, Filter) ])
Create a shelf using a dict shelf definition. :param obj: A Python dictionary describing a Shelf. :param selectable: A SQLAlchemy Table, a Recipe, a table name, or a SQLAlchemy join to select from. :param metadata: If `selectable` is passed as a table name, then in order...
Create a shelf using a yaml shelf definition. :param yaml_str: A string containing yaml ingredient definitions. :param selectable: A SQLAlchemy Table, a Recipe, or a SQLAlchemy join to select from. :return: A shelf that contains the ingredients defined in yaml_str. def from_yaml(cl...
Create a shelf using a yaml shelf definition. :param yaml_str: A string containing yaml ingredient definitions. :param selectable: A SQLAlchemy Table, a Recipe, or a SQLAlchemy join to select from. :return: A shelf that contains the ingredients defined in yaml_str. def from_validated_y...
Find an Ingredient, optionally using the shelf. :param obj: A string or Ingredient :param filter_to_class: The Ingredient subclass that obj must be an instance of :param constructor: An optional callable for building Ingredients from obj :return: An Ingredient of subcl...
Make columns, group_bys, filters, havings def brew_query_parts(self): """ Make columns, group_bys, filters, havings """ columns, group_bys, filters, havings = [], [], set(), set() for ingredient in self.ingredients(): if ingredient.query_columns: columns.exte...
Add any calculated values to each row of a resultset generating a new namedtuple :param list: a list of row results :param cache_context: optional extra context for caching :return: a list with ingredient.cauldron_extras added for all ingredients def enchant(self, list...
Toggles whether automatic filters are applied to a recipe. The following will disable automatic filters for this recipe:: recipe.apply_automatic_filters(False) def apply_automatic_filters(self, value): """Toggles whether automatic filters are applied to a recipe. The following will...
Sets a dictionary of automatic filters to apply to this recipe. If your recipe uses a shelf that has dimensions 'state' and 'gender' you could filter the data to Men in California and New Hampshire with:: shelf = Shelf({ 'state': Dimension(Census.state), 'gen...
Take a recipe that has dimensions Resummarize it over one of the dimensions returning averages of the metrics. def modify_postquery_parts(self, postquery_parts): """ Take a recipe that has dimensions Resummarize it over one of the dimensions returning averages of the met...
Should this recipe be anonymized def anonymize(self, value): """ Should this recipe be anonymized""" assert isinstance(value, bool) if self._anonymize != value: self.dirty = True self._anonymize = value # Builder pattern must return the recipe return se...
Put the anonymizers in the last position of formatters def add_ingredients(self): """ Put the anonymizers in the last position of formatters """ for ingredient in self.recipe._cauldron.values(): if hasattr(ingredient.meta, 'anonymizer'): anonymizer = ingredient.meta.anonymiz...
Blend a recipe into the base recipe. This performs an inner join of the blend_recipe to the base recipe's SQL. def blend(self, blend_recipe, join_base, join_blend): """Blend a recipe into the base recipe. This performs an inner join of the blend_recipe to the base recipe's SQL. ...
Make the comparison recipe a subquery that is left joined to the base recipe using dimensions that are shared between the recipes. Hoist the metric from the comparison recipe up to the base query while adding the suffix. def modify_postquery_parts(self, postquery_parts): """ Ma...
Adds a comparison recipe to a base recipe. def compare(self, compare_recipe, suffix='_compare'): """Adds a comparison recipe to a base recipe.""" assert isinstance(compare_recipe, Recipe) assert isinstance(suffix, basestring) self.compare_recipe.append(compare_recipe) self.suffi...
Make the comparison recipe a subquery that is left joined to the base recipe using dimensions that are shared between the recipes. Hoist the metric from the comparison recipe up to the base query while adding the suffix. def modify_postquery_parts(self, postquery_parts): """Make the co...
List the blobs/files inside a container/share_name. Args: container_or_share_name(str): Name of the container/share_name where we want to list the blobs/files. container(bool): flag to know it you are listing files or blobs. account(str): The name of the storage account. ...
Sign a remote file to distribute. The azure url format is https://myaccount.blob.core.windows.net/mycontainer/myblob. Args: remote_file(str): The blob that we want to sign. def generate_url(self, remote_file): """Sign a remote file to distribute. The azure url format is https://myaccount....
Delete file from the cloud. The azure url format is https://myaccount.blob.core.windows.net/mycontainer/myblob. Args: remote_file(str): The path of the file to be deleted. Raises: :exc:`~..OsmosisError`: if the file is not uploaded correctly. def delete(self, remote_file): ...
Copy file from a path to another path. The azure url format is https://myaccount.blob.core.windows.net/mycontainer/myblob. Args: source_path(str): The path of the file to be copied. dest_path(str): The destination path where the file is going to be allocated. Raises: ...
Generate an SQL expression string with bound parameters rendered inline for the given SQLAlchemy statement. The function can also receive a `sqlalchemy.orm.Query` object instead of statement. WARNING: Should only be used for debugging. Inlining parameters is not safe when handling user created...
Replace a format with a default def _normalize_coerce_to_format_with_lookup(self, v): """ Replace a format with a default """ try: return self.format_lookup.get(v, v) except TypeError: # v is something we can't lookup (like a list) return v
coerces strings to a dict {'value': str} def _normalize_coerce_to_field_dict(self, v): """ coerces strings to a dict {'value': str} """ def tokenize(s): """ Tokenize a string by splitting it by + and - >>> tokenize('this + that') ['this', '+', 'that'] ...
Is not a list or a dict def _validate_type_scalar(self, value): """ Is not a list or a dict """ if isinstance( value, _int_types + (_str_type, float, date, datetime, bool) ): return True
Construct a Recipe from a plain Python dictionary. Most of the directives only support named ingredients, specified as strings, and looked up on the shelf. But filters can be specified as objects. Additionally, each RecipeExtension can extract and handle data from the configura...
Defines a shelf to use for this recipe def shelf(self, shelf=None): """ Defines a shelf to use for this recipe """ if shelf is None: self._shelf = Shelf({}) elif isinstance(shelf, Shelf): self._shelf = shelf elif isinstance(shelf, dict): self._shelf =...
Add a list of Metric ingredients to the query. These can either be Metric objects or strings representing metrics on the shelf. The Metric expression will be added to the query's select statement. The metric value is a property of each row of the result. :param metrics: Metrics to add ...
Add a list of Dimension ingredients to the query. These can either be Dimension objects or strings representing dimensions on the shelf. The Dimension expression will be added to the query's select statement and to the group_by. :param dimensions: Dimensions to add to the recipe. Dimen...
Add a list of Filter ingredients to the query. These can either be Filter objects or strings representing filters on the service's shelf. ``.filters()`` are additive, calling .filters() more than once will add to the list of filters being used by the recipe. The Filter expression will b...
Add a list of ingredients to order by to the query. These can either be Dimension or Metric objects or strings representing order_bys on the shelf. The Order_by expression will be added to the query's order_by statement :param order_bys: Order_bys to add to the recipe. Order_bys can ...
Limit the number of rows returned from the database. :param limit: The number of rows to return in the recipe. 0 will return all rows. :type limit: int def limit(self, limit): """ Limit the number of rows returned from the database. :param limit: The number of ro...
Offset a number of rows before returning rows from the database. :param offset: The number of rows to offset in the recipe. 0 will return from the first available row :type offset: int def offset(self, offset): """ Offset a number of rows before returning rows from the d...
Determine if the running engine is postgres def _is_postgres(self): """ Determine if the running engine is postgres """ if self._is_postgres_engine is None: is_postgres_engine = False try: dialect = self.session.bind.engine.name if 'redshift' in d...
Build a set of order by columns def _prepare_order_bys(self): """ Build a set of order by columns """ order_bys = OrderedSet() if self._order_bys: for ingredient in self._order_bys: if isinstance(ingredient, Dimension): # Reverse the ordering colu...
Generates a query using the ingredients supplied by the recipe. :return: A SQLAlchemy query def query(self): """ Generates a query using the ingredients supplied by the recipe. :return: A SQLAlchemy query """ if len(self._cauldron.ingredients()) == 0: raise...
The recipe is dirty if it is flagged dirty or any extensions are flagged dirty def dirty(self): """ The recipe is dirty if it is flagged dirty or any extensions are flagged dirty """ if self._dirty: return True else: for extension in self.recipe_extension...
If dirty is true set the recipe to dirty flag. If false, clear the recipe and all extension dirty flags def dirty(self, value): """ If dirty is true set the recipe to dirty flag. If false, clear the recipe and all extension dirty flags """ if value: self._dirty = True ...
The recipe's query as a subquery suitable for use in joins or other queries. def subquery(self, name=None): """ The recipe's query as a subquery suitable for use in joins or other queries. """ query = self.query() return query.subquery(name=name)
Return an alias to a table def as_table(self, name=None): """ Return an alias to a table """ if name is None: name = self._id return alias(self.subquery(), name=name)
Return a (potentially cached) list of result objects. def all(self): """ Return a (potentially cached) list of result objects. """ starttime = fetchtime = enchanttime = time.time() fetched_from_cache = False if self.dirty or self.all_dirty: query = self.query() ...
Validates that all of the keys in one of the sets of keys are defined as keys of ``value``. def _validate_condition_keys(self, field, value, error): """ Validates that all of the keys in one of the sets of keys are defined as keys of ``value``. """ if 'field' in value: ...
routes to the survival method, returns survivors def survival(self,parents,offspring,elite=None,elite_index=None,X=None,X_O=None,F=None,F_O=None): """routes to the survival method, returns survivors""" if self.sel == 'tournament': survivors, survivor_index = self.tournament(parents + offspr...
conducts tournament selection of size tourn_size def tournament(self,individuals,tourn_size, num_selections=None): """conducts tournament selection of size tourn_size""" winners = [] locs = [] if num_selections is None: num_selections = len(individuals) for i in np....
conducts lexicase selection for de-aggregated fitness vectors def lexicase(self,F, num_selections=None, survival = False): """conducts lexicase selection for de-aggregated fitness vectors""" if num_selections is None: num_selections = F.shape[0] winners = [] locs = [] ...
conducts epsilon lexicase selection for de-aggregated fitness vectors def epsilon_lexicase(self, F, sizes, num_selections=None, survival = False): """conducts epsilon lexicase selection for de-aggregated fitness vectors""" # pdb.set_trace() if num_selections is None: num_selecti...
median absolute deviation statistic def mad(self,x, axis=None): """median absolute deviation statistic""" return np.median(np.abs(x - np.median(x, axis)), axis)
deterministic crowding implementation (for non-steady state). offspring compete against the parent they are most similar to, here defined as the parent they are most correlated with. the offspring only replace their parent if they are more fit. def deterministic_crowding(self,parents,offspring,...
performs variation operators on parents. def variation(self,parents): """performs variation operators on parents.""" # downselect to features that are important if (self.valid(parents) and self.ml_type != 'SVC' and self.ml_type != 'SVR'): # this is needed because svm has...
subtree-like swap crossover between programs p_i and p_j. def cross(self,p_i,p_j, max_depth = 2): """subtree-like swap crossover between programs p_i and p_j.""" # only choose crossover points for out_types available in both programs # pdb.set_trace() # determine possible outttypes ...