code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def read_mnist_images(filename, dtype=None): """Read MNIST images from the original ubyte file format. Parameters ---------- filename : str Filename/path from which to read images. dtype : 'float32', 'float64', or 'bool' If unspecified, images will be returned in their original ...
Read MNIST images from the original ubyte file format. Parameters ---------- filename : str Filename/path from which to read images. dtype : 'float32', 'float64', or 'bool' If unspecified, images will be returned in their original unsigned byte format. Returns ------- ...
def get_user_id(self): 'Returns "id" of a OneDrive user.' if self._user_id is None: self._user_id = self.get_user_data()['id'] return self._user_id
Returns "id" of a OneDrive user.
def register(self, model, handler=None): """ Register a permission handler to the model Parameters ---------- model : django model class A django model class handler : permission handler class, string, or None A permission handler class or a dotte...
Register a permission handler to the model Parameters ---------- model : django model class A django model class handler : permission handler class, string, or None A permission handler class or a dotted path Raises ------ ImproperlyConfi...
def action_is_satisfied(action): ''' Returns False if the parse would raise an error if no more arguments are given to this action, True otherwise. ''' num_consumed_args = _num_consumed_args.get(action, 0) if action.nargs in [OPTIONAL, ZERO_OR_MORE, REMAINDER]: return True if action.nargs =...
Returns False if the parse would raise an error if no more arguments are given to this action, True otherwise.
def _update_solution_data(self, s): """ Returns the voltage angle and generator set-point vectors. """ x = s["x"] # Va_var = self.om.get_var("Va") # Vm_var = self.om.get_var("Vm") # Pg_var = self.om.get_var("Pg") # Qg_var = self.om.get_var("Qg") Va = x[self._...
Returns the voltage angle and generator set-point vectors.
def split(self, verbose=None, end_in_new_line=None): """Save the elapsed time of the current split and restart the stopwatch. The current elapsed time will be appended to :attr:`split_elapsed_time`. If the stopwatch is paused, then it will remain paused. Otherwise, it will continue runn...
Save the elapsed time of the current split and restart the stopwatch. The current elapsed time will be appended to :attr:`split_elapsed_time`. If the stopwatch is paused, then it will remain paused. Otherwise, it will continue running. Parameters ---------- verbose : Op...
def update_timestamps(self, chan_id, ts): """Updates the timestamp for the given channel id. :param chan_id: :param ts: :return: """ try: self.last_update[chan_id] = ts except KeyError: self.log.warning("Attempted ts update of channel %s, ...
Updates the timestamp for the given channel id. :param chan_id: :param ts: :return:
def _create_tokens_for_next_line_dent(self, newline_token): """ Starting from a newline token that isn't followed by another newline token, returns any indent or dedent tokens that immediately follow. If indentation doesn't change, returns None. """ indent_delta = self._g...
Starting from a newline token that isn't followed by another newline token, returns any indent or dedent tokens that immediately follow. If indentation doesn't change, returns None.
def best_match(self, seqs, scan_rc=True): """ give the best match of each motif in each sequence returns an iterator of nested lists containing tuples: (score, position, strand) """ self.set_threshold(threshold=0.0) for matches in self.scan(seqs, 1, scan_rc): ...
give the best match of each motif in each sequence returns an iterator of nested lists containing tuples: (score, position, strand)
def zip(*args, **kwargs): """ Returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables (or default if too short). """ args = [list(iterable) for iterable in args] n = max(map(len, args)) v = kwargs.get("default", None) ret...
Returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables (or default if too short).
def check_stops( feed: "Feed", *, as_df: bool = False, include_warnings: bool = False ) -> List: """ Analog of :func:`check_agency` for ``feed.stops``. """ table = "stops" problems = [] # Preliminary checks if feed.stops is None: problems.append(["error", "Missing table", table,...
Analog of :func:`check_agency` for ``feed.stops``.
def init_app(self, app): """绑定app """ if app.config.MONGO_URIS and isinstance(app.config.MONGO_URIS, dict): self.MONGO_URIS = app.config.MONGO_URIS self.app = app else: raise ValueError( "nonstandard sanic config MONGO_URIS,MONGO_URIS ...
绑定app
def paginate_queryset(self, queryset, request, view=None): """ adds `max_count` as a running tally of the largest table size. Used for calculating next/previous links later """ result = super(MultipleModelLimitOffsetPagination, self).paginate_queryset(queryset, request, view) ...
adds `max_count` as a running tally of the largest table size. Used for calculating next/previous links later
def is_interface_up(interface): """ Checks if an interface is up. :param interface: interface name :returns: boolean """ if sys.platform.startswith("linux"): if interface not in psutil.net_if_addrs(): return False import fcntl SIOCGIFFLAGS = 0x8913 ...
Checks if an interface is up. :param interface: interface name :returns: boolean
def uploadfile(baseurl, filename, format_, token, nonce, cert, method=requests.post): """Uploads file (given by `filename`) to server at `baseurl`. `sesson_key` and `nonce` are string values that get passed as POST parameters. """ filehash = sha1sum(filename) files = {'filedata': open(filename,...
Uploads file (given by `filename`) to server at `baseurl`. `sesson_key` and `nonce` are string values that get passed as POST parameters.
def _get_magnitude_term(self, C, mag): """ Returns the magnitude scaling term - equation 3 """ if mag >= self.CONSTS["Mh"]: return C["e1"] + C["b3"] * (mag - self.CONSTS["Mh"]) else: return C["e1"] + (C["b1"] * (mag - self.CONSTS["Mh"])) +\ ...
Returns the magnitude scaling term - equation 3
def post(self, object_type, object_id): """Add new tags to an object.""" if object_id == 0: return Response(status=404) tagged_objects = [] for name in request.get_json(force=True): if ':' in name: type_name = name.split(':', 1)[0] ...
Add new tags to an object.
def express_route_ports_locations(self): """Instance depends on the API version: * 2018-08-01: :class:`ExpressRoutePortsLocationsOperations<azure.mgmt.network.v2018_08_01.operations.ExpressRoutePortsLocationsOperations>` """ api_version = self._get_api_version('express_route_ports_lo...
Instance depends on the API version: * 2018-08-01: :class:`ExpressRoutePortsLocationsOperations<azure.mgmt.network.v2018_08_01.operations.ExpressRoutePortsLocationsOperations>`
def render(self, doc, context=None, math_option=False, img_path='', css_path=CSS_PATH): """Start thread to render a given documentation""" # If the thread is already running wait for it to finish before # starting it again. if self.wait(): self.doc = doc ...
Start thread to render a given documentation
def get_z(self, var, coords=None): """ Get the vertical (z-) coordinate of a variable This method searches for the z-coordinate in the :attr:`ds`. It first checks whether there is one dimension that holds an ``'axis'`` attribute with 'Z', otherwise it looks whether there is an i...
Get the vertical (z-) coordinate of a variable This method searches for the z-coordinate in the :attr:`ds`. It first checks whether there is one dimension that holds an ``'axis'`` attribute with 'Z', otherwise it looks whether there is an intersection between the :attr:`z` attribute and...
def add_label(self, query_params=None): ''' Create a label for a board. Returns a new Label object. ''' list_json = self.fetch_json( uri_path=self.base_uri + '/labels', http_method='POST', query_params=query_params or {} ) return self....
Create a label for a board. Returns a new Label object.
def time_series( self, start_date='-30d', end_date='now', precision=None, distrib=None, tzinfo=None): """ Returns a generator yielding tuples of ``(<datetime>, <value>)``. The data points will start at ``start_date``, and b...
Returns a generator yielding tuples of ``(<datetime>, <value>)``. The data points will start at ``start_date``, and be at every time interval specified by ``precision``. ``distrib`` is a callable that accepts ``<datetime>`` and returns ``<value>``
def from_sites(cls, sites, charge=None, validate_proximity=False, to_unit_cell=False): """ Convenience constructor to make a Structure from a list of sites. Args: sites: Sequence of PeriodicSites. Sites must have the same lattice. valid...
Convenience constructor to make a Structure from a list of sites. Args: sites: Sequence of PeriodicSites. Sites must have the same lattice. validate_proximity (bool): Whether to check if there are sites that are less than 0.01 Ang apart. Defaults to False...
def _terminalSymbolsGenerator(self): """Generator of unique terminal symbols used for building the Generalized Suffix Tree. Unicode Private Use Area U+E000..U+F8FF is used to ensure that terminal symbols are not part of the input string. """ py2 = sys.version[0] < '3' UPP...
Generator of unique terminal symbols used for building the Generalized Suffix Tree. Unicode Private Use Area U+E000..U+F8FF is used to ensure that terminal symbols are not part of the input string.
def stream_url(self, item, *, device_id=None, quality='hi', session_token=None): """Get a URL to stream a podcast episode, library song, station_song, or store song. Note: Streaming requires a ``device_id`` from a valid, linked mobile device. Parameters: item (str): A podcast episode, library song, statio...
Get a URL to stream a podcast episode, library song, station_song, or store song. Note: Streaming requires a ``device_id`` from a valid, linked mobile device. Parameters: item (str): A podcast episode, library song, station_song, or store song. A Google Music subscription is required to stream store son...
def get_filename(self, task, default_ext): """Set the path where the image will be saved. The default strategy is to use an increasing 6-digit number as the filename. You can override this method if you want to set custom naming rules. The file extension is kept if it can be obtained fr...
Set the path where the image will be saved. The default strategy is to use an increasing 6-digit number as the filename. You can override this method if you want to set custom naming rules. The file extension is kept if it can be obtained from the url, otherwise ``default_ext`` is used ...
def get_consistent_resource(self): """ :return a payment that you can trust. :rtype Payment """ http_client = HttpClient() response, _ = http_client.get(routes.url(routes.PAYMENT_RESOURCE, resource_id=self.id)) return Payment(**response)
:return a payment that you can trust. :rtype Payment
def write_grid_tpl(name, tpl_file, suffix, zn_array=None, shape=None, spatial_reference=None,longnames=False): """ write a grid-based template file Parameters ---------- name : str the base parameter name tpl_file : str the template file to write - include path ...
write a grid-based template file Parameters ---------- name : str the base parameter name tpl_file : str the template file to write - include path zn_array : numpy.ndarray an array used to skip inactive cells Returns ------- df : pandas.DataFrame a datafr...
def abs_timedelta(delta): """Returns an "absolute" value for a timedelta, always representing a time distance.""" if delta.days < 0: now = _now() return now - (now + delta) return delta
Returns an "absolute" value for a timedelta, always representing a time distance.
def attributes_js(cls, attributes): """ Generates JS code to look up attributes on JS objects from an attributes specification dictionary. If the specification references a plotting particular plotting handle it will also generate JS code to get the ID of the object. Sim...
Generates JS code to look up attributes on JS objects from an attributes specification dictionary. If the specification references a plotting particular plotting handle it will also generate JS code to get the ID of the object. Simple example (when referencing cb_data or cb_obj): ...
def linspace(start, stop, num, decimals=18): """ Returns a list of evenly spaced numbers over a specified interval. Inspired from Numpy's linspace function: https://github.com/numpy/numpy/blob/master/numpy/core/function_base.py :param start: starting value :type start: float :param stop: end value...
Returns a list of evenly spaced numbers over a specified interval. Inspired from Numpy's linspace function: https://github.com/numpy/numpy/blob/master/numpy/core/function_base.py :param start: starting value :type start: float :param stop: end value :type stop: float :param num: number of samp...
def setup_signals(self, ): """Connect the signals with the slots to make the ui functional :returns: None :rtype: None :raises: None """ self.duplicate_tb.clicked.connect(self.duplicate) self.delete_tb.clicked.connect(self.delete) self.load_tb.clicked.con...
Connect the signals with the slots to make the ui functional :returns: None :rtype: None :raises: None
def _get_stddevs(self, C, stddev_types, num_sites, mag): """ Returns standard deviation as defined in equation 23, page 2291 (Tavakoli and Pezeshk, 2005) """ stddevs = [] sigma = (C['c14'] + C['c15'] * mag) if mag < 7.2 else C['c16'] vals = sigma * np.ones((num_si...
Returns standard deviation as defined in equation 23, page 2291 (Tavakoli and Pezeshk, 2005)
def sendpfast(x, pps=None, mbps=None, realtime=None, loop=0, file_cache=False, iface=None, verbose=True): """Send packets at layer 2 using tcpreplay for performance pps: packets per second mpbs: MBits per second realtime: use packet's timestamp, bending time with realtime value loop: number of time...
Send packets at layer 2 using tcpreplay for performance pps: packets per second mpbs: MBits per second realtime: use packet's timestamp, bending time with realtime value loop: number of times to process the packet list file_cache: cache packets in RAM instead of reading from disk at each iteration ...
def extract_common_fields(self, data): """Extract fields from a basic user query.""" email = None for curr_email in data.get("emails", []): email = email or curr_email.get("email") if curr_email.get("verified", False) and \ curr_email.get("primary", Fa...
Extract fields from a basic user query.
def sphere_pos(self, x): """Sphere (squared norm) test objective function""" # return np.random.rand(1)[0]**0 * sum(x**2) + 1 * np.random.rand(1)[0] c = 0.0 if x[0] < c: return np.nan return -c**2 + sum((x + 0)**2)
Sphere (squared norm) test objective function
def get_location(self,callb=None): """Convenience method to request the location from the device This method will check whether the value has already been retrieved from the device, if so, it will simply return it. If no, it will request the information from the device and request that ...
Convenience method to request the location from the device This method will check whether the value has already been retrieved from the device, if so, it will simply return it. If no, it will request the information from the device and request that callb be executed when a response is received....
def get_host_lock(url): """Get lock object for given URL host.""" hostname = get_hostname(url) return host_locks.setdefault(hostname, threading.Lock())
Get lock object for given URL host.
def merge(self, conflicted, tables=[], diff_only=True): """ Merges specific **tables** or all tables of **conflicted** database into the master database. Parameters ---------- conflicted: str The path of the SQL database to be merged into the master. tables: ...
Merges specific **tables** or all tables of **conflicted** database into the master database. Parameters ---------- conflicted: str The path of the SQL database to be merged into the master. tables: list (optional) The list of tables to merge. If None, all tables...
def validate_data_table(data_table, sed=None): """ Validate all columns of a data table. If a list of tables is passed, all tables will be validated and then concatenated Parameters ---------- data_table : `astropy.table.Table` or list of `astropy.table.Table`. sed : bool, optional ...
Validate all columns of a data table. If a list of tables is passed, all tables will be validated and then concatenated Parameters ---------- data_table : `astropy.table.Table` or list of `astropy.table.Table`. sed : bool, optional Whether to convert the fluxes to SED. If unset, all data ...
def render_footer(self, ctx, data): """ Render any required static content in the footer, from the C{staticContent} attribute of this page. """ if self.staticContent is None: return ctx.tag header = self.staticContent.getFooter() if header is not None...
Render any required static content in the footer, from the C{staticContent} attribute of this page.
def id_lookup(paper_id, idtype): """Take an ID of type PMID, PMCID, or DOI and lookup the other IDs. If the DOI is not found in Pubmed, try to obtain the DOI by doing a reverse-lookup of the DOI in CrossRef using article metadata. Parameters ---------- paper_id : str ID of the article....
Take an ID of type PMID, PMCID, or DOI and lookup the other IDs. If the DOI is not found in Pubmed, try to obtain the DOI by doing a reverse-lookup of the DOI in CrossRef using article metadata. Parameters ---------- paper_id : str ID of the article. idtype : str Type of the ID...
def get_mime_message(subject, text): """Creates MIME message :param subject: Subject of email :param text: Email content :return: Email formatted as HTML ready to be sent """ message = MIMEText( "<html>" + str(text).replace("\n", "<br>") + "</html>", "html" ) mes...
Creates MIME message :param subject: Subject of email :param text: Email content :return: Email formatted as HTML ready to be sent
def get_cache_key(brain_or_object): """Generate a cache key for a common brain or object :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :returns: Cache Key :rtype: str """ key = [ get_portal_typ...
Generate a cache key for a common brain or object :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :returns: Cache Key :rtype: str
def new_portfolio(self, portfolio_cookie=None): ''' 根据 self.user_cookie 创建一个 portfolio :return: 如果存在 返回 新建的 QA_Portfolio 如果已经存在 返回 这个portfolio ''' _portfolio = QA_Portfolio( user_cookie=self.user_cookie, portfolio_cookie=portfolio_cookie ...
根据 self.user_cookie 创建一个 portfolio :return: 如果存在 返回 新建的 QA_Portfolio 如果已经存在 返回 这个portfolio
def _api_handler(self, *args, **kwargs): """ Thin wrapper around api_handler from `indicoio.utils.api` to add in stored keyword argument to the JSON body """ keyword_arguments = {} keyword_arguments.update(self.keywords) keyword_arguments.update(kwargs) return api...
Thin wrapper around api_handler from `indicoio.utils.api` to add in stored keyword argument to the JSON body
def display_grid_scores(grid_scores, top=None): """Helper function to format a report on a grid of scores""" grid_scores = sorted(grid_scores, key=lambda x: x[1], reverse=True) if top is not None: grid_scores = grid_scores[:top] # Compute a threshold for staring models with overlapping ...
Helper function to format a report on a grid of scores
def _get_nameservers(domain): """ Looks for domain nameservers and returns the IPs of the nameservers as a list. The list is empty, if no nameservers were found. Needed associated domain zone name for lookup. """ nameservers = [] rdtypes_ns = ['SOA', 'NS'] ...
Looks for domain nameservers and returns the IPs of the nameservers as a list. The list is empty, if no nameservers were found. Needed associated domain zone name for lookup.
def get_fastq_files(directory, lane, fc_name): """Retrieve fastq files for the given lane, ready to process. """ files = glob.glob(os.path.join(directory, "%s_*%s*txt*" % (lane, fc_name))) files.sort() if len(files) > 2 or len(files) == 0: raise ValueError("Did not find correct files for %s ...
Retrieve fastq files for the given lane, ready to process.
def visit_tryfinally(self, node, parent): """visit a TryFinally node by returning a fresh instance of it""" newnode = nodes.TryFinally(node.lineno, node.col_offset, parent) newnode.postinit( [self.visit(child, newnode) for child in node.body], [self.visit(n, newnode) for ...
visit a TryFinally node by returning a fresh instance of it
def _set_prior(self, prior): """Set prior for this parameter. The prior must be a function accepting the current value of the parameter as input and giving the probability density as output.""" if prior is None: # Removing prior self._prior = None else: ...
Set prior for this parameter. The prior must be a function accepting the current value of the parameter as input and giving the probability density as output.
def consecutiveness(password, consecutive_length=3): """ Consecutiveness is the enemy of entropy, but makes it easier to remember. :param str password: :param int consecutive_length: length of the segment to be uniform to consider loss of entropy :param int base_length: usual len...
Consecutiveness is the enemy of entropy, but makes it easier to remember. :param str password: :param int consecutive_length: length of the segment to be uniform to consider loss of entropy :param int base_length: usual length of the password :return int: in range 0-1 >>> Complex...
def parse_root(raw): "Efficiently parses the root element of a *raw* XML document, returning a tuple of its qualified name and attribute dictionary." if sys.version < '3': fp = StringIO(raw) else: fp = BytesIO(raw.encode('UTF-8')) for event, element in etree.iterparse(fp, events=('start'...
Efficiently parses the root element of a *raw* XML document, returning a tuple of its qualified name and attribute dictionary.
def taxids(self): """Distinct NCBI taxonomy identifiers (``taxid``) in :class:`.models.Entry` :return: NCBI taxonomy identifiers :rtype: list[int] """ r = self.session.query(distinct(models.Entry.taxid)).all() return [x[0] for x in r]
Distinct NCBI taxonomy identifiers (``taxid``) in :class:`.models.Entry` :return: NCBI taxonomy identifiers :rtype: list[int]
def typed_encode(self, r): """ :param record: expecting id and value properties :return: dict with id and json properties """ try: value = r.get('value') if "json" in r: value = json2value(r["json"]) elif is_data(value) or val...
:param record: expecting id and value properties :return: dict with id and json properties
def exception_handler(job, *exc_info): """ Called by RQ when there is a failure in a worker. NOTE: Make sure that in your RQ worker process, rollbar.init() has been called with handler='blocking'. The default handler, 'thread', does not work from inside an RQ worker. """ # Report data about the...
Called by RQ when there is a failure in a worker. NOTE: Make sure that in your RQ worker process, rollbar.init() has been called with handler='blocking'. The default handler, 'thread', does not work from inside an RQ worker.
def validate(nanopub: dict, error_level: str = "WARNING") -> Tuple[str, str, str]: """Validate Nanopub Error Levels are similar to log levels - selecting WARNING includes both WARNING and ERROR, selecting ERROR just includes ERROR The validation result is a list of objects containing { ...
Validate Nanopub Error Levels are similar to log levels - selecting WARNING includes both WARNING and ERROR, selecting ERROR just includes ERROR The validation result is a list of objects containing { 'level': 'Warning|Error', 'section': 'Assertion|Annotation|Structure', ...
def createKeyboardTab(self): ''' KEYBOARD ''' _keyboardList = [ 'KEYCODE_1', 'KEYCODE_2', 'KEYCODE_3', 'KEYCODE_4', 'KEYCODE_5', 'KEYCODE_6', 'KEYCODE_7', 'KEYCODE_8', 'KEYCODE_9', 'KEYCODE_0', 'KEYCODE_Q', 'KEYCODE_W', 'KEYCODE_E', 'KEYCODE_R', 'KEYCODE_T', 'KEYCODE_...
KEYBOARD
def stage_http_response2(self, payload): """Log complete http response, including response1 and payload""" # required because http code uses sending all None to reset # parameters. We ignore that if not self._http_response_version and not payload: return if self.enab...
Log complete http response, including response1 and payload
def copy_format(self): """Copies the format of the selected cells to the Clipboard Cells are shifted so that the top left bbox corner is at 0,0 """ row, col, tab = self.grid.actions.cursor code_array = self.grid.code_array # Cell attributes new_cell_attribute...
Copies the format of the selected cells to the Clipboard Cells are shifted so that the top left bbox corner is at 0,0
def handle_fail_rcs(self, req): """ Bail out if we get a 401 and leave a message """ try: logger.debug("HTTP Status Code: %s", req.status_code) logger.debug("HTTP Response Text: %s", req.text) logger.debug("HTTP Response Reason: %s", req.reason) ...
Bail out if we get a 401 and leave a message
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'document_retrieval_strategy' ) and self.document_retrieval_strategy is not None: _dict[ 'document_retrieval_strategy'] = self.document_retrieval_...
Return a json dictionary representing this model.
def create(self, message, mid=None, age=60, force=True): """ create session force if you pass `force = False`, it may raise SessionError due to duplicate message id """ with self.session_lock: if not hasattr(message, "id"): message....
create session force if you pass `force = False`, it may raise SessionError due to duplicate message id
def restore_gc_state(): """ Restore the garbage collector state on leaving the with block. """ old_isenabled = gc.isenabled() old_flags = gc.get_debug() try: yield finally: gc.set_debug(old_flags) (gc.enable if old_isenabled else gc.disable)()
Restore the garbage collector state on leaving the with block.
def _get_axis_data(self, bunch, dim, cluster_id=None, load_all=None): """Extract the points from the data on a given dimension. bunch is returned by the features() function. dim is the string specifying the dimensions to extract for the data. """ if dim in self.attributes: ...
Extract the points from the data on a given dimension. bunch is returned by the features() function. dim is the string specifying the dimensions to extract for the data.
def distb(self, tb=None, file=None): """Disassemble a traceback (default: last traceback).""" if tb is None: try: tb = sys.last_traceback except AttributeError: raise RuntimeError("no last traceback to disassemble") while tb.tb_next: tb...
Disassemble a traceback (default: last traceback).
def plot_magseries(times, mags, magsarefluxes=False, errs=None, out=None, sigclip=30.0, normto='globalmedian', normmingap=4.0, timebin=None, yrange=N...
This plots a magnitude/flux time-series. Parameters ---------- times,mags : np.array The mag/flux time-series to plot as a function of time. magsarefluxes : bool Indicates if the input `mags` array is actually an array of flux measurements instead of magnitude measurements. If...
def frequency_psd_from_qd(self, tau0=1.0): """ return frequency power spectral density coefficient h_a for the noise type defined by (qd, b, tau0) Colored noise generated with (qd, b, tau0) parameters will show a frequency power spectral density of S_y(f) = Freq...
return frequency power spectral density coefficient h_a for the noise type defined by (qd, b, tau0) Colored noise generated with (qd, b, tau0) parameters will show a frequency power spectral density of S_y(f) = Frequency_PSD(f) = h_a * f^a where the slope a ...
def positionToIntensityUncertainty(image, sx, sy, kernelSize=None): ''' calculates the estimated standard deviation map from the changes of neighbouring pixels from a center pixel within a point spread function defined by a std.dev. in x and y taken from the (sx, sy) maps sx,sy -> either 2d ...
calculates the estimated standard deviation map from the changes of neighbouring pixels from a center pixel within a point spread function defined by a std.dev. in x and y taken from the (sx, sy) maps sx,sy -> either 2d array of same shape as [image] of single values
def get_env_credential(env='dev'): """Get Account Credential from Spinnaker for *env*. Args: env (str): Environment name to find credentials for. Returns: dict: Complete credentials for *env*:: { 'accountId': '123098123', 'accountType': 'dev', ...
Get Account Credential from Spinnaker for *env*. Args: env (str): Environment name to find credentials for. Returns: dict: Complete credentials for *env*:: { 'accountId': '123098123', 'accountType': 'dev', 'assumeRole': 'role/spinnak...
def references(self, env, object_name, model, assoc_class, result_class_name, role, result_role, keys_only): """Instrument Associations. All four association-related operations (Associators, AssociatorNames, References, ReferenceNames) are mapped to this method. This ...
Instrument Associations. All four association-related operations (Associators, AssociatorNames, References, ReferenceNames) are mapped to this method. This method is a python generator Keyword arguments: env -- Provider Environment (pycimmb.ProviderEnvironment) object_n...
def nvm_primer(): '''Getting started with nvm (cf. https://github.com/creationix/nvm#usage). ''' print('\nDownload, compile and install the latest release of node:\n\n' + cyan(' nvm install node')) print('\nAnd then in any new shell:\n\n' + cyan(' nvm use node') + ' # use the...
Getting started with nvm (cf. https://github.com/creationix/nvm#usage).
def _create_keywords_wizard_action(self): """Create action for keywords creation wizard.""" icon = resources_path('img', 'icons', 'show-keyword-wizard.svg') self.action_keywords_wizard = QAction( QIcon(icon), self.tr('Keywords Creation Wizard'), self.iface.mai...
Create action for keywords creation wizard.
def clean_videos(self): """ Validates that all values in the video list are integer ids and removes all None values. """ if self.videos: self.videos = [int(v) for v in self.videos if v is not None and is_valid_digit(v)]
Validates that all values in the video list are integer ids and removes all None values.
def _sweep(self): """ Checks the state of each measurement and verifies their state, if an active measurement is now complete then passes them to the completed measurement set, if failed then to the failed set, if failed and old then evicts. :return: """ while self.runnin...
Checks the state of each measurement and verifies their state, if an active measurement is now complete then passes them to the completed measurement set, if failed then to the failed set, if failed and old then evicts. :return:
def getFreeEnergyDifferences(self, compute_uncertainty=True, uncertainty_method=None, warning_cutoff=1.0e-10, return_theta=False): """Get the dimensionless free energy differences and uncertainties among all thermodynamic states. Parameters ---------- compute_uncertainty : bool, option...
Get the dimensionless free energy differences and uncertainties among all thermodynamic states. Parameters ---------- compute_uncertainty : bool, optional If False, the uncertainties will not be computed (default: True) uncertainty_method : string, optional Choi...
def emit(self, record): """ Publish record to redis logging list """ try: if self.max_messages: p = self.redis_client.pipeline() p.rpush(self.key, self.format(record)) p.ltrim(self.key, -self.max_messages, -1) p....
Publish record to redis logging list
def monkey_patch(): """ Monkey patches `zmq.Context` and `zmq.Socket` If test_suite is True, the pyzmq test suite will be patched for compatibility as well. """ ozmq = __import__('zmq') ozmq.Socket = zmq.Socket ozmq.Context = zmq.Context ozmq.Poller = zmq.Poller ioloop = __impor...
Monkey patches `zmq.Context` and `zmq.Socket` If test_suite is True, the pyzmq test suite will be patched for compatibility as well.
def advance_job_status(namespace: str, job: Job, duration: float, err: Optional[Exception]): """Advance the status of a job depending on its execution. This function is called after a job has been executed. It calculates its next status and calls the appropriate signals. """ ...
Advance the status of a job depending on its execution. This function is called after a job has been executed. It calculates its next status and calls the appropriate signals.
def insert(self): """persist the .fields""" self.default_val = 0 #fields = self.fields #fields = self.orm_class.depart(self.fields, is_update=False) #self.set_fields(fields) return self.interface.insert( self.schema, self.fields ) ...
persist the .fields
def _get_leftMargin(self): """ This must return an int or float. If the glyph has no outlines, this must return `None`. Subclasses may override this method. """ bounds = self.bounds if bounds is None: return None xMin, yMin, xMax, yMax = bound...
This must return an int or float. If the glyph has no outlines, this must return `None`. Subclasses may override this method.
def cbday_roll(self): """ Define default roll function to be called in apply method. """ cbday = CustomBusinessDay(n=self.n, normalize=False, **self.kwds) if self._prefix.endswith('S'): # MonthBegin roll_func = cbday.rollforward else: ...
Define default roll function to be called in apply method.
def colored_level_name(self, levelname): """ Colors the logging level in the logging record """ if self.colors_disabled: return self.plain_levelname_format.format(levelname) else: return self.colored_levelname_format.format(self.color_map[levelname], level...
Colors the logging level in the logging record
def create_port(self, context, network_id, port_id, **kwargs): """Create a port. :param context: neutron api request context. :param network_id: neutron network id. :param port_id: neutron port id. :param kwargs: required keys - device_id: neutron port device_id (ins...
Create a port. :param context: neutron api request context. :param network_id: neutron network id. :param port_id: neutron port id. :param kwargs: required keys - device_id: neutron port device_id (instance_id) instance_node_id: nova hypervisor ho...
def series_to_yaml_safe(series, ordered=False): """ Convert a pandas Series to a dict that will survive YAML serialization and re-conversion back to a Series. Parameters ---------- series : pandas.Series ordered: bool, optional, default False If True, an OrderedDict is returned. ...
Convert a pandas Series to a dict that will survive YAML serialization and re-conversion back to a Series. Parameters ---------- series : pandas.Series ordered: bool, optional, default False If True, an OrderedDict is returned. Returns ------- safe : dict or OrderedDict
def drawItem(self, item, painter, option): """ Draws the inputed item as a bar graph. :param item | <XChartDatasetItem> painter | <QPainter> option | <QStyleOptionGraphicsItem> """ dataset = item.dataset() ...
Draws the inputed item as a bar graph. :param item | <XChartDatasetItem> painter | <QPainter> option | <QStyleOptionGraphicsItem>
def negative_gradient(self, y, y_pred, sample_weight=None, **kwargs): """Negative gradient of partial likelihood Parameters --------- y : tuple, len = 2 First element is boolean event indicator and second element survival/censoring time. y_pred : np.ndarray, shape=(n...
Negative gradient of partial likelihood Parameters --------- y : tuple, len = 2 First element is boolean event indicator and second element survival/censoring time. y_pred : np.ndarray, shape=(n,): The predictions.
def firmware_manifest_retrieve(self, manifest_id, **kwargs): # noqa: E501 """Get a manifest # noqa: E501 Retrieve a firmware manifest. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchronous=True >>>...
Get a manifest # noqa: E501 Retrieve a firmware manifest. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchronous=True >>> thread = api.firmware_manifest_retrieve(manifest_id, asynchronous=True) >>> r...
def validate(self, input_string): """ Validate url :return: True if match / False otherwise """ parsed_url = urlparse(url=input_string) return bool(parsed_url.scheme and parsed_url.netloc)
Validate url :return: True if match / False otherwise
def approve(group_id, user_id): """Approve a user.""" membership = Membership.query.get_or_404((user_id, group_id)) group = membership.group if group.can_edit(current_user): try: membership.accept() except Exception as e: flash(str(e), 'error') return...
Approve a user.
def pattern_match(pattern, string): """ :type pattern: str :type string: str :rtype: bool """ def backtrack(pattern, string, dic): if len(pattern) == 0 and len(string) > 0: return False if len(pattern) == len(string) == 0: return True for end in...
:type pattern: str :type string: str :rtype: bool
async def _get_packet_from_stream(self, stream, existing_data, got_first_packet=True, psml_structure=None): """A coroutine which returns a single packet if it can be read from the given StreamReader. :return a tuple of (packet, remaining_data). The packet will be None if there was not enough XML data t...
A coroutine which returns a single packet if it can be read from the given StreamReader. :return a tuple of (packet, remaining_data). The packet will be None if there was not enough XML data to create a packet. remaining_data is the leftover data which was not enough to create a packet from. :r...
def dev_parameters_vs_axis(dnaRef, dnaSubj, parameter, bp, axis='Z', bp_range=True, windows=10, err_type='block', tool='gmx analyze'): """To calculate deviation in the given parameters of a Subject DNA to Reference DNA along the given axis. .. note:: Deviation = Reference_DNA(parameter) - Subject_DNA(parameter...
To calculate deviation in the given parameters of a Subject DNA to Reference DNA along the given axis. .. note:: Deviation = Reference_DNA(parameter) - Subject_DNA(parameter) .. warning:: To calculate errors by using ``error = 'acf'`` or ``error = 'block'``, GROMACS tool ``g_analyze`` ...
def apply(self, func, axis=0, subset=None, **kwargs): """ Apply a function column-wise, row-wise, or table-wise, updating the HTML representation with the result. Parameters ---------- func : function ``func`` should take a Series or DataFrame (depending ...
Apply a function column-wise, row-wise, or table-wise, updating the HTML representation with the result. Parameters ---------- func : function ``func`` should take a Series or DataFrame (depending on ``axis``), and return an object with the same shape. ...
def debit(self, amount, credit_account, description, debit_memo="", credit_memo="", datetime=None): """ Post a debit of 'amount' and a credit of -amount against this account and credit_account respectively. note amount must be non-negative. """ assert amount >= 0 return self.po...
Post a debit of 'amount' and a credit of -amount against this account and credit_account respectively. note amount must be non-negative.
def masked_rec_array_to_mgr(data, index, columns, dtype, copy): """ Extract from a masked rec array and create the manager. """ # essentially process a record array then fill it fill_value = data.fill_value fdata = ma.getdata(data) if index is None: index = get_names_from_index(fdat...
Extract from a masked rec array and create the manager.
def find_card_bundles(provider: Provider, deck: Deck) -> Optional[Iterator]: '''each blockchain transaction can contain multiple cards, wrapped in bundles. This method finds and returns those bundles.''' if isinstance(provider, RpcNode): if deck.id is None: raise Exception("deck.id r...
each blockchain transaction can contain multiple cards, wrapped in bundles. This method finds and returns those bundles.
def Synchronized(f): """Synchronization decorator.""" @functools.wraps(f) def NewFunction(self, *args, **kw): with self.lock: return f(self, *args, **kw) return NewFunction
Synchronization decorator.
def compare_dicts(old=None, new=None): ''' Compare before and after results from various salt functions, returning a dict describing the changes that were made. ''' ret = {} for key in set((new or {})).union((old or {})): if key not in old: # New key ret[key] = {'...
Compare before and after results from various salt functions, returning a dict describing the changes that were made.
def imbtree(ntips, treeheight=1.0): """ Return an imbalanced (comb-like) tree topology. """ rtree = toytree.tree() rtree.treenode.add_child(name="0") rtree.treenode.add_child(name="1") for i in range(2, ntips): # empty node cherry = toytre...
Return an imbalanced (comb-like) tree topology.