code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def _gamma_factorial(self, expr, n): r""" Compute :math:`\frac {(\alpha)_m = (\alpha + m - 1)!}{(\alpha - 1)!}` See Eq. 3 in Gamma moment closure Lakatos 2014 unpublished :param expr: a symbolic expression :type expr: :param n: :type n: `int` :return: a ...
r""" Compute :math:`\frac {(\alpha)_m = (\alpha + m - 1)!}{(\alpha - 1)!}` See Eq. 3 in Gamma moment closure Lakatos 2014 unpublished :param expr: a symbolic expression :type expr: :param n: :type n: `int` :return: a symbolic expression
def get_options_for_id(options: Dict[str, Dict[str, Any]], identifier: str): """ Helper method, from the full options dict of dicts, to return either the options related to this parser or an empty dictionary. It also performs all the var type checks :param options: :param identifier: :return: ...
Helper method, from the full options dict of dicts, to return either the options related to this parser or an empty dictionary. It also performs all the var type checks :param options: :param identifier: :return:
def from_cwl(cls, data, __reference__=None): """Return an instance from CWL data.""" class_name = data.get('class', None) cls = cls.registry.get(class_name, cls) if __reference__: with with_reference(__reference__): self = cls( **{k: v ...
Return an instance from CWL data.
def accumulate(self, axis: AxisIdentifier) -> HistogramBase: """Calculate cumulative frequencies along a certain axis. Returns ------- new_hist: Histogram of the same type & size """ # TODO: Merge with Histogram1D.cumulative_frequencies # TODO: Deal with errors a...
Calculate cumulative frequencies along a certain axis. Returns ------- new_hist: Histogram of the same type & size
def move(self, x, y): """Move the virtual cursor. Args: x (int): x-coordinate to place the cursor. y (int): y-coordinate to place the cursor. .. seealso:: :any:`get_cursor`, :any:`print_str`, :any:`write` """ self._cursor = self._normalizePoint(x, y)
Move the virtual cursor. Args: x (int): x-coordinate to place the cursor. y (int): y-coordinate to place the cursor. .. seealso:: :any:`get_cursor`, :any:`print_str`, :any:`write`
def setDefaults(configObj={}): """ Return a dictionary of the default parameters which also been updated with the user overrides. """ paramDict = { 'gain': 7, # Detector gain, e-/ADU 'grow': 1, # Radius around CR pixel to mask [default=1 for ...
Return a dictionary of the default parameters which also been updated with the user overrides.
def as_doc(self): """Get the SON document representation of this DBRef. Generally not needed by application developers """ doc = SON([("$ref", self.collection), ("$id", self.id)]) if self.database is not None: doc["$db"] = self.database doc...
Get the SON document representation of this DBRef. Generally not needed by application developers
def get_subpackages(name): """Return subpackages of package *name*""" splist = [] for dirpath, _dirnames, _filenames in os.walk(name): if osp.isfile(osp.join(dirpath, '__init__.py')): splist.append(".".join(dirpath.split(os.sep))) return splist
Return subpackages of package *name*
def merge_user_commits(cls, commits): """Merge all the commits for the user. Aggregate line counts, and use the most recent commit (by date/time) as the representative commit for the user. """ user = None for commit in commits: if not user: us...
Merge all the commits for the user. Aggregate line counts, and use the most recent commit (by date/time) as the representative commit for the user.
def imsave(filename, data, maxval=None, pam=False): """Write image data to Netpbm file. Examples -------- >>> image = numpy.array([[0, 1],[65534, 65535]], dtype=numpy.uint16) >>> imsave('_tmp.pgm', image) """ try: netpbm = NetpbmFile(data, maxval=maxval) netpbm.write(filena...
Write image data to Netpbm file. Examples -------- >>> image = numpy.array([[0, 1],[65534, 65535]], dtype=numpy.uint16) >>> imsave('_tmp.pgm', image)
def _extract_proxies(self, ajax_endpoint): ''' request the xml object ''' proxy_xml = requests.get(ajax_endpoint) print(proxy_xml.content) root = etree.XML(proxy_xml.content) quote = root.xpath('quote')[0] ''' extract the raw text from the body of the quote ...
request the xml object
def _zforce(self,R,z,phi=0.,t=0.): """ NAME: _zforce PURPOSE: evaluate the vertical force for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: ...
NAME: _zforce PURPOSE: evaluate the vertical force for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: the vertical force HISTORY: ...
def unpack(self, obs): """Return a correctly shaped numpy array for this feature.""" planes = getattr(obs.feature_layer_data, self.layer_set) plane = getattr(planes, self.name) return self.unpack_layer(plane)
Return a correctly shaped numpy array for this feature.
def customize(self, customize): """ Special handling for opcodes, such as those that take a variable number of arguments -- we add a new entry for each in TABLE_R. """ for k, v in list(customize.items()): if k in TABLE_R: continue op = k[ :...
Special handling for opcodes, such as those that take a variable number of arguments -- we add a new entry for each in TABLE_R.
def is_(self, value): """ Sets the operator type to Query.Op.Is and sets the value to the inputted value. :param value <variant> :return <Query> :sa __eq__ :usage |>>> from orb import Query as Q ...
Sets the operator type to Query.Op.Is and sets the value to the inputted value. :param value <variant> :return <Query> :sa __eq__ :usage |>>> from orb import Query as Q |>>> query = Q('test').is_(...
def _read(self, ti, try_number, metadata=None): """ Read logs of given task instance and try_number from Wasb remote storage. If failed, read the log from task instance host machine. :param ti: task instance object :param try_number: task instance try_number to read logs from ...
Read logs of given task instance and try_number from Wasb remote storage. If failed, read the log from task instance host machine. :param ti: task instance object :param try_number: task instance try_number to read logs from :param metadata: log metadata, can be ...
def rpc_get_account_balance(self, address, token_type, **con_info): """ Get the balance of an address for a particular token type Returns the value on success Returns 0 if the balance is 0, or if there is no address """ if not check_account_address(address): r...
Get the balance of an address for a particular token type Returns the value on success Returns 0 if the balance is 0, or if there is no address
def handle_friday(next_date: Datum, period: str, mult: int, start_date: Datum): """ Extracted the calculation for when the next_day is Friday """ assert isinstance(next_date, Datum) assert isinstance(start_date, Datum) # Starting from line 220. tmp_sat = next_date.clone() tmp_sat.add_days(1) ...
Extracted the calculation for when the next_day is Friday
def get_existing_pipelines(self): """Get existing pipeline configs for specific application. Returns: str: Pipeline config json """ url = "{0}/applications/{1}/pipelineConfigs".format(API_URL, self.app_name) resp = requests.get(url, verify=GATE_CA_BUNDLE, cert=GATE_...
Get existing pipeline configs for specific application. Returns: str: Pipeline config json
def accel_next(self, *args): """Callback to go to the next tab. Called by the accel key. """ if self.get_notebook().get_current_page() + 1 == self.get_notebook().get_n_pages(): self.get_notebook().set_current_page(0) else: self.get_notebook().next_page() r...
Callback to go to the next tab. Called by the accel key.
def _installed_packages(self) -> Generator[str, None, None]: """Extract installed packages as list from `package.json`.""" with (self._build_dir / 'package.json').open('r') as f: packages = json.load(f) yield from packages['dependencies'].keys()
Extract installed packages as list from `package.json`.
def handle(dispatcher, *accept_args, **accept_kwargs): """ :param dispatcher: dispatcher to recieve events from :param accept_args: args to match on :param accept_kwargs: kwargs to match on Creates an MNDFunction instance which containing the argspec and adds the function to the dispatcher. ...
:param dispatcher: dispatcher to recieve events from :param accept_args: args to match on :param accept_kwargs: kwargs to match on Creates an MNDFunction instance which containing the argspec and adds the function to the dispatcher.
def main(): """ Parses the command-line args, and calls run. """ parser = argparse.ArgumentParser( description='A pipeline that generates analysis pipelines.') parser.add_argument('input', nargs='?', help='A valid metapipe configuration file.') parser.add_argument('-o', '--out...
Parses the command-line args, and calls run.
def _pack_image(filename, max_size, form_field='image', f=None): """Pack image from file into multipart-formdata post body""" # image must be less than 700kb in size if f is None: try: if os.path.getsize(filename) > (max_size * 1024): raise TweepEr...
Pack image from file into multipart-formdata post body
def do_global_lock(self, args): '''read (or clear) the global lock''' if args.purge: self.task_master.registry.force_clear_lock() else: owner = self.task_master.registry.read_lock() if owner: heartbeat = self.task_master.get_heartbeat(owner) ...
read (or clear) the global lock
def daterange(start, stop, step=1, inclusive=False): """In the spirit of :func:`range` and :func:`xrange`, the `daterange` generator that yields a sequence of :class:`~datetime.date` objects, starting at *start*, incrementing by *step*, until *stop* is reached. When *inclusive* is True, the final d...
In the spirit of :func:`range` and :func:`xrange`, the `daterange` generator that yields a sequence of :class:`~datetime.date` objects, starting at *start*, incrementing by *step*, until *stop* is reached. When *inclusive* is True, the final date may be *stop*, **if** *step* falls evenly on it. By ...
def get_consistent_set_and_saxis(magmoms, saxis=None): """ Method to ensure a list of magmoms use the same spin axis. Returns a tuple of a list of Magmoms and their global spin axis. :param magmoms: list of magmoms (Magmoms, scalars or vectors) :param saxis: can provide a specif...
Method to ensure a list of magmoms use the same spin axis. Returns a tuple of a list of Magmoms and their global spin axis. :param magmoms: list of magmoms (Magmoms, scalars or vectors) :param saxis: can provide a specific global spin axis :return: (list of Magmoms, global spin axis) tu...
def html(self) -> str: """Get whole html representation of this node.""" if self._inner_element: return self.start_tag + self._inner_element.html + self.end_tag return super().html
Get whole html representation of this node.
def to_dict(self): """ Return dict representation of public key to embed in DID document. """ return { 'id': self.id, 'type': str(self.type.ver_type), 'controller': canon_ref(self.did, self.controller), **self.type.specification(self.value...
Return dict representation of public key to embed in DID document.
def host_diskpool_get_info(self, disk_pool=None): """ Retrieve diskpool information. :param str disk_pool: the disk pool info. It use ':' to separate disk pool type and pool name, eg "ECKD:eckdpool" or "FBA:fbapool" :returns: Dictionary describing disk pool usage info """ ...
Retrieve diskpool information. :param str disk_pool: the disk pool info. It use ':' to separate disk pool type and pool name, eg "ECKD:eckdpool" or "FBA:fbapool" :returns: Dictionary describing disk pool usage info
def sync_counts(**kwargs): """ Iterates over registered recipes and denormalizes ``Badge.users.count()`` into ``Badge.users_count`` field. """ badges = kwargs.get('badges') excluded = kwargs.get('exclude_badges') instances = registry.get_recipe_instances(badges=badges, excluded=excluded) ...
Iterates over registered recipes and denormalizes ``Badge.users.count()`` into ``Badge.users_count`` field.
def discover(): """ Automatically discover the paths to various data folders in this project and compose a Project instance. Returns: A constructed Project object. Raises: ValueError: if the paths could not be figured out automatically. I...
Automatically discover the paths to various data folders in this project and compose a Project instance. Returns: A constructed Project object. Raises: ValueError: if the paths could not be figured out automatically. In this case, you have to create a Pr...
def cropcenter(sz, img=None): """ if no img, then return crop function :param sz: :param img: :return: """ l = len(sz) sz = np.array(sz) def wrapped(im): imsz = np.array(im.shape) s = (imsz[:l] - sz) / 2 # start index to = s + sz # end index # img[...
if no img, then return crop function :param sz: :param img: :return:
def add_bool_option(self, *args, **kwargs): """ Add a boolean option. @keyword help: Option description. """ dest = [o for o in args if o.startswith("--")][0].replace("--", "").replace("-", "_") self.parser.add_option(dest=dest, action="store_true", default=False, ...
Add a boolean option. @keyword help: Option description.
def parse_setup(options: Union[List, str]) -> str: """Convert potentially a list of commands into a single string. This creates a single string with newlines between each element of the list so that they will all run after each other in a bash script. """ if isinstance(options, str): retur...
Convert potentially a list of commands into a single string. This creates a single string with newlines between each element of the list so that they will all run after each other in a bash script.
def remove_readonly(func, path, _): "Clear the readonly bit and reattempt the removal" os.chmod(path, stat.S_IWRITE) func(path)
Clear the readonly bit and reattempt the removal
def token_at_cursor(code, pos=0): """ Find the token present at the passed position in the code buffer :return (tuple): a pair (token, start_position) """ l = len(code) end = start = pos # Go forwards while we get alphanumeric chars while end < l and code[end].isalpha(): end += ...
Find the token present at the passed position in the code buffer :return (tuple): a pair (token, start_position)
def image_data(image): """Get components and bytes for an image""" # NOTE: We might want to check the actual image.mode # and convert to an acceptable format. # At the moment we load the data as is. data = image.tobytes() components = len(data) // (image.size[0] * image.size[1]...
Get components and bytes for an image
def alleles_to_retrieve(df): """Alleles to retrieve from genome fasta Get a dict of the genome fasta contig title to a list of blastn results of the allele sequences that must be retrieved from the genome contig. Args: df (pandas.DataFrame): blastn results dataframe Returns: {str:...
Alleles to retrieve from genome fasta Get a dict of the genome fasta contig title to a list of blastn results of the allele sequences that must be retrieved from the genome contig. Args: df (pandas.DataFrame): blastn results dataframe Returns: {str:[pandas.Series]}: dict of contig tit...
def _parse(self, fname): """Parse a processed.top GROMACS topology file The function reads in the file line-by-line, and it's a bunch of 'elif' statements, writing parameter/atom line to current section/molecule. ParamTypes are added to self.xyztypes (AtomType goes to self.atomtypes). ...
Parse a processed.top GROMACS topology file The function reads in the file line-by-line, and it's a bunch of 'elif' statements, writing parameter/atom line to current section/molecule. ParamTypes are added to self.xyztypes (AtomType goes to self.atomtypes). Params are added to current ...
def generate_default_filename(infile_path, is_cropped_file=True): """Generate the name of the default output file from the name of the input file. The is_cropped_file boolean is used to indicate that the file has been (or will be) cropped, to determine which filename-modification string to use. Functi...
Generate the name of the default output file from the name of the input file. The is_cropped_file boolean is used to indicate that the file has been (or will be) cropped, to determine which filename-modification string to use. Function assumes that args has been set globally by argparse.
def search_rule_by_id(self, ruleID) -> Rule: """ searches a rule by given id Args: ruleID(str): the rule to search for Returns the rule object or None if it couldn't find a rule """ for r in self.rules: if r.id == ruleID...
searches a rule by given id Args: ruleID(str): the rule to search for Returns the rule object or None if it couldn't find a rule
def io_priority(self): """ IO priority for this instance. """ return ( self._iocb.aio_reqprio if self._iocb.u.c.flags & libaio.IOCB_FLAG_IOPRIO else None )
IO priority for this instance.
def get_built_image_info(self): """ query docker about built image :return dict """ logger.info("getting information about built image '%s'", self.image) image_info = self.tasker.get_image_info_by_image_name(self.image) items_count = len(image_info) if it...
query docker about built image :return dict
def _generic_convert_string(v, from_type, to_type, encoding): """ Generic method to convert any argument type (string type, list, set, tuple, dict) to an equivalent, with string values converted to given 'to_type' (str or unicode). This method must be used with Python 2 interpreter only. :param v: ...
Generic method to convert any argument type (string type, list, set, tuple, dict) to an equivalent, with string values converted to given 'to_type' (str or unicode). This method must be used with Python 2 interpreter only. :param v: The value to convert :param from_type: The original string type to con...
def generic_modis5kmto1km(*data5km): """Getting 1km data for modis from 5km tiepoints. """ cols5km = np.arange(2, 1354, 5) cols1km = np.arange(1354) lines = data5km[0].shape[0] * 5 rows5km = np.arange(2, lines, 5) rows1km = np.arange(lines) along_track_order = 1 cross_track_order = ...
Getting 1km data for modis from 5km tiepoints.
def draw_strip_text(self, text_lines, location, pid): """ Create a background patch and put a label on it """ ax = self.axs[pid] themeable = self.figure._themeable dim = self.strip_dimensions(text_lines, location, pid) if location == 'right': rotation...
Create a background patch and put a label on it
def get_next_character(self): """ Returns the character after the cursor. :return: Next cursor character. :rtype: QString """ cursor = self.textCursor() cursor.movePosition(QTextCursor.NextCharacter, QTextCursor.KeepAnchor) return cursor.selectedText()
Returns the character after the cursor. :return: Next cursor character. :rtype: QString
def get_job_details(self, job_id): """ Gets all details for existing job :param job_id: job_id as returned by 'create_operation_job(...)' :return: job info as xml """ response = requests.get(self._get_job_details_url(job_id)) response.raise_for_status() ...
Gets all details for existing job :param job_id: job_id as returned by 'create_operation_job(...)' :return: job info as xml
def _temp_exists(method, ip): ''' Checks if the ip exists as a temporary rule based on the method supplied, (tempallow, tempdeny). ''' _type = method.replace('temp', '').upper() cmd = "csf -t | awk -v code=1 -v type=_type -v ip=ip '$1==type && $2==ip {{code=0}} END {{exit code}}'".format(_type=_...
Checks if the ip exists as a temporary rule based on the method supplied, (tempallow, tempdeny).
def install_setuptools(python_cmd='python', use_sudo=True): """ Install the latest version of `setuptools`_. :: import burlap burlap.python_setuptools.install_setuptools() """ setuptools_version = package_version('setuptools', python_cmd) distribute_version = package_version...
Install the latest version of `setuptools`_. :: import burlap burlap.python_setuptools.install_setuptools()
def _check_for_slash_endings(self, readnames): ''' Provide a list of read names to be checked for the /1 or /2 endings which cause troubles downstream when working with paired reads. This function checks the list for ANY read ending in /1 or /2. The reads are first stripped of an...
Provide a list of read names to be checked for the /1 or /2 endings which cause troubles downstream when working with paired reads. This function checks the list for ANY read ending in /1 or /2. The reads are first stripped of any comment lines, using the 'split' function Parameters ...
def routes(self): """ Retrieves the main routes of the DTS Collection Response format expected : { "@context": "/dts/api/contexts/EntryPoint.jsonld", "@id": "/dts/api/", "@type": "EntryPoint", "collections": "/dts/api/collections/", ...
Retrieves the main routes of the DTS Collection Response format expected : { "@context": "/dts/api/contexts/EntryPoint.jsonld", "@id": "/dts/api/", "@type": "EntryPoint", "collections": "/dts/api/collections/", "documents": "/dts...
async def import_image(self, data, stream: bool = False): """ Import tarball of image to docker. Args: data: tarball data of image to be imported Returns: Tarball of the image """ headers = {"Content-Type": "application/x-tar"} response =...
Import tarball of image to docker. Args: data: tarball data of image to be imported Returns: Tarball of the image
def update_cache_for_instance( model_name, instance_pk, instance=None, version=None): """Update the cache for an instance, with cascading updates.""" cache = SampleCache() invalid = cache.update_instance(model_name, instance_pk, instance, version) for invalid_name, invalid_pk, invalid_version in...
Update the cache for an instance, with cascading updates.
def find_lc_timegroups(lctimes, mingap=4.0): '''This finds the time gaps in the light curve, so we can figure out which times are for consecutive observations and which represent gaps between seasons. Parameters ---------- lctimes : np.array This is the input array of times, assumed to...
This finds the time gaps in the light curve, so we can figure out which times are for consecutive observations and which represent gaps between seasons. Parameters ---------- lctimes : np.array This is the input array of times, assumed to be in some form of JD. mingap : float ...
def update_opdocs(self, checksum, opdocs, revision=None): """ Modifies the internal state based a change to the content and returns the sets of words added and removed. :Parameters: checksum : `hashable` A checksum generated from the text of a revision ...
Modifies the internal state based a change to the content and returns the sets of words added and removed. :Parameters: checksum : `hashable` A checksum generated from the text of a revision opdocs : `iterable` ( `dict` ) A sequence of operations ...
def transform_sequence(f): """ A decorator to take a function operating on a point and turn it into a function returning a callable operating on a sequence. The functions passed to this decorator must define a kwarg called "point", or have point be the last positional argument """ @wraps(f) ...
A decorator to take a function operating on a point and turn it into a function returning a callable operating on a sequence. The functions passed to this decorator must define a kwarg called "point", or have point be the last positional argument
def to_literal(self): """ Convert the node into a literal Python object """ if not self.nodes: return (self.tag, self.attrib, self.text, []) else: return (self.tag, self.attrib, self.text, list(map(to_literal, self.nodes)))
Convert the node into a literal Python object
def spt(points, max_dist_error, max_speed_error): """ A combination of both `td_sp` and `td_tr` Detailed in, Spatiotemporal Compression Techniques for Moving Point Objects, Nirvana Meratnia and Rolf A. de By, 2004, in Advances in Database Technology - EDBT 2004: 9th Internationa...
A combination of both `td_sp` and `td_tr` Detailed in, Spatiotemporal Compression Techniques for Moving Point Objects, Nirvana Meratnia and Rolf A. de By, 2004, in Advances in Database Technology - EDBT 2004: 9th International Conference on Extending Database Technology, Her...
def create_committee_member(self, url="", account=None, **kwargs): """ Create a committee member :param str url: URL to read more about the worker :param str account: (optional) the account to allow access to (defaults to ``default_account``) """ if not a...
Create a committee member :param str url: URL to read more about the worker :param str account: (optional) the account to allow access to (defaults to ``default_account``)
def merge(arg, *rest, **kwargs): """Merge a collection, with functions as items, into a single function that takes a collection and maps its items through corresponding functions. :param arg: A collection of functions, such as list, tuple, or dictionary :param default: Optional default function to use ...
Merge a collection, with functions as items, into a single function that takes a collection and maps its items through corresponding functions. :param arg: A collection of functions, such as list, tuple, or dictionary :param default: Optional default function to use for items within mer...
def create_config(): """Initiates process to generate configuration file.""" file_exists = exists(CONFIG_FILE) if not file_exists: # Set directories config.add_section('Directories') defaults = [ ('AbstractRetrieval', expanduser('~/.scopus/abstract_retrieval')), ...
Initiates process to generate configuration file.
def get_info(self, code): """Return a dict of information about the currency""" currency = self.get_currency(code) info = {} users = list(filter(None, currency['users'].split(','))) if users: info['Users'] = users alt = list(filter(None, currency['alternativ...
Return a dict of information about the currency
def wait_event(self, filter: Callable[[T_Event], bool] = None) -> Awaitable[T_Event]: """Shortcut for calling :func:`wait_event` with this signal in the first argument.""" return wait_event([self], filter)
Shortcut for calling :func:`wait_event` with this signal in the first argument.
def new_dataset(data, identifier=None): """Initialize a new RT-DC dataset Parameters ---------- data: can be one of the following: - dict - .tdms file - .rtdc file - subclass of `RTDCBase` (will create a hierarchy child) identifier: str A u...
Initialize a new RT-DC dataset Parameters ---------- data: can be one of the following: - dict - .tdms file - .rtdc file - subclass of `RTDCBase` (will create a hierarchy child) identifier: str A unique identifier for this dataset. If set to `N...
def _maybe_host_form_to_py_ast( _: GeneratorContext, node: MaybeHostForm ) -> GeneratedPyAST: """Generate a Python AST node for accessing a potential Python module variable name with a namespace.""" assert node.op == NodeOp.MAYBE_HOST_FORM return GeneratedPyAST( node=_load_attr( ...
Generate a Python AST node for accessing a potential Python module variable name with a namespace.
def pad_matrix(self, matrix, pad_value=0): """ Pad a possibly non-square matrix to make it square. :Parameters: matrix : list of lists matrix to pad pad_value : int value to use to pad the matrix :rtype: list of lists :re...
Pad a possibly non-square matrix to make it square. :Parameters: matrix : list of lists matrix to pad pad_value : int value to use to pad the matrix :rtype: list of lists :return: a new, possibly padded, matrix
def find_key(self, regex): """Attempts to find a single S3 key based on the passed regex Given a regular expression, this method searches the S3 bucket for a matching key, and returns it if exactly 1 key matches. Otherwise, None is returned. :param regex: (str) Regular expressi...
Attempts to find a single S3 key based on the passed regex Given a regular expression, this method searches the S3 bucket for a matching key, and returns it if exactly 1 key matches. Otherwise, None is returned. :param regex: (str) Regular expression for an S3 key :return: (str...
def label_sectors( *, labels=["I", "II", "IV", "VI", "V", "III"], ax=None, lw=2, lc="k", cs=None, c_zlevel=2, c_alpha=0.5, fontsize=40 ): """Label the six time-orderings in a three-pulse experiment. Parameters ---------- labels : list of strings Labels to pla...
Label the six time-orderings in a three-pulse experiment. Parameters ---------- labels : list of strings Labels to place within sectors, starting in the upper left and proceeding clockwise. Default is ['I', 'II', 'IV', 'VI', 'V', 'III']. ax : matplotlib axis object (optional) Ax...
def derive_source_offset(self, offset, is_end=False): """ Given a post-preprocessed coordinate, derives the corresponding coordinate in the original source file. Returns result in the following tuple: (src_offset, src_path, include_ref) where: - src_offse...
Given a post-preprocessed coordinate, derives the corresponding coordinate in the original source file. Returns result in the following tuple: (src_offset, src_path, include_ref) where: - src_offset is the translated coordinate If the input offset lands o...
def start(self): """Start the channel""" # observers for this channel only need to wait for one value self._observer_params.update(dict(once=True)) super(CurrentResourceValue, self).start() self._api.ensure_notifications_thread() self._api._mds_rpc_post( devic...
Start the channel
def get_line_number(line_map, offset): """Find a line number, given a line map and a character offset.""" for lineno, line_offset in enumerate(line_map, start=1): if line_offset > offset: return lineno return -1
Find a line number, given a line map and a character offset.
def delete_interconnect(self, enclosure_uri, bay, timeout=-1): """ Deletes an interconnect from a location. Warning: This won't delete the LOGICAL INTERCONNECT itself and might cause inconsistency between the enclosure and Logical Interconnect Group. Args: ...
Deletes an interconnect from a location. Warning: This won't delete the LOGICAL INTERCONNECT itself and might cause inconsistency between the enclosure and Logical Interconnect Group. Args: enclosure_uri: URI of the Enclosure bay: Bay timeout...
def revise(self, data, ignore_none=True): """ Revise attributes value with dictionary data. :type data: dict :type ignore_none: bool **中文文档** 将一个字典中的数据更新到本条文档。当且仅当数据值不为None时。 """ if not isinstance(data, dict): raise TypeError("`data` has to ...
Revise attributes value with dictionary data. :type data: dict :type ignore_none: bool **中文文档** 将一个字典中的数据更新到本条文档。当且仅当数据值不为None时。
def _trim_and_decode(ids, subtokenizer): """Trim EOS and PAD tokens from ids, and decode to return a string.""" try: index = list(ids).index(tokenizer.EOS_ID) return subtokenizer.decode(ids[:index]) except ValueError: # No EOS found in sequence return subtokenizer.decode(ids)
Trim EOS and PAD tokens from ids, and decode to return a string.
def _write_images(self, name:str, images:[Tensor])->None: "Writes list of images as tensors to Tensorboard." tag = self.ds_type.name + ' ' + name self.tbwriter.add_image(tag=tag, img_tensor=vutils.make_grid(images, normalize=True), global_step=self.iteration)
Writes list of images as tensors to Tensorboard.
def mask_file(regionfile, infile, outfile, negate=False): """ Created a masked version of file, using a region. Parameters ---------- regionfile : str A file which can be loaded as a :class:`AegeanTools.regions.Region`. The image will be masked according to this region. infile...
Created a masked version of file, using a region. Parameters ---------- regionfile : str A file which can be loaded as a :class:`AegeanTools.regions.Region`. The image will be masked according to this region. infile : str Input FITS image. outfile : str Output FIT...
def get_trade_histories(self, symbol): """List the latest trades for a symbol https://docs.kucoin.com/#get-trade-histories :param symbol: Name of symbol e.g. KCS-BTC :type symbol: string .. code:: python orders = client.get_trade_histories('KCS-BTC') :ret...
List the latest trades for a symbol https://docs.kucoin.com/#get-trade-histories :param symbol: Name of symbol e.g. KCS-BTC :type symbol: string .. code:: python orders = client.get_trade_histories('KCS-BTC') :returns: ApiResponse .. code:: python ...
def _get_x_axis(self): """See http://www.gdal.org/gdal_datamodel.html for details.""" # 0,0 is top/left top top/left pixel. Actual x/y coord of that pixel are (.5,.5). x_centers = np.linspace(.5, self.x_size - .5, self.x_size) y_centers = x_centers * 0 return (self.geotransform[0...
See http://www.gdal.org/gdal_datamodel.html for details.
def close(self): """Send CLOSE command to device.""" close_command = StandardSend(self._address, COMMAND_LIGHT_OFF_0X13_0X00) self._send_method(close_command, self._close_message_received)
Send CLOSE command to device.
def params(dirnames, param_func, t_steady=None): """Calculate a parameter of a set of model output directories, for a measure function which returns an associated uncertainty. Parameters ---------- dirnames: list[str] Model output directory paths. param_func: function Function w...
Calculate a parameter of a set of model output directories, for a measure function which returns an associated uncertainty. Parameters ---------- dirnames: list[str] Model output directory paths. param_func: function Function which takes a :class:`Model` instance as a single argumen...
def clean(self): ''' priorDays is required for Generic Repeated Expenses to avoid infinite loops ''' if not self.priorDays and not self.startDate: raise ValidationError(_( 'Either a start date or an "up to __ days in the past" limit is required ' + 'for repeat...
priorDays is required for Generic Repeated Expenses to avoid infinite loops
def _coerce_type(self, field_type, value): """Returns unicode(value) after trying to coerce it into the Solr field type. @param field_type(string) The Solr field type for the value @param value(any) The value that is to be represented as Unicode text. """ if value is None: ...
Returns unicode(value) after trying to coerce it into the Solr field type. @param field_type(string) The Solr field type for the value @param value(any) The value that is to be represented as Unicode text.
def run(self, gin): """ Run GULP using the gin as input Args: gin: GULP input string Returns: gout: GULP output string """ with ScratchDir("."): p = subprocess.Popen( self._gulp_cmd, stdout=subprocess.PIPE, ...
Run GULP using the gin as input Args: gin: GULP input string Returns: gout: GULP output string
def _convolve_spatial2(im, hs, mode = "constant", grid_dim = None, pad_factor = 2, plan = None, return_plan = False): """ spatial varying convolution of an 2d image with a 2d grid of psfs shape(im_...
spatial varying convolution of an 2d image with a 2d grid of psfs shape(im_ = (Ny,Nx) shape(hs) = (Gy,Gx, Hy,Hx) the input image im is subdivided into (Gy,Gx) blocks hs[j,i] is the psf at the center of each block (i,j) as of now each image dimension has to be divisible by the grid dim, i.e. N...
def dedent(text): """Equivalent of textwrap.dedent that ignores unindented first line. This means it will still dedent strings like: '''foo is a bar ''' For use in wrap_paragraphs. """ if text.startswith('\n'): # text starts with blank line, don't ignore the first line ...
Equivalent of textwrap.dedent that ignores unindented first line. This means it will still dedent strings like: '''foo is a bar ''' For use in wrap_paragraphs.
def loadmask(self, filename: str) -> np.ndarray: """Load a mask file.""" mask = scipy.io.loadmat(self.find_file(filename, what='mask')) maskkey = [k for k in mask.keys() if not (k.startswith('_') or k.endswith('_'))][0] return mask[maskkey].astype(np.bool)
Load a mask file.
def texto_decimal(valor, remover_zeros=True): """Converte um valor :py:class:`decimal.Decimal` para texto, com a opção de remover os zeros à direita não significativos. A conversão para texto irá considerar o :py:module:`locale` para converter o texto pronto para apresentação. :param decimal.Decima...
Converte um valor :py:class:`decimal.Decimal` para texto, com a opção de remover os zeros à direita não significativos. A conversão para texto irá considerar o :py:module:`locale` para converter o texto pronto para apresentação. :param decimal.Decimal valor: Valor a converter para texto. :param boo...
def __init_from_list_np2d(self, mats, params_str, ref_dataset): """Initialize data from a list of 2-D numpy matrices.""" ncol = mats[0].shape[1] nrow = np.zeros((len(mats),), np.int32) if mats[0].dtype == np.float64: ptr_data = (ctypes.POINTER(ctypes.c_double) * len(mats))() ...
Initialize data from a list of 2-D numpy matrices.
def write_multiple_registers(slave_id, starting_address, values): """ Return ADU for Modbus function code 16: Write Multiple Registers. :param slave_id: Number of slave. :return: Byte array with ADU. """ function = WriteMultipleRegisters() function.starting_address = starting_address functi...
Return ADU for Modbus function code 16: Write Multiple Registers. :param slave_id: Number of slave. :return: Byte array with ADU.
def scale(self, selections, factor): '''Scale the objects represented by *selections* up to a certain *factor*. ''' if 'atoms' in selections: atms = selections['atoms'].mask if factor is None: self.scale_factors[atms] = 1.0 else: ...
Scale the objects represented by *selections* up to a certain *factor*.
def get_min_distance(self, mesh): """ For each point in ``mesh`` compute the minimum distance to each surface element and return the smallest value. See :meth:`superclass method <.base.BaseSurface.get_min_distance>` for spec of input and result values. """ ...
For each point in ``mesh`` compute the minimum distance to each surface element and return the smallest value. See :meth:`superclass method <.base.BaseSurface.get_min_distance>` for spec of input and result values.
def is_dxlink(x): ''' :param x: A potential DNAnexus link Returns whether *x* appears to be a DNAnexus link (is a dict with key ``"$dnanexus_link"``) with a referenced data object. ''' if not isinstance(x, dict): return False if '$dnanexus_link' not in x: return False li...
:param x: A potential DNAnexus link Returns whether *x* appears to be a DNAnexus link (is a dict with key ``"$dnanexus_link"``) with a referenced data object.
def share(self, project, to_user, force_send, auth_role, user_message): """ Send mail and give user specified access to the project. :param project: RemoteProject project to share :param to_user: RemoteUser user to receive email/access :param auth_role: str project role eg 'proje...
Send mail and give user specified access to the project. :param project: RemoteProject project to share :param to_user: RemoteUser user to receive email/access :param auth_role: str project role eg 'project_admin' to give to the user :param user_message: str message to be sent with the s...
def get_queryset(self): # pylint: disable=method-hidden """Return queryset.""" if self.request and self.request.query_params.get('hydrate_data', False): return self.queryset.prefetch_related('data__entity_set') return self.queryset
Return queryset.
def repmd(instr, marker, value, sigdig): """ Replace a marker with a double precision number. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/repmd_c.html :param instr: Input string. :type instr: str :param marker: Marker to be replaced. :type marker: str :param value: Replacem...
Replace a marker with a double precision number. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/repmd_c.html :param instr: Input string. :type instr: str :param marker: Marker to be replaced. :type marker: str :param value: Replacement value. :type value: float :param sigdig: ...
def run(self): """Parse the script file. :rtype: :py:class:`~turberfield.dialogue.model.Model` """ model = Model(self.fP, self.doc) self.doc.walkabout(model) return model
Parse the script file. :rtype: :py:class:`~turberfield.dialogue.model.Model`
def lsdirs(root=".", **kwargs): """ Return only subdirectories from a directory listing. Arguments: root (str): Path to directory. Can be relative or absolute. **kwargs: Any additional arguments to be passed to ls(). Returns: list of str: A list of directory paths. Raise...
Return only subdirectories from a directory listing. Arguments: root (str): Path to directory. Can be relative or absolute. **kwargs: Any additional arguments to be passed to ls(). Returns: list of str: A list of directory paths. Raises: OSError: If root directory does ...
def delete_password(self, service, username): """Delete the password for the username of the service. """ if not self.connected(service): # the user pressed "cancel" when prompted to unlock their keyring. raise PasswordDeleteError("Cancelled by user") if not self....
Delete the password for the username of the service.