code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def calculate_deltat(year, month): """Calculate the difference between Terrestrial Dynamical Time (TD) and Universal Time (UT). Note: This function is not yet compatible for calculations using Numba. Equations taken from http://eclipse.gsfc.nasa.gov/SEcat5/deltatpoly.html """ plw = 'Delta...
Calculate the difference between Terrestrial Dynamical Time (TD) and Universal Time (UT). Note: This function is not yet compatible for calculations using Numba. Equations taken from http://eclipse.gsfc.nasa.gov/SEcat5/deltatpoly.html
def createSegment(self, cell): """ Create a :class:`~nupic.algorithms.connections.Segment` on the specified cell. This method calls :meth:`~nupic.algorithms.connections.Connections.createSegment` on the underlying :class:`~nupic.algorithms.connections.Connections`, and it does some extra boo...
Create a :class:`~nupic.algorithms.connections.Segment` on the specified cell. This method calls :meth:`~nupic.algorithms.connections.Connections.createSegment` on the underlying :class:`~nupic.algorithms.connections.Connections`, and it does some extra bookkeeping. Unit tests should call this metho...
def add_metadata(self, metadata_matrix, meta_index_store): ''' Returns a new corpus with a the metadata matrix and index store integrated. :param metadata_matrix: scipy.sparse matrix (# docs, # metadata) :param meta_index_store: IndexStore of metadata values :return: TermDocMatr...
Returns a new corpus with a the metadata matrix and index store integrated. :param metadata_matrix: scipy.sparse matrix (# docs, # metadata) :param meta_index_store: IndexStore of metadata values :return: TermDocMatrixWithoutCategories
def standardize_input_data(data): """ Ensure utf-8 encoded strings are passed to the indico API """ if type(data) == bytes: data = data.decode('utf-8') if type(data) == list: data = [ el.decode('utf-8') if type(data) == bytes else el for el in data ] ...
Ensure utf-8 encoded strings are passed to the indico API
def _construct_columns(self, column_map): ''' a helper method for constructing the column objects for a table object ''' from sqlalchemy import Column, String, Boolean, Integer, Float, Binary column_args = [] for key, value in column_map.items(): recor...
a helper method for constructing the column objects for a table object
def dependencies(self) -> List[Dependency]: """Return the PB dependencies.""" dependencies_str = DB.get_hash_value(self.key, 'dependencies') dependencies = [] for dependency in ast.literal_eval(dependencies_str): dependencies.append(Dependency(dependency)) return depe...
Return the PB dependencies.
def node_style(self, node, **kwargs): ''' Modifies a node style to the dot representation. ''' if node not in self.edges: self.edges[node] = {} self.nodes[node] = kwargs
Modifies a node style to the dot representation.
def extend_reservation(request, user_id, days=7): ''' Allows staff to extend the reservation on a given user's cart. ''' user = User.objects.get(id=int(user_id)) cart = CartController.for_user(user) cart.extend_reservation(datetime.timedelta(days=days)) return redirect(request.META["HTTP_REFER...
Allows staff to extend the reservation on a given user's cart.
def field_values(self): """ Access the field_values :returns: twilio.rest.autopilot.v1.assistant.field_type.field_value.FieldValueList :rtype: twilio.rest.autopilot.v1.assistant.field_type.field_value.FieldValueList """ if self._field_values is None: self._fi...
Access the field_values :returns: twilio.rest.autopilot.v1.assistant.field_type.field_value.FieldValueList :rtype: twilio.rest.autopilot.v1.assistant.field_type.field_value.FieldValueList
def _parse_pool_transaction_file( ledger, nodeReg, cliNodeReg, nodeKeys, activeValidators, ledger_size=None): """ helper function for parseLedgerForHaAndKeys """ for _, txn in ledger.getAllTxn(to=ledger_size): if get_type(txn) == NODE: ...
helper function for parseLedgerForHaAndKeys
def cis(x: float) -> complex: r""" Implements Euler's formula :math:`\text{cis}(x) = e^{i \pi x} = \cos(x) + i \sin(x)` """ return np.cos(x) + 1.0j * np.sin(x)
r""" Implements Euler's formula :math:`\text{cis}(x) = e^{i \pi x} = \cos(x) + i \sin(x)`
def create_datastream(self, datastream): """ To create Datastream :param datastream: Datastream :param options: dict """ raw_datastream = self.http.post('/Datastream', datastream) return Schemas.Datastream(datastream=raw_datastream)
To create Datastream :param datastream: Datastream :param options: dict
def run_once(self): """This function runs one iteration of the IRC client. This is called in a loop by the run_loop function. It can be called separately, but most of the time there is no need to do this. """ packet = _parse_irc_packet(next(self.lines)) #Get next line from gener...
This function runs one iteration of the IRC client. This is called in a loop by the run_loop function. It can be called separately, but most of the time there is no need to do this.
def devserver_cmd(argv=sys.argv[1:]): # pragma: no cover """\ Serve the web API for development. Usage: pld-devserver [options] Options: -h --help Show this screen. --host=<host> The host to use [default: 0.0.0.0]. --port=<port> The port to use [default: 5000]. --de...
\ Serve the web API for development. Usage: pld-devserver [options] Options: -h --help Show this screen. --host=<host> The host to use [default: 0.0.0.0]. --port=<port> The port to use [default: 5000]. --debug=<debug> Whether or not to use debug mode [default: 0]...
def delete(self, path, data=None): """Executes a DELETE. 'path' may not be None. Should include the full path to the resoure. 'data' may be None or a dictionary. Returns a named tuple that includes: status: the HTTP status code json: the returned JSON-HAL ...
Executes a DELETE. 'path' may not be None. Should include the full path to the resoure. 'data' may be None or a dictionary. Returns a named tuple that includes: status: the HTTP status code json: the returned JSON-HAL If the key was not set, throws an APIConfi...
def lcm(*numbers): """ Return lowest common multiple of a sequence of numbers. Args: \*numbers: Sequence of numbers. Returns: (int) Lowest common multiple of numbers. """ n = 1 for i in numbers: n = (i * n) // gcd(i, n) return n
Return lowest common multiple of a sequence of numbers. Args: \*numbers: Sequence of numbers. Returns: (int) Lowest common multiple of numbers.
def listBlockSummaries(self, block_name="", dataset="", detail=False): """ API that returns summary information like total size and total number of events in a dataset or a list of blocks :param block_name: list block summaries for block_name(s) :type block_name: str, list :para...
API that returns summary information like total size and total number of events in a dataset or a list of blocks :param block_name: list block summaries for block_name(s) :type block_name: str, list :param dataset: list block summaries for all blocks in dataset :type dataset: str ...
def emit(self): """Get a mapping from a transcript :return: One random Transcript sequence :rtype: sequence """ i = self.options.rand.get_weighted_random_index(self._weights) return self._transcriptome.transcripts[i]
Get a mapping from a transcript :return: One random Transcript sequence :rtype: sequence
def merge_entity(self, entity, if_match='*'): ''' Adds a merge entity operation to the batch. See :func:`~azure.storage.table.tableservice.TableService.merge_entity` for more information on merges. The operation will not be executed until the batch is committed. ...
Adds a merge entity operation to the batch. See :func:`~azure.storage.table.tableservice.TableService.merge_entity` for more information on merges. The operation will not be executed until the batch is committed. :param entity: The entity to merge. Could be a dict...
def save_df_output( df_output: pd.DataFrame, freq_s: int = 3600, site: str = '', path_dir_save: Path = Path('.'),)->list: '''save supy output dataframe to txt files Parameters ---------- df_output : pd.DataFrame output dataframe of supy simulation freq_s : in...
save supy output dataframe to txt files Parameters ---------- df_output : pd.DataFrame output dataframe of supy simulation freq_s : int, optional output frequency in second (the default is 3600, which indicates the a txt with hourly values) path_dir_save : Path, optional dir...
def setup(self, in_name=None, out_name=None, required=None, hidden=None, multiple=None, defaults=None): """ Set the options of the block. Only the not None given options are set .. note:: a block may have multiple inputs but have only one output :param in_name: name(s) ...
Set the options of the block. Only the not None given options are set .. note:: a block may have multiple inputs but have only one output :param in_name: name(s) of the block input data :type in_name: str or list of str :param out_name: name of the block output data :ty...
def _protected_division(x1, x2): """Closure of division (x1/x2) for zero denominator.""" with np.errstate(divide='ignore', invalid='ignore'): return np.where(np.abs(x2) > 0.001, np.divide(x1, x2), 1.)
Closure of division (x1/x2) for zero denominator.
def init_logger(self): """Init logger.""" if not self.result_logger: if not os.path.exists(self.local_dir): os.makedirs(self.local_dir) if not self.logdir: self.logdir = tempfile.mkdtemp( prefix="{}_{}".format( ...
Init logger.
def ionic_strength(mis, zis): r'''Calculate the ionic strength of a solution in one of two ways, depending on the inputs only. For Pitzer and Bromley models, `mis` should be molalities of each component. For eNRTL models, `mis` should be mole fractions of each electrolyte in the solution. This will ...
r'''Calculate the ionic strength of a solution in one of two ways, depending on the inputs only. For Pitzer and Bromley models, `mis` should be molalities of each component. For eNRTL models, `mis` should be mole fractions of each electrolyte in the solution. This will sum to be much less than 1. ....
def __compute_evolution( df, id_cols, value_col, date_col=None, freq=1, compare_to=None, method='abs', format='column', offseted_suffix='_offseted', evolution_col_name='evolution_computed', how='left', fillna=None, raise_duplicate_error=True ): """ Compute an ...
Compute an evolution column : - against a period distant from a fixed frequency. - against a part of the df Unfortunately, pandas doesn't allow .change() and .pct_change() to be executed with a MultiIndex. Args: df (pd.DataFrame): id_cols (list(str)): value_col (str...
def license_present(name): ''' Ensures that the specified PowerPath license key is present on the host. name The license key to ensure is present ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if not __salt__['powerpath.has_...
Ensures that the specified PowerPath license key is present on the host. name The license key to ensure is present
def output(self, output, accepts, set_http_code, set_content_type): """ Formats a response from a WSGI app to handle any RDF graphs If a view function returns a single RDF graph, serialize it based on Accept header If it's not an RDF graph, return it without any special handling """ graph = Decorator...
Formats a response from a WSGI app to handle any RDF graphs If a view function returns a single RDF graph, serialize it based on Accept header If it's not an RDF graph, return it without any special handling
def centroid_2dg(data, error=None, mask=None): """ Calculate the centroid of a 2D array by fitting a 2D Gaussian (plus a constant) to the array. Invalid values (e.g. NaNs or infs) in the ``data`` or ``error`` arrays are automatically masked. The mask for invalid values represents the combinati...
Calculate the centroid of a 2D array by fitting a 2D Gaussian (plus a constant) to the array. Invalid values (e.g. NaNs or infs) in the ``data`` or ``error`` arrays are automatically masked. The mask for invalid values represents the combination of the invalid-value masks for the ``data`` and ``er...
def statement(self): """ A terminated relational algebra statement. """ return (self.assignment ^ self.expression) + Suppress( self.syntax.terminator)
A terminated relational algebra statement.
def parse_option(self, option, block_name, *values): """ Parse domain values for option. """ _extra_subs = ('www', 'm', 'mobile') if len(values) == 0: # expect some values here.. raise ValueError for value in values: value = value.lower() ...
Parse domain values for option.
def state(self, new_state): """Set the state.""" with self.lock: self._state.exit() self._state = new_state self._state.enter()
Set the state.
def list_all_customer_groups(cls, **kwargs): """List CustomerGroups Return a list of CustomerGroups This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.list_all_customer_groups(async=True) ...
List CustomerGroups Return a list of CustomerGroups This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.list_all_customer_groups(async=True) >>> result = thread.get() :param async bool ...
def AddShadow(self, fileset): """Add the shadow entries to the shadow store.""" shadow = fileset.get("/etc/shadow") if shadow: self._ParseFile(shadow, self.ParseShadowEntry) else: logging.debug("No /etc/shadow file.")
Add the shadow entries to the shadow store.
def get_content_slug_by_slug(self, slug): """Returns the latest :class:`Content <pages.models.Content>` slug object that match the given slug for the current site domain. :param slug: the wanted slug. """ content = self.filter(type='slug', body=slug) if settings.PAGE_USE...
Returns the latest :class:`Content <pages.models.Content>` slug object that match the given slug for the current site domain. :param slug: the wanted slug.
def build(self): """ Builds and returns all combinations of parameters specified by the param grid. """ keys = self._param_grid.keys() grid_values = self._param_grid.values() def to_key_value_pairs(keys, values): return [(key, key.typeConverter(value)...
Builds and returns all combinations of parameters specified by the param grid.
def luminosity_integral(self, x, axis_ratio): """Routine to integrate the luminosity of an elliptical light profile. The axis ratio is set to 1.0 for computing the luminosity within a circle""" r = x * axis_ratio return 2 * np.pi * r * self.intensities_from_grid_radii(x)
Routine to integrate the luminosity of an elliptical light profile. The axis ratio is set to 1.0 for computing the luminosity within a circle
def insertions_from_masked(seq): """ get coordinates of insertions from insertion-masked sequence """ insertions = [] prev = True for i, base in enumerate(seq): if base.isupper() and prev is True: insertions.append([]) prev = False elif base.islower(): ...
get coordinates of insertions from insertion-masked sequence
def writeCleanup(self, varBind, **context): """Finalize Managed Object Instance modification. Implements the successful third step of the multi-step workflow of the SNMP SET command processing (:RFC:`1905#section-4.2.5`). The goal of the third (successful) phase is to seal the new stat...
Finalize Managed Object Instance modification. Implements the successful third step of the multi-step workflow of the SNMP SET command processing (:RFC:`1905#section-4.2.5`). The goal of the third (successful) phase is to seal the new state of the requested Managed Object Instance. Onc...
def should_stop(self, result): """Whether the given result meets this trial's stopping criteria.""" if result.get(DONE): return True for criteria, stop_value in self.stopping_criterion.items(): if criteria not in result: raise TuneError( ...
Whether the given result meets this trial's stopping criteria.
def set_genre(self, genre): """Sets song's genre :param genre: genre """ self._set_attr(TCON(encoding=3, text=str(genre)))
Sets song's genre :param genre: genre
def drop_if(df, fun): """Drops columns where fun(ction) is true Args: fun: a function that will be applied to columns """ def _filter_f(col): try: return fun(df[col]) except: return False cols = list(filter(_filter_f, df.columns)) return df.drop(...
Drops columns where fun(ction) is true Args: fun: a function that will be applied to columns
def resolve_orm_path(model, orm_path): """ Follows the queryset-style query path of ``orm_path`` starting from ``model`` class. If the path ends up referring to a bad field name, ``django.db.models.fields.FieldDoesNotExist`` will be raised. """ bits = orm_path.split('__') endpoint_model =...
Follows the queryset-style query path of ``orm_path`` starting from ``model`` class. If the path ends up referring to a bad field name, ``django.db.models.fields.FieldDoesNotExist`` will be raised.
def major_flux(self, fraction=0.9): r"""Returns the main pathway part of the net flux comprising at most the requested fraction of the full flux. """ (paths, pathfluxes) = self.pathways(fraction=fraction) return self._pathways_to_flux(paths, pathfluxes, n=self.nstates)
r"""Returns the main pathway part of the net flux comprising at most the requested fraction of the full flux.
def pprint(self, index=False, delimiter='-'): """Pretty-print the binary tree. :param index: If set to True (default: False), display level-order_ indexes using the format: ``{index}{delimiter}{value}``. :type index: bool :param delimiter: Delimiter character between the nod...
Pretty-print the binary tree. :param index: If set to True (default: False), display level-order_ indexes using the format: ``{index}{delimiter}{value}``. :type index: bool :param delimiter: Delimiter character between the node index and the node value (default: '-'). ...
def get(self, id, seq, line): # pylint: disable=invalid-name,redefined-builtin """Get a highlight. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param line: Line number in TestResult's logfile as an int. :return: :class:`highlights.Highlight <hig...
Get a highlight. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param line: Line number in TestResult's logfile as an int. :return: :class:`highlights.Highlight <highlights.Highlight>` object
def deleteMember(self, address, id, headers=None, query_params=None, content_type="application/json"): """ Delete member from network It is method for DELETE /network/{id}/member/{address} """ uri = self.client.base_url + "/network/"+id+"/member/"+address return self.clie...
Delete member from network It is method for DELETE /network/{id}/member/{address}
def request(key, features, query, timeout=5): """Make an API request :param string key: API key to use :param list features: features to request. It must be a subset of :data:`FEATURES` :param string query: query to send :param integer timeout: timeout of the request :returns: result of the API...
Make an API request :param string key: API key to use :param list features: features to request. It must be a subset of :data:`FEATURES` :param string query: query to send :param integer timeout: timeout of the request :returns: result of the API request :rtype: dict
def _ztanh(Np: int, gridmin: float, gridmax: float) -> np.ndarray: """ typically call via setupz instead """ x0 = np.linspace(0, 3.14, Np) # arbitrarily picking 3.14 as where tanh gets to 99% of asymptote return np.tanh(x0)*gridmax+gridmin
typically call via setupz instead
def predecesors_pattern(element, root): """ Look for `element` by its predecesors. Args: element (obj): HTMLElement instance of the object you are looking for. root (obj): Root of the `DOM`. Returns: list: ``[PathCall()]`` - list with one :class:`PathCall` object (to \ ...
Look for `element` by its predecesors. Args: element (obj): HTMLElement instance of the object you are looking for. root (obj): Root of the `DOM`. Returns: list: ``[PathCall()]`` - list with one :class:`PathCall` object (to \ allow use with ``.extend(predecesors_pattern()...
def _append_to_scalar_dict(self, tag, scalar_value, global_step, timestamp): """Adds a list [timestamp, step, value] to the value of `self._scalar_dict[tag]`. This allows users to store scalars in memory and dump them to a json file later.""" if tag not in self._scalar_dict.keys(): s...
Adds a list [timestamp, step, value] to the value of `self._scalar_dict[tag]`. This allows users to store scalars in memory and dump them to a json file later.
def on_mouse_wheel(self, event): '''handle mouse wheel zoom changes''' state = self.state if not state.can_zoom: return mousepos = self.image_coordinates(event.GetPosition()) rotation = event.GetWheelRotation() / event.GetWheelDelta() oldzoom = self.zoom ...
handle mouse wheel zoom changes
def _bfs(root_node, process_node): """ Implementation of Breadth-first search (BFS) on caffe network DAG :param root_node: root node of caffe network DAG :param process_node: function to run on each node """ from collections import deque seen_nodes = set() next_nodes = deque() see...
Implementation of Breadth-first search (BFS) on caffe network DAG :param root_node: root node of caffe network DAG :param process_node: function to run on each node
def Copier(source, destination): """Factory method to select the right copier for a given source and destination. """ if source.type == 'local' and destination.type == 'local': return LocalCopier(source, destination) elif source.type == 'local' and destination.type == 'google_storage': ...
Factory method to select the right copier for a given source and destination.
def handle(self): """Handles start request.""" # Mapper spec as form arguments. mapreduce_name = self._get_required_param("name") mapper_input_reader_spec = self._get_required_param("mapper_input_reader") mapper_handler_spec = self._get_required_param("mapper_handler") mapper_output_writer_spec ...
Handles start request.
def download_photo_async(photo): """Download a photo to the the path(global varialbe `directory`) :param photo: The photo information include id and title :type photo: dict """ photo_id = photo['id'] photo_title = photo['title'] download_url = get_photo_url(photo_id) photo_format = down...
Download a photo to the the path(global varialbe `directory`) :param photo: The photo information include id and title :type photo: dict
def project_data(self): ''' Assign the sum of ``.integral``\* to each sensible point in the ``pyny.Space`` for the intervals that the points are visible to the Sun. The generated information is stored in: * **.proj_vor** (*ndarray*): ``.integral`` projected t...
Assign the sum of ``.integral``\* to each sensible point in the ``pyny.Space`` for the intervals that the points are visible to the Sun. The generated information is stored in: * **.proj_vor** (*ndarray*): ``.integral`` projected to the Voronoi diagram. ...
def ignore_path(path, ignore_list=None, whitelist=None): """ Returns a boolean indicating if a path should be ignored given an ignore_list and a whitelist of glob patterns. """ if ignore_list is None: return True should_ignore = matches_glob_list(path, ignore_list) if whitelist is N...
Returns a boolean indicating if a path should be ignored given an ignore_list and a whitelist of glob patterns.
def register(self, reg_data, retry=True, interval=1, timeout=3): """ register function retry True, infinity retries False, no retries Number, retries times interval time period for retry return False if no success ...
register function retry True, infinity retries False, no retries Number, retries times interval time period for retry return False if no success Tunnel if success
def _split_python(python): """Split Python source into chunks. Chunks are separated by at least two return lines. The break must not be followed by a space. Also, long Python strings spanning several lines are not splitted. """ python = _preprocess(python) if not python: return [] ...
Split Python source into chunks. Chunks are separated by at least two return lines. The break must not be followed by a space. Also, long Python strings spanning several lines are not splitted.
def info(gandi, resource, id, value): """Display information about an SSH key. Resource can be a name or an ID """ output_keys = ['name', 'fingerprint'] if id: output_keys.append('id') if value: output_keys.append('value') ret = [] for item in resource: sshkey ...
Display information about an SSH key. Resource can be a name or an ID
def run(self, messages): """Determine if a student is elgible to recieve a hint. Based on their state, poses reflection questions. After more attempts, ask if students would like hints. If so, query the server. """ if self.args.local: return # Only r...
Determine if a student is elgible to recieve a hint. Based on their state, poses reflection questions. After more attempts, ask if students would like hints. If so, query the server.
def rows_max(self, size=None, focus=False): """Return the number of rows for `size` If `size` is not given, the currently rendered number of rows is returned. """ if size is not None: ow = self._original_widget ow_size = self._get_original_widget_size(size) ...
Return the number of rows for `size` If `size` is not given, the currently rendered number of rows is returned.
def legal_status(CASRN, Method=None, AvailableMethods=False, CASi=None): r'''Looks up the legal status of a chemical according to either a specifc method or with all methods. Returns either the status as a string for a specified method, or the status of the chemical in all available data sources, in th...
r'''Looks up the legal status of a chemical according to either a specifc method or with all methods. Returns either the status as a string for a specified method, or the status of the chemical in all available data sources, in the format {source: status}. Parameters ---------- CASRN : str...
def share_matrix(locifile, tree=None, nameorder=None): """ returns a matrix of shared RAD-seq data Parameters: ----------- locifile (str): Path to a ipyrad .loci file. tree (str): Path to Newick file or a Newick string representation of a tree. If used, names will...
returns a matrix of shared RAD-seq data Parameters: ----------- locifile (str): Path to a ipyrad .loci file. tree (str): Path to Newick file or a Newick string representation of a tree. If used, names will be ordered by the ladderized tip order. nameorder (lis...
async def add_unknown_id(self, unknown_id, timeout=OTGW_DEFAULT_TIMEOUT): """ Inform the gateway that the boiler doesn't support the specified Data-ID, even if the boiler doesn't indicate that by returning an Unknown-DataId response. Using this command allows the gateway to send ...
Inform the gateway that the boiler doesn't support the specified Data-ID, even if the boiler doesn't indicate that by returning an Unknown-DataId response. Using this command allows the gateway to send an alternative Data-ID to the boiler instead. Return the added ID, or None on ...
def get_repos(self, visibility=github.GithubObject.NotSet, affiliation=github.GithubObject.NotSet, type=github.GithubObject.NotSet, sort=github.GithubObject.NotSet, direction=github.GithubObject.NotSet): """ :calls: `GET /user/repos <http://developer.github.com/v3/repos>` :param visibility: stri...
:calls: `GET /user/repos <http://developer.github.com/v3/repos>` :param visibility: string :param affiliation: string :param type: string :param sort: string :param direction: string :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Repository.Reposito...
def create(self, _attributes=None, **attributes): """ Create a new instance of the related model. :param attributes: The attributes :type attributes: dict :rtype: Model """ if _attributes is not None: attributes.update(_attributes) instance ...
Create a new instance of the related model. :param attributes: The attributes :type attributes: dict :rtype: Model
def find_usage(self): """ Determine the current usage for each limit of this service, and update corresponding Limit via :py:meth:`~.AwsLimit._add_current_usage`. """ logger.debug("Checking usage for service %s", self.service_name) self.connect() for lim i...
Determine the current usage for each limit of this service, and update corresponding Limit via :py:meth:`~.AwsLimit._add_current_usage`.
def post_loader(*decorator_args, serializer): """ Decorator to automatically instantiate a model from json request data :param serializer: The ModelSerializer to use to load data from the request """ def wrapped(fn): @wraps(fn) def decorated(*args, **kwargs): return fn(*...
Decorator to automatically instantiate a model from json request data :param serializer: The ModelSerializer to use to load data from the request
def undeploy_lambda_alb(self, lambda_name): """ The `zappa undeploy` functionality for ALB infrastructure. """ print("Undeploying ALB infrastructure...") # Locate and delete alb/lambda permissions try: # https://boto3.amazonaws.com/v1/documentation/api/latest...
The `zappa undeploy` functionality for ALB infrastructure.
def purge(self, session, checksum): ''' Deletes calc entry by checksum entirely from the database NB source files on disk are not deleted NB: this is the PUBLIC method @returns error ''' C = session.query(model.Calculation).get(checksum) if not C: ...
Deletes calc entry by checksum entirely from the database NB source files on disk are not deleted NB: this is the PUBLIC method @returns error
def __convert_key(expression): """Converts keys in YAML that reference other keys. """ if type(expression) is str and len(expression) > 2 and expression[1] == '!': expression = eval(expression[2:-1]) return expression
Converts keys in YAML that reference other keys.
def request(self, request): """ Perform an HTTP request through the context Args: request: A v20.request.Request object Returns: A v20.response.Response object """ url = "{}{}".format(self._base_url, request.path) timeout = self.poll_ti...
Perform an HTTP request through the context Args: request: A v20.request.Request object Returns: A v20.response.Response object
def qorts_general_stats (self): """ Add columns to the General Statistics table """ headers = OrderedDict() headers['Genes_PercentWithNonzeroCounts'] = { 'title': '% Genes with Counts', 'description': 'Percent of Genes with Non-Zero Counts', 'max': 100, ...
Add columns to the General Statistics table
def sql(self): """If you access this attribute, we will build an SQLite database out of the FASTA file and you will be able access everything in an indexed fashion, and use the blaze library via sql.frame""" from fasta.indexed import DatabaseFASTA, fasta_to_sql db = DatabaseFASTA...
If you access this attribute, we will build an SQLite database out of the FASTA file and you will be able access everything in an indexed fashion, and use the blaze library via sql.frame
def GET_AUTH(self, courseid, aggregationid=''): # pylint: disable=arguments-differ """ Edit a aggregation """ course, __ = self.get_course_and_check_rights(courseid, allow_all_staff=True) if course.is_lti(): raise web.notfound() return self.display_page(course, aggregation...
Edit a aggregation
def create_from_str(name_and_zone: str): """ Factory method for creating a user from a string in the form `name#zone`. :param name_and_zone: the user's name followed by hash followed by the user's zone :return: the created user """ if _NAME_ZONE_SEGREGATOR not in name_and...
Factory method for creating a user from a string in the form `name#zone`. :param name_and_zone: the user's name followed by hash followed by the user's zone :return: the created user
def _versioned_lib_name(env, libnode, version, prefix, suffix, prefix_generator, suffix_generator, **kw): """For libnode='/optional/dir/libfoo.so.X.Y.Z' it returns 'libfoo.so'""" Verbose = False if Verbose: print("_versioned_lib_name: libnode={:r}".format(libnode.get_path())) print("_versio...
For libnode='/optional/dir/libfoo.so.X.Y.Z' it returns 'libfoo.so
def split_by_files(self, valid_names:'ItemList')->'ItemLists': "Split the data by using the names in `valid_names` for validation." if isinstance(self.items[0], Path): return self.split_by_valid_func(lambda o: o.name in valid_names) else: return self.split_by_valid_func(lambda o: os.path.basenam...
Split the data by using the names in `valid_names` for validation.
def scheme_specification(cls): """ :meth:`.WSchemeHandler.scheme_specification` method implementation """ return WSchemeSpecification( 'file', WURIComponentVerifier(WURI.Component.path, WURIComponentVerifier.Requirement.optional) )
:meth:`.WSchemeHandler.scheme_specification` method implementation
def run_script(self, filename, start_opts=None, globals_=None, locals_=None): """ Run debugger on Python script `filename'. The script may inspect sys.argv for command arguments. `globals_' and `locals_' are the dictionaries to use for local and global variables. If `g...
Run debugger on Python script `filename'. The script may inspect sys.argv for command arguments. `globals_' and `locals_' are the dictionaries to use for local and global variables. If `globals' is not given, globals() (the current global variables) is used. If `locals_' is not given, it...
def merge_requests_data_to(to, food={}): """Merge a small analyzed result to a big one, this function will modify the original ``to``""" if not to: to.update(food) to['requests_counter']['normal'] += food['requests_counter']['normal'] to['requests_counter']['slow'] += food['requests_counte...
Merge a small analyzed result to a big one, this function will modify the original ``to``
def from_raw(self, raw: RawScalar) -> Optional[bytes]: """Override superclass method.""" try: return base64.b64decode(raw, validate=True) except TypeError: return None
Override superclass method.
def get_out_ip_addr(cls, tenant_id): """Retrieves the 'out' service subnet attributes. """ if tenant_id not in cls.serv_obj_dict: LOG.error("Fabric not prepared for tenant %s", tenant_id) return tenant_obj = cls.serv_obj_dict.get(tenant_id) return tenant_obj.get_o...
Retrieves the 'out' service subnet attributes.
def __add_text(self, text): """Adds the given Unicode text as a locally defined symbol.""" if text is not None and not isinstance(text, six.text_type): raise TypeError('Local symbol definition must be a Unicode sequence or None: %r' % text) sid = self.__new_sid() location = N...
Adds the given Unicode text as a locally defined symbol.
def Dadgostar_Shaw_integral_over_T(T, similarity_variable): r'''Calculate the integral of liquid constant-pressure heat capacitiy with the similarity variable concept and method as shown in [1]_. Parameters ---------- T : float Temperature of gas [K] similarity_variable : float ...
r'''Calculate the integral of liquid constant-pressure heat capacitiy with the similarity variable concept and method as shown in [1]_. Parameters ---------- T : float Temperature of gas [K] similarity_variable : float similarity variable as defined in [1]_, [mol/g] Returns ...
def find_files(path, patterns): """ Returns all files from a given path that matches the pattern or list of patterns @type path: str @param path: A path to traverse @typ patterns: str|list @param patterns: A pattern or a list of patterns to match @rtype: list[str]: @return: A list...
Returns all files from a given path that matches the pattern or list of patterns @type path: str @param path: A path to traverse @typ patterns: str|list @param patterns: A pattern or a list of patterns to match @rtype: list[str]: @return: A list of matched files
def _execute_pillar(pillar_name, run_type): ''' Run one or more nagios plugins from pillar data and get the result of run_type The pillar have to be in this format: ------ webserver: Ping_google: - check_icmp: 8.8.8.8 - check_icmp: google.com Load: ...
Run one or more nagios plugins from pillar data and get the result of run_type The pillar have to be in this format: ------ webserver: Ping_google: - check_icmp: 8.8.8.8 - check_icmp: google.com Load: - check_load: -w 0.8 -c 1 APT: - ch...
def capability_info(self, name=None): """Return information about the requested capability from this list. Will return None if there is no information about the requested capability. """ for r in self.resources: if (r.capability == name): return(r) re...
Return information about the requested capability from this list. Will return None if there is no information about the requested capability.
def msg_name(code): """Convert integer message code into a string name.""" ids = {v: k for k, v in COMMANDS.items()} return ids[code]
Convert integer message code into a string name.
def normalize_parameters(params): """**Parameters Normalization** Per `section 3.4.1.3.2`_ of the spec. For example, the list of parameters from the previous section would be normalized as follows: Encoded:: +------------------------+------------------+ | Name | Va...
**Parameters Normalization** Per `section 3.4.1.3.2`_ of the spec. For example, the list of parameters from the previous section would be normalized as follows: Encoded:: +------------------------+------------------+ | Name | Value | +------------------------+...
def manifest_repr(self, p_num): """ Builds a manifest string representation of the parameters and returns it :param p_num: int :return: string """ # Build the parameter prefix prefix = "p" + str(p_num) + "_" # Generate the manifest string manifest...
Builds a manifest string representation of the parameters and returns it :param p_num: int :return: string
def clear_dir(path): """Empty out the image directory.""" for f in os.listdir(path): f_path = os.path.join(path, f) if os.path.isfile(f_path) or os.path.islink(f_path): os.unlink(f_path)
Empty out the image directory.
def autogen_explicit_injectable_metaclass(classname, regen_command=None, conditional_imports=None): r""" Args: classname (?): Returns: ?: CommandLine: python -m utool.util_class --exec-autogen_explicit_injectable_metaclass Example:...
r""" Args: classname (?): Returns: ?: CommandLine: python -m utool.util_class --exec-autogen_explicit_injectable_metaclass Example: >>> # DISABLE_DOCTEST >>> from utool.util_class import * # NOQA >>> from utool.util_class import __CLASSTYPE_ATTRIBUTES...
def _sanitize_inputs(self): """Sanitizes input fields and returns a map <GlobalStreamId -> Grouping>""" ret = {} if self.inputs is None: return if isinstance(self.inputs, dict): # inputs are dictionary, must be either <HeronComponentSpec -> Grouping> or # <GlobalStreamId -> Grouping> ...
Sanitizes input fields and returns a map <GlobalStreamId -> Grouping>
def machine_to_machine(self): """ Access the machine_to_machine :returns: twilio.rest.api.v2010.account.available_phone_number.machine_to_machine.MachineToMachineList :rtype: twilio.rest.api.v2010.account.available_phone_number.machine_to_machine.MachineToMachineList """ ...
Access the machine_to_machine :returns: twilio.rest.api.v2010.account.available_phone_number.machine_to_machine.MachineToMachineList :rtype: twilio.rest.api.v2010.account.available_phone_number.machine_to_machine.MachineToMachineList
def relaxation_matvec(P, p0, obs, times=[1]): r"""Relaxation experiment. The relaxation experiment describes the time-evolution of an expectation value starting in a non-equilibrium situation. Parameters ---------- P : (M, M) ndarray Transition matrix p0 : (M,) ndarray (optiona...
r"""Relaxation experiment. The relaxation experiment describes the time-evolution of an expectation value starting in a non-equilibrium situation. Parameters ---------- P : (M, M) ndarray Transition matrix p0 : (M,) ndarray (optional) Initial distribution for a relaxation e...
def expand(obj, relation, seen): """ Return the to_json or id of a sqlalchemy relationship. """ if hasattr(relation, 'all'): relation = relation.all() if hasattr(relation, '__iter__'): return [expand(obj, item, seen) for item in relation] if type(relation) not in seen: return ...
Return the to_json or id of a sqlalchemy relationship.
def triggers_update_many(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/triggers#update-many-triggers" api_path = "/api/v2/triggers/update_many.json" return self.call(api_path, method="PUT", data=data, **kwargs)
https://developer.zendesk.com/rest_api/docs/core/triggers#update-many-triggers
def dotter(self): """Prints formatted time to stdout at the start of a line, as well as a "." whenever the length of the line is equal or lesser than 80 "." long""" if self.globalcount <= 80: sys.stdout.write('.') self.globalcount += 1 else: sys.stdout...
Prints formatted time to stdout at the start of a line, as well as a "." whenever the length of the line is equal or lesser than 80 "." long