code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def heat_wave_frequency(tasmin, tasmax, thresh_tasmin='22.0 degC', thresh_tasmax='30 degC', window=3, freq='YS'): # Dev note : we should decide if it is deg K or C r"""Heat wave frequency Number of heat waves over a given period. A heat wave is defined as an event where the mini...
r"""Heat wave frequency Number of heat waves over a given period. A heat wave is defined as an event where the minimum and maximum daily temperature both exceeds specific thresholds over a minimum number of days. Parameters ---------- tasmin : xarrray.DataArray Minimum daily temperature...
def _adjust_penalty(self, observ, old_policy_params, length): """Adjust the KL policy between the behavioral and current policy. Compute how much the policy actually changed during the multiple update steps. Adjust the penalty strength for the next training phase if we overshot or undershot the target ...
Adjust the KL policy between the behavioral and current policy. Compute how much the policy actually changed during the multiple update steps. Adjust the penalty strength for the next training phase if we overshot or undershot the target divergence too much. Args: observ: Sequences of observatio...
def post(self, url, data, headers={}): """ POST request for creating new objects. data should be a dictionary. """ response = self._run_method('POST', url, data=data, headers=headers) return self._handle_response(url, response)
POST request for creating new objects. data should be a dictionary.
def confusion_matrix(model, X, y, ax=None, classes=None, sample_weight=None, percent=False, label_encoder=None, cmap='YlOrRd', fontsize=None, random_state=None, **kwargs): """Quick method: Creates a heatmap visualization of the sklearn.metrics.confusion_matrix(). A...
Quick method: Creates a heatmap visualization of the sklearn.metrics.confusion_matrix(). A confusion matrix shows each combination of the true and predicted classes for a test data set. The default color map uses a yellow/orange/red color scale. The user can choose between displaying values as the...
def closed(self, code, reason=None): """Handler called when the WebSocket is closed. Status code 1000 denotes a normal close; all others are errors.""" if code != 1000: self._error = errors.SignalFlowException(code, reason) _logger.info('Lost WebSocket connection with %s ...
Handler called when the WebSocket is closed. Status code 1000 denotes a normal close; all others are errors.
def getecho (self): """This returns the terminal echo mode. This returns True if echo is on or False if echo is off. Child applications that are expecting you to enter a password often set ECHO False. See waitnoecho(). """ attr = termios.tcgetattr(self.child_fd) if attr[3] & te...
This returns the terminal echo mode. This returns True if echo is on or False if echo is off. Child applications that are expecting you to enter a password often set ECHO False. See waitnoecho().
def is_dataset(ds): """Whether ds is a Dataset. Compatible across TF versions.""" import tensorflow as tf from tensorflow_datasets.core.utils import py_utils dataset_types = [tf.data.Dataset] v1_ds = py_utils.rgetattr(tf, "compat.v1.data.Dataset", None) v2_ds = py_utils.rgetattr(tf, "compat.v2.data.Dataset"...
Whether ds is a Dataset. Compatible across TF versions.
def append_row(table, label, data): """Append new row to table widget. :param table: The table that shall have the row added to it. :type table: QTableWidget :param label: Label for the row. :type label: str :param data: custom data associated with label value. :type data: str """ ...
Append new row to table widget. :param table: The table that shall have the row added to it. :type table: QTableWidget :param label: Label for the row. :type label: str :param data: custom data associated with label value. :type data: str
def get_object(self, pid, type=None): '''Initialize and return a new :class:`~eulfedora.models.DigitalObject` instance from the same repository, passing along the connection credentials in use by the current object. If type is not specified, the current DigitalObject class will ...
Initialize and return a new :class:`~eulfedora.models.DigitalObject` instance from the same repository, passing along the connection credentials in use by the current object. If type is not specified, the current DigitalObject class will be used. :param pid: pid of the object t...
def lande_g_factors(element, isotope, L=None, J=None, F=None): r"""Return the Lande g-factors for a given atom or level. >>> element = "Rb" >>> isotope = 87 >>> print(lande_g_factors(element, isotope)) [ 9.9999e-01 2.0023e+00 -9.9514e-04] The spin-orbit g-factor for a certain J >...
r"""Return the Lande g-factors for a given atom or level. >>> element = "Rb" >>> isotope = 87 >>> print(lande_g_factors(element, isotope)) [ 9.9999e-01 2.0023e+00 -9.9514e-04] The spin-orbit g-factor for a certain J >>> print(lande_g_factors(element, isotope, L=0, J=1/Integer(2))) ...
def rpc_request(method_name: str, *args, **kwargs) -> rpcq.messages.RPCRequest: """ Create RPC request :param method_name: Method name :param args: Positional arguments :param kwargs: Keyword arguments :return: JSON RPC formatted dict """ if args: kwargs['*args'] = args ret...
Create RPC request :param method_name: Method name :param args: Positional arguments :param kwargs: Keyword arguments :return: JSON RPC formatted dict
def get_locs(self, seq): """ Get location for a given label/slice/list/mask or a sequence of such as an array of integers. Parameters ---------- seq : label/slice/list/mask or a sequence of such You should use one of the above for each level. If a l...
Get location for a given label/slice/list/mask or a sequence of such as an array of integers. Parameters ---------- seq : label/slice/list/mask or a sequence of such You should use one of the above for each level. If a level should not be used, set it to ``slice(No...
def _setup_notification_listener(self, topic_name, url): """Setup notification listener for a service.""" self.notify_listener = rpc.DfaNotifcationListener( topic_name, url, rpc.DfaNotificationEndpoints(self))
Setup notification listener for a service.
def step(self, vector_action=None, memory=None, text_action=None, value=None, custom_action=None) -> AllBrainInfo: """ Provides the environment with an action, moves the environment dynamics forward accordingly, and returns observation, state, and reward information to the agent. :param ...
Provides the environment with an action, moves the environment dynamics forward accordingly, and returns observation, state, and reward information to the agent. :param value: Value estimates provided by agents. :param vector_action: Agent's vector action. Can be a scalar or vector of int/floats...
def plot2d(self, c_poly='default', alpha=1, cmap='default', ret=False, title=' ', colorbar=False, cbar_label=''): """ Generates a 2D plot for the z=0 Surface projection. :param c_poly: Polygons color. :type c_poly: matplotlib color :param alpha: Op...
Generates a 2D plot for the z=0 Surface projection. :param c_poly: Polygons color. :type c_poly: matplotlib color :param alpha: Opacity. :type alpha: float :param cmap: colormap :type cmap: matplotlib.cm :param ret: If True, returns the figure. It...
def yesterday(symbol, token='', version=''): '''This returns previous day adjusted price data for one or more stocks https://iexcloud.io/docs/api/#previous-day-prices Available after 4am ET Tue-Sat Args: symbol (string); Ticker to request token (string); Access token version (s...
This returns previous day adjusted price data for one or more stocks https://iexcloud.io/docs/api/#previous-day-prices Available after 4am ET Tue-Sat Args: symbol (string); Ticker to request token (string); Access token version (string); API version Returns: dict: resu...
def plot(self, figsize="GROW", parameters=None, chains=None, extents=None, filename=None, display=False, truth=None, legend=None, blind=None, watermark=None): # pragma: no cover """ Plot the chain! Parameters ---------- figsize : str|tuple(float)|float, optional ...
Plot the chain! Parameters ---------- figsize : str|tuple(float)|float, optional The figure size to generate. Accepts a regular two tuple of size in inches, or one of several key words. The default value of ``COLUMN`` creates a figure of appropriate size of i...
def append(self, species, coords, coords_are_cartesian=False, validate_proximity=False, properties=None): """ Append a site to the structure. Args: species: Species of inserted site coords (3x1 array): Coordinates of inserted site coords_are_ca...
Append a site to the structure. Args: species: Species of inserted site coords (3x1 array): Coordinates of inserted site coords_are_cartesian (bool): Whether coordinates are cartesian. Defaults to False. validate_proximity (bool): Whether to check...
def crescent_data(num_data=200, seed=default_seed): """ Data set formed from a mixture of four Gaussians. In each class two of the Gaussians are elongated at right angles to each other and offset to form an approximation to the crescent data that is popular in semi-supervised learning as a toy problem. :param ...
Data set formed from a mixture of four Gaussians. In each class two of the Gaussians are elongated at right angles to each other and offset to form an approximation to the crescent data that is popular in semi-supervised learning as a toy problem. :param num_data_part: number of data to be sampled (default is 200)...
def _color_name_to_rgb(self, color): " Turn 'ffffff', into (0xff, 0xff, 0xff). " try: rgb = int(color, 16) except ValueError: raise else: r = (rgb >> 16) & 0xff g = (rgb >> 8) & 0xff b = rgb & 0xff return r, g, b
Turn 'ffffff', into (0xff, 0xff, 0xff).
def get(self, key, default=None): """Returns the value of `key` if it exists, else `default`.""" if key in self._hparam_types: # Ensure that default is compatible with the parameter type. if default is not None: param_type, is_param_list = self._hparam_types[key] type_str = 'list<%s>...
Returns the value of `key` if it exists, else `default`.
def libvlc_media_player_set_time(p_mi, i_time): '''Set the movie time (in ms). This has no effect if no media is being played. Not all formats and protocols support this. @param p_mi: the Media Player. @param i_time: the movie time (in ms). ''' f = _Cfunctions.get('libvlc_media_player_set_time',...
Set the movie time (in ms). This has no effect if no media is being played. Not all formats and protocols support this. @param p_mi: the Media Player. @param i_time: the movie time (in ms).
def _append_slash_if_dir_path(self, relpath): """For a dir path return a path that has a trailing slash.""" if self._isdir_raw(relpath): return self._append_trailing_slash(relpath) return relpath
For a dir path return a path that has a trailing slash.
def Disks(self): """Return disks object associated with server. >>> clc.v2.Server("WA1BTDIX01").Disks() <clc.APIv2.disk.Disks object at 0x10feea190> """ if not self.disks: self.disks = clc.v2.Disks(server=self,disks_lst=self.data['details']['disks'],session=self.session) return(self.disks)
Return disks object associated with server. >>> clc.v2.Server("WA1BTDIX01").Disks() <clc.APIv2.disk.Disks object at 0x10feea190>
def build_struct_type(s_sdt): ''' Build an xsd complexType out of a S_SDT. ''' s_dt = nav_one(s_sdt).S_DT[17]() struct = ET.Element('xs:complexType', name=s_dt.name) first_filter = lambda selected: not nav_one(selected).S_MBR[46, 'succeeds']() s_mbr = nav_any(s_sdt).S_MBR[44](first...
Build an xsd complexType out of a S_SDT.
async def get_tracks(self, query) -> Tuple[Track, ...]: """ Gets tracks from lavalink. Parameters ---------- query : str Returns ------- Tuple[Track, ...] """ if not self._warned: log.warn("get_tracks() is now deprecated. Plea...
Gets tracks from lavalink. Parameters ---------- query : str Returns ------- Tuple[Track, ...]
def check_valid_solution(solution, graph): """Check that the solution is valid: every path is visited exactly once.""" expected = Counter( i for (i, _) in graph.iter_starts_with_index() if i < graph.get_disjoint(i) ) actual = Counter( min(i, graph.get_disjoint(i)) for i i...
Check that the solution is valid: every path is visited exactly once.
def search(self, **kwargs): """Firms search http://api.2gis.ru/doc/firms/searches/search/ """ point = kwargs.pop('point', False) if point: kwargs['point'] = '%s,%s' % (point[0], point[1]) bound = kwargs.pop('bound', False) if bound: kwar...
Firms search http://api.2gis.ru/doc/firms/searches/search/
def command(self, command, value=1, check=True, allowable_errors=None, codec_options=DEFAULT_CODEC_OPTIONS, _deadline=None, **kwargs): """command(command, value=1, check=True, allowable_errors=None, codec_options=DEFAULT_CODEC_OPTIONS)""" if isinstance(command, (bytes, unicode)): ...
command(command, value=1, check=True, allowable_errors=None, codec_options=DEFAULT_CODEC_OPTIONS)
def get_create_table_sql(self, table, create_flags=CREATE_INDEXES): """ Returns the SQL statement(s) to create a table with the specified name, columns and constraints on this platform. :param table: The table :type table: Table :type create_flags: int ...
Returns the SQL statement(s) to create a table with the specified name, columns and constraints on this platform. :param table: The table :type table: Table :type create_flags: int :rtype: str
def delim(arguments): """ Execute delim action. :param arguments: Parsed command line arguments from :func:`main` """ if bool(arguments.control_files) == bool(arguments.directory): raise ValueError( 'Exactly one of control_files and `-d` must be specified.') if argumen...
Execute delim action. :param arguments: Parsed command line arguments from :func:`main`
def render(self, *args, **kwargs): """ Render the template using keyword arguments as local variables. """ env = {}; stdout = [] for dictarg in args: env.update(dictarg) env.update(kwargs) self.execute(stdout, env) return ''.join(stdout)
Render the template using keyword arguments as local variables.
def parse_locator(locator): """ Parses a valid selenium By and value from a locator; returns as a named tuple with properties 'By' and 'value' locator -- a valid element locator or css string """ # handle backwards compatibility to support new Locator class if i...
Parses a valid selenium By and value from a locator; returns as a named tuple with properties 'By' and 'value' locator -- a valid element locator or css string
def add_rpt(self, sequence, mod, pt): """Add a repeater to the previous sequence""" modstr = self.value(mod) if modstr == '!!': # cursor on the REPEATER self._stream.restore_context() # log the error self.diagnostic.notify( error.Severity.ERROR, "Canno...
Add a repeater to the previous sequence
def pull(remote='origin', branch='master'): """git pull commit""" print(cyan("Pulling changes from repo ( %s / %s)..." % (remote, branch))) local("git pull %s %s" % (remote, branch))
git pull commit
def _generate_url_root(protocol, host, port): """ Generate API root URL without resources :param protocol: Web protocol [HTTP | HTTPS] (string) :param host: Hostname or IP (string) :param port: Service port (string) :return: ROOT url """ return URL_ROOT_PA...
Generate API root URL without resources :param protocol: Web protocol [HTTP | HTTPS] (string) :param host: Hostname or IP (string) :param port: Service port (string) :return: ROOT url
def get_coauthors(self): """Retrieves basic information about co-authors as a list of namedtuples in the form (surname, given_name, id, areas, affiliation_id, name, city, country), where areas is a list of subject area codes joined by "; ". Note: These information will not be cac...
Retrieves basic information about co-authors as a list of namedtuples in the form (surname, given_name, id, areas, affiliation_id, name, city, country), where areas is a list of subject area codes joined by "; ". Note: These information will not be cached and are slow for large c...
def save_load(jid, clear_load, minion=None): ''' Save the load to the specified jid ''' cb_ = _get_connection() try: jid_doc = cb_.get(six.text_type(jid)) except couchbase.exceptions.NotFoundError: cb_.add(six.text_type(jid), {}, ttl=_get_ttl()) jid_doc = cb_.get(six.tex...
Save the load to the specified jid
def stats_for(self, dt): """ Returns stats for the month containing the given datetime """ # TODO - this would be nicer if we formatted the stats if not isinstance(dt, datetime): raise TypeError('stats_for requires a datetime object!') return self._client.get(...
Returns stats for the month containing the given datetime
def status(self): """Get status on the repo. :return: :rtype: """ rd = self.repo_dir logger.debug("pkg path %s", rd) if not rd: print( "unable to find pkg '%s'. %s" % (self.name, did_u_mean(self.name)) ) cwd = os....
Get status on the repo. :return: :rtype:
def age(self, as_at_date=None): """ Compute the person's age """ if self.date_of_death != None or self.is_deceased == True: return None as_at_date = date.today() if as_at_date == None else as_at_date if self.date_of_birth != None: if (as_...
Compute the person's age
def enhancer(self): """Lazy loading of enhancements only if needed.""" if self._enhancer is None: self._enhancer = Enhancer(ppp_config_dir=self.ppp_config_dir) return self._enhancer
Lazy loading of enhancements only if needed.
def files_rm(self, path, recursive=False, **kwargs): """Removes a file from the MFS. .. code-block:: python >>> c.files_rm("/bla/file") b'' Parameters ---------- path : str Filepath within the MFS recursive : bool Recursi...
Removes a file from the MFS. .. code-block:: python >>> c.files_rm("/bla/file") b'' Parameters ---------- path : str Filepath within the MFS recursive : bool Recursively remove directories?
def moveCursor(self, cursorAction, modifiers): """ Returns a QModelIndex object pointing to the next object in the view, based on the given cursorAction and keyboard modifiers specified by modifiers. :param modifiers | <QtCore.Qt.KeyboardModifiers> ...
Returns a QModelIndex object pointing to the next object in the view, based on the given cursorAction and keyboard modifiers specified by modifiers. :param modifiers | <QtCore.Qt.KeyboardModifiers>
def empty(self, duration): '''Empty label annotations. Constructs a single observation with an empty value (None). Parameters ---------- duration : number > 0 The duration of the annotation ''' ann = super(DynamicLabelTransformer, self).empty(duratio...
Empty label annotations. Constructs a single observation with an empty value (None). Parameters ---------- duration : number > 0 The duration of the annotation
def edit_section(self, id, course_section_end_at=None, course_section_name=None, course_section_restrict_enrollments_to_section_dates=None, course_section_sis_section_id=None, course_section_start_at=None): """ Edit a section. Modify an existing section. """ path = {} ...
Edit a section. Modify an existing section.
def str_variants(institute_id, case_name): """Display a list of STR variants.""" page = int(request.args.get('page', 1)) variant_type = request.args.get('variant_type', 'clinical') form = StrFiltersForm(request.args) institute_obj, case_obj = institute_and_case(store, institute_id, case_name) ...
Display a list of STR variants.
def run_outdated(cls, options): """Print outdated user packages.""" latest_versions = sorted( cls.find_packages_latest_versions(cls.options), key=lambda p: p[0].project_name.lower()) for dist, latest_version, typ in latest_versions: if latest_version > dist.p...
Print outdated user packages.
def getRastersAsPngs(self, session, tableName, rasterIds, postGisRampString, rasterField='raster', rasterIdField='id', cellSize=None, resampleMethod='NearestNeighbour'): """ Return the raster in a PNG format """ # Validate VALID_RESAMPLE_METHODS = ('NearestNeighbour', 'Bilinear'...
Return the raster in a PNG format
def _dataflash_dir(self, mpstate): '''returns directory path to store DF logs in. May be relative''' if mpstate.settings.state_basedir is None: ret = 'dataflash' else: ret = os.path.join(mpstate.settings.state_basedir,'dataflash') try: os.makedirs(re...
returns directory path to store DF logs in. May be relative
def plot_isotherm(self, T, Pmin=None, Pmax=None, methods_P=[], pts=50, only_valid=True): # pragma: no cover r'''Method to create a plot of the property vs pressure at a specified temperature according to either a specified list of methods, or the user methods (if set), or...
r'''Method to create a plot of the property vs pressure at a specified temperature according to either a specified list of methods, or the user methods (if set), or all methods. User-selectable number of points, and pressure range. If only_valid is set, `test_method_validity_P` will be...
def expect(self, *args): '''Consume and return the next token if it has the correct type Multiple token types (as strings, e.g. 'integer64') can be given as arguments. If the next token is one of them, consume and return it. If the token type doesn't match, raise a ConfigParseError. ...
Consume and return the next token if it has the correct type Multiple token types (as strings, e.g. 'integer64') can be given as arguments. If the next token is one of them, consume and return it. If the token type doesn't match, raise a ConfigParseError.
def page(self, attr=None, fill=u' '): u'''Fill the entire screen.''' if attr is None: attr = self.attr if len(fill) != 1: raise ValueError info = CONSOLE_SCREEN_BUFFER_INFO() self.GetConsoleScreenBufferInfo(self.hout, byref(info)) if info.d...
u'''Fill the entire screen.
def _scheduleMePlease(self): """ This queue needs to have its run() method invoked at some point in the future. Tell the dependent scheduler to schedule it if it isn't already pending execution. """ sched = IScheduler(self.store) if len(list(sched.scheduledTimes(...
This queue needs to have its run() method invoked at some point in the future. Tell the dependent scheduler to schedule it if it isn't already pending execution.
def lock_file(path): """File based lock on ``path``. Creates a file based lock. When acquired, other processes or threads are prevented from acquiring the same lock until it is released. """ with _paths_lock: lock = _paths_to_locks.get(path) if lock is None: _paths_to_lo...
File based lock on ``path``. Creates a file based lock. When acquired, other processes or threads are prevented from acquiring the same lock until it is released.
def interface_by_ipaddr(self, ipaddr): ''' Given an IP address, return the interface that 'owns' this address ''' ipaddr = IPAddr(ipaddr) for devname,iface in self._devinfo.items(): if iface.ipaddr == ipaddr: return iface raise KeyError("No dev...
Given an IP address, return the interface that 'owns' this address
def kwargs_to_variable_assignment(kwargs: dict, value_representation=repr, assignment_operator: str = ' = ', statement_separator: str = '\n', statement_per_line: bool = False) -> str: """ Convert a dictionary i...
Convert a dictionary into a string with assignments Each assignment is constructed based on: key assignment_operator value_representation(value) statement_separator, where key and value are the key and value of the dictionary. Moreover one can seprate the assignment statements by new lines. Parame...
def params_size(m: Union[nn.Module,Learner], size: tuple = (3, 64, 64))->Tuple[Sizes, Tensor, Hooks]: "Pass a dummy input through the model to get the various sizes. Returns (res,x,hooks) if `full`" if isinstance(m, Learner): if m.data.is_empty: raise Exception("This is an empty `Learner` an...
Pass a dummy input through the model to get the various sizes. Returns (res,x,hooks) if `full`
def set_inbound_cipher( self, block_engine, block_size, mac_engine, mac_size, mac_key ): """ Switch inbound data cipher. """ self.__block_engine_in = block_engine self.__block_size_in = block_size self.__mac_engine_in = mac_engine self.__mac_size_in = ...
Switch inbound data cipher.
def comments(self): '''Looks through the last 3 messages and returns those comments.''' if self.cache['comments']: return self.cache['comments'] comments = [] for message in self.messages[0:3]: comment_xml = self.bc.comments(message.id) for comment_node in ET.from...
Looks through the last 3 messages and returns those comments.
def get_children(self): """Return an iterator for accessing the children of this cursor.""" # FIXME: Expose iteration from CIndex, PR6125. def visitor(child, parent, children): # FIXME: Document this assertion in API. # FIXME: There should just be an isNull method. ...
Return an iterator for accessing the children of this cursor.
async def service_messages(self, msg, _context): """Get all messages for a service.""" msgs = self.service_manager.service_messages(msg.get('name')) return [x.to_dict() for x in msgs]
Get all messages for a service.
def astype(array, y): """A functional form of the `astype` method. Args: array: The array or number to cast. y: An array or number, as the input, whose type should be that of array. Returns: An array or number with the same dtype as `y`. """ if isinstance(y, autograd.core.Node): return array...
A functional form of the `astype` method. Args: array: The array or number to cast. y: An array or number, as the input, whose type should be that of array. Returns: An array or number with the same dtype as `y`.
def ar_periodogram(x, window='hanning', window_len=7): """ Compute periodogram from data x, using prewhitening, smoothing and recoloring. The data is fitted to an AR(1) model for prewhitening, and the residuals are used to compute a first-pass periodogram with smoothing. The fitted coefficients ar...
Compute periodogram from data x, using prewhitening, smoothing and recoloring. The data is fitted to an AR(1) model for prewhitening, and the residuals are used to compute a first-pass periodogram with smoothing. The fitted coefficients are then used for recoloring. Parameters ---------- x : ...
def validate(self, config): """Validate that the source file is ok """ if not isinstance(config, ConfigObject): raise Exception("Config object expected") if config["output"]["componants"] not in ("local", "remote", "embedded", "without"): raise ValueError("Unknow...
Validate that the source file is ok
def handle_data(self, data): ''' Method called for each event by zipline. In intuition this is the place to factorize algorithms and then call event() ''' self.days += 1 signals = {} self.orderbook = {} # Everytime but the first tick if self.initialized and self....
Method called for each event by zipline. In intuition this is the place to factorize algorithms and then call event()
def set_os_environ(variables_mapping): """ set variables mapping to os.environ """ for variable in variables_mapping: os.environ[variable] = variables_mapping[variable] logger.log_debug("Set OS environment variable: {}".format(variable))
set variables mapping to os.environ
def bcesp(y1,y1err,y2,y2err,cerr,nsim=10000): """ Parallel implementation of the BCES with bootstrapping. Divide the bootstraps equally among the threads (cores) of the machine. It will automatically detect the number of cores available. Usage: >>> a,b,aerr,berr,covab=bcesp(x,xerr,y,yerr,cov,nsim) :param x,y: data ...
Parallel implementation of the BCES with bootstrapping. Divide the bootstraps equally among the threads (cores) of the machine. It will automatically detect the number of cores available. Usage: >>> a,b,aerr,berr,covab=bcesp(x,xerr,y,yerr,cov,nsim) :param x,y: data :param xerr,yerr: measurement errors affecting x an...
def ready_to_draw(mol): """Shortcut function to prepare molecule to draw. Overwrite this function for customized appearance. It is recommended to clone the molecule before draw because all the methods above are destructive. """ copied = molutil.clone(mol) # display_terminal_carbon(mol) e...
Shortcut function to prepare molecule to draw. Overwrite this function for customized appearance. It is recommended to clone the molecule before draw because all the methods above are destructive.
def instance(cls, size): """ Cache threadpool since context is recreated for each request """ if not getattr(cls, "_instance", None): cls._instance = {} if size not in cls._instance: cls._instance[size] = ThreadPool(size) return cls._instan...
Cache threadpool since context is recreated for each request
def mkIntDate(s): """ Convert the webserver formatted dates to an integer format by stripping the leading char and casting """ n = s.__len__() d = int(s[-(n - 1):n]) return d
Convert the webserver formatted dates to an integer format by stripping the leading char and casting
async def set_agent_neighbors(self): '''Set neighbors for all the agents in all the slave environments. Assumes that all the slave environments have their neighbors set. ''' for addr in self.addrs: r_manager = await self.env.connect(addr) await r_manager.set_agent...
Set neighbors for all the agents in all the slave environments. Assumes that all the slave environments have their neighbors set.
def compile_config(path, source=None, config_name=None, config_data=None, config_data_source=None, script_parameters=None, salt_env='base'): r''' Compile a config from a PowerShell script (``.ps1``)...
r''' Compile a config from a PowerShell script (``.ps1``) Args: path (str): Path (local) to the script that will create the ``.mof`` configuration file. If no source is passed, the file must exist locally. Required. source (str): Path to the script on ``file_roots`` to...
def getMeanInpCurrents(params, numunits=100, filepattern=os.path.join('simulation_output_default', 'population_input_spikes*')): '''return a dict with the per population mean and std synaptic current, averaging over numcells recorded units f...
return a dict with the per population mean and std synaptic current, averaging over numcells recorded units from each population in the network Returned currents are in unit of nA.
def make_path(*args): """ >>> _hack_make_path_doctest_output(make_path("/a", "b")) '/a/b' >>> _hack_make_path_doctest_output(make_path(["/a", "b"])) '/a/b' >>> _hack_make_path_doctest_output(make_path(*["/a", "b"])) '/a/b' >>> _hack_make_path_doctest_output(make_path("/a")) '/a' ...
>>> _hack_make_path_doctest_output(make_path("/a", "b")) '/a/b' >>> _hack_make_path_doctest_output(make_path(["/a", "b"])) '/a/b' >>> _hack_make_path_doctest_output(make_path(*["/a", "b"])) '/a/b' >>> _hack_make_path_doctest_output(make_path("/a")) '/a' >>> _hack_make_path_doctest_output...
def flatten(value): """value can be any nesting of tuples, arrays, dicts. returns 1D numpy array and an unflatten function.""" if isinstance(value, np.ndarray): def unflatten(vector): return np.reshape(vector, value.shape) return np.ravel(value), unflatten elif isinstance...
value can be any nesting of tuples, arrays, dicts. returns 1D numpy array and an unflatten function.
def parse_table_data(lines): """"Parse list of lines from SOFT file into DataFrame. Args: lines (:obj:`Iterable`): Iterator over the lines. Returns: :obj:`pandas.DataFrame`: Table data. """ # filter lines that do not start with symbols data = "\n".join([i.rstrip() for i in lin...
Parse list of lines from SOFT file into DataFrame. Args: lines (:obj:`Iterable`): Iterator over the lines. Returns: :obj:`pandas.DataFrame`: Table data.
def parse(self, text, *, metadata=None, filename="input"): """ Parses a string. Appends a list of blurb ENTRIES to self, as tuples: (metadata, body) metadata is a dict. body is a string. """ metadata = metadata or {} body = [] in_metadata = True ...
Parses a string. Appends a list of blurb ENTRIES to self, as tuples: (metadata, body) metadata is a dict. body is a string.
def _compute_bounds(self, axis, view): """Return the (min, max) bounding values of this visual along *axis* in the local coordinate system. """ is_vertical = self._is_vertical pos = self._pos if axis == 0 and is_vertical: return (pos[0, 0], pos[0, 0]) ...
Return the (min, max) bounding values of this visual along *axis* in the local coordinate system.
def parseFloat(self, words): """Convert a floating-point number described in words to a double. Supports two kinds of descriptions: those with a 'point' (e.g., "one point two five") and those with a fraction (e.g., "one and a quarter"). Args: words (str): Descriptio...
Convert a floating-point number described in words to a double. Supports two kinds of descriptions: those with a 'point' (e.g., "one point two five") and those with a fraction (e.g., "one and a quarter"). Args: words (str): Description of the floating-point number. ...
def density_und(CIJ): ''' Density is the fraction of present connections to possible connections. Parameters ---------- CIJ : NxN np.ndarray undirected (weighted/binary) connection matrix Returns ------- kden : float density N : int number of vertices k ...
Density is the fraction of present connections to possible connections. Parameters ---------- CIJ : NxN np.ndarray undirected (weighted/binary) connection matrix Returns ------- kden : float density N : int number of vertices k : int number of edges ...
def dutyCycle(self, active=False, readOnly=False): """Compute/update and return the positive activations duty cycle of this segment. This is a measure of how often this segment is providing good predictions. :param active True if segment just provided a good prediction :param readOnly If True, c...
Compute/update and return the positive activations duty cycle of this segment. This is a measure of how often this segment is providing good predictions. :param active True if segment just provided a good prediction :param readOnly If True, compute the updated duty cycle, but don't change ...
def from_http(cls, headers: Mapping[str, str]) -> Optional["RateLimit"]: """Gather rate limit information from HTTP headers. The mapping providing the headers is expected to support lowercase keys. Returns ``None`` if ratelimit info is not found in the headers. """ try: ...
Gather rate limit information from HTTP headers. The mapping providing the headers is expected to support lowercase keys. Returns ``None`` if ratelimit info is not found in the headers.
def set_file_paths(self, new_file_paths): """ Update this with a new set of paths to DAG definition files. :param new_file_paths: list of paths to DAG definition files :type new_file_paths: list[unicode] :return: None """ self._file_paths = new_file_paths ...
Update this with a new set of paths to DAG definition files. :param new_file_paths: list of paths to DAG definition files :type new_file_paths: list[unicode] :return: None
def send_result(self, return_code, output, service_description='', time_stamp=0, specific_servers=None): ''' Send result to the Skinken WS ''' if time_stamp == 0: time_stamp = int(time.time()) if specific_servers == None: specific_servers = self.servers ...
Send result to the Skinken WS
def joint_sfs_scaled(dac1, dac2, n1=None, n2=None): """Compute the joint site frequency spectrum between two populations, scaled such that a constant value is expected across the spectrum for neutral variation, constant population size and unrelated populations. Parameters ---------- dac1 : arr...
Compute the joint site frequency spectrum between two populations, scaled such that a constant value is expected across the spectrum for neutral variation, constant population size and unrelated populations. Parameters ---------- dac1 : array_like, int, shape (n_variants,) Derived allele co...
def get_resources_strings(self): """Returns a list of all the strings found withing the resources (if any). This method will scan all entries in the resources directory of the PE, if there is one, and will return a list() with the strings. An empty list will be returned...
Returns a list of all the strings found withing the resources (if any). This method will scan all entries in the resources directory of the PE, if there is one, and will return a list() with the strings. An empty list will be returned otherwise.
def get_last_live_chat(self): """ Check if there is a live chat that ended in the last 3 days, and return it. We will display a link to it on the articles page. """ now = datetime.now() lcqs = self.get_query_set() lcqs = lcqs.filter( chat_ends_at__lte=now...
Check if there is a live chat that ended in the last 3 days, and return it. We will display a link to it on the articles page.
def _xr_to_keyset(line): ''' Parse xfsrestore output keyset elements. ''' tkns = [elm for elm in line.strip().split(":", 1) if elm] if len(tkns) == 1: return "'{0}': ".format(tkns[0]) else: key, val = tkns return "'{0}': '{1}',".format(key.strip(), val.strip())
Parse xfsrestore output keyset elements.
def yum_install(self, packages, ignore_error=False): """Install some packages on the remote host. :param packages: ist of packages to install. """ return self.run('yum install -y --quiet ' + ' '.join(packages), ignore_error=ignore_error, retry=5)
Install some packages on the remote host. :param packages: ist of packages to install.
def get_publish_path(self, obj): """ publish_path joins the publish_paths for the chat type and the channel. """ return os.path.join( obj.chat_type.publish_path, obj.publish_path.lstrip("/") )
publish_path joins the publish_paths for the chat type and the channel.
def _CCompiler_spawn_silent(cmd, dry_run=None): """Spawn a process, and eat the stdio.""" proc = Popen(cmd, stdout=PIPE, stderr=PIPE) out, err = proc.communicate() if proc.returncode: raise DistutilsExecError(err)
Spawn a process, and eat the stdio.
def get_multi_generation(self, tables, db='default'): """Takes a list of table names and returns an aggregate value for the generation""" generations = [] for table in tables: generations.append(self.get_single_generation(table, db)) key = self.keygen.gen_multi_key(ge...
Takes a list of table names and returns an aggregate value for the generation
def create_chapter_from_string(self, html_string, url=None, title=None): """ Creates a Chapter object from a string. Sanitizes the string using the clean_function method, and saves it as the content of the created chapter. Args: html_string (string): The html or xhtm...
Creates a Chapter object from a string. Sanitizes the string using the clean_function method, and saves it as the content of the created chapter. Args: html_string (string): The html or xhtml content of the created Chapter url (Option[string]): A url to i...
def prepare(cls): """Prepare NApp to be uploaded by creating openAPI skeleton.""" if cls._ask_openapi(): napp_path = Path() tpl_path = SKEL_PATH / 'napp-structure/username/napp' OpenAPI(napp_path, tpl_path).render_template() print('Please, update your open...
Prepare NApp to be uploaded by creating openAPI skeleton.
def _set_default_configs(user_settings, default): """Set the default value to user settings if user not specified the value. """ for key in default: if key not in user_settings: user_settings[key] = default[key] return user_settings
Set the default value to user settings if user not specified the value.
def remove(self, document_id, namespace, timestamp): """Remove a document from Elasticsearch.""" index, doc_type = self._index_and_mapping(namespace) action = { '_op_type': 'delete', '_index': index, '_type': doc_type, '_id': u(document_id) ...
Remove a document from Elasticsearch.
def run_actions(self, actions): """ Runs the given lists of attached actions and instance actions on the client. :param actions: Actions to apply. :type actions: list[dockermap.map.action.ItemAction] :return: Where the result is not ``None``, returns the output from the client. ...
Runs the given lists of attached actions and instance actions on the client. :param actions: Actions to apply. :type actions: list[dockermap.map.action.ItemAction] :return: Where the result is not ``None``, returns the output from the client. Note that this is a generator and needs to...
def perspective(fovy, aspect, znear, zfar): """Create perspective projection matrix Parameters ---------- fovy : float The field of view along the y axis. aspect : float Aspect ratio of the view. znear : float Near coordinate of the field of view. zfar : float ...
Create perspective projection matrix Parameters ---------- fovy : float The field of view along the y axis. aspect : float Aspect ratio of the view. znear : float Near coordinate of the field of view. zfar : float Far coordinate of the field of view. Returns...
def tri_area(self, lons, lats): """ Calculate the area enclosed by 3 points on the unit sphere. Parameters ---------- lons : array of floats, shape (3) longitudinal coordinates in radians lats : array of floats, shape (3) latitudinal coordinates...
Calculate the area enclosed by 3 points on the unit sphere. Parameters ---------- lons : array of floats, shape (3) longitudinal coordinates in radians lats : array of floats, shape (3) latitudinal coordinates in radians Returns ------- ...