code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def getDigestableArgs(Argv): r"""Splits the given Argv into *Args and **KwArgs. """ first_kwarg_pos = 0 for arg in Argv: if KWARG_VALIDATOR.search(arg): break else: first_kwarg_pos += 1 for arg in Argv[first_kwarg_pos:]: # ensure that the kwargs are valid if not KWARG_VALIDATOR.sear...
r"""Splits the given Argv into *Args and **KwArgs.
def calc_q1_lz_v1(self): """Calculate the slow response of the lower zone layer. Required control parameters: |K4| |Gamma| Calculated fluxes sequence: |Q1| Updated state sequence: |LZ| Basic equations: :math:`\\frac{dLZ}{dt} = -Q1` \n :math:`Q1 = \...
Calculate the slow response of the lower zone layer. Required control parameters: |K4| |Gamma| Calculated fluxes sequence: |Q1| Updated state sequence: |LZ| Basic equations: :math:`\\frac{dLZ}{dt} = -Q1` \n :math:`Q1 = \\Bigl \\lbrace { ...
def check_ordered(self): """ True if each chromosome is listed together as a chunk and if the range starts go from smallest to largest otherwise false :return: is it ordered? :rtype: bool """ sys.stderr.write("error unimplemented check_ordered\n") sys.exit() seen_chrs = set() curr_chr ...
True if each chromosome is listed together as a chunk and if the range starts go from smallest to largest otherwise false :return: is it ordered? :rtype: bool
def poll(self, timeout=-1, maxevents=-1): """ Poll for events :param timeout: The amount of seconds to wait for events before giving up. The default value, -1, represents infinity. Note that unlike the underlying ``epoll_wait()`` timeout is a fractional numbe...
Poll for events :param timeout: The amount of seconds to wait for events before giving up. The default value, -1, represents infinity. Note that unlike the underlying ``epoll_wait()`` timeout is a fractional number representing **seconds**. :param maxeven...
def find_first(self, attr_name, resources, extra_prefix=''): """ Returns the boto object for the first resource in ``resources`` that belongs to this stack. Uses the attribute specified by ``attr_name`` to match the stack name. E.g. An RDS instance for a stack named ``foo`` mi...
Returns the boto object for the first resource in ``resources`` that belongs to this stack. Uses the attribute specified by ``attr_name`` to match the stack name. E.g. An RDS instance for a stack named ``foo`` might be named ``foo-mydb-fis8932ifs``. This call:: find_firs...
def geocode_addresses(self, project_id, dataset_id, address_field, geometry_field, **extra_params): """ Geocode addresses in a dataset. The dataset must have a string field with the addresses to geocode and a geometry field (points) for the geocoding results. ...
Geocode addresses in a dataset. The dataset must have a string field with the addresses to geocode and a geometry field (points) for the geocoding results. :param project_id: Must be a string. :param dataset_id: Must be a string. :param address_field: Name of the address field in...
def result_sort(result_list, start_index=0): """Sorts a list of results in O(n) in place (since every run is unique) :param result_list: List of tuples [(run_idx, res), ...] :param start_index: Index with which to start, every entry before `start_index` is ignored """ if len(result_list) < 2: ...
Sorts a list of results in O(n) in place (since every run is unique) :param result_list: List of tuples [(run_idx, res), ...] :param start_index: Index with which to start, every entry before `start_index` is ignored
def is_premium(self, media_type): """Get if the session is premium for a given media type @param str media_type Should be one of ANDROID.MEDIA_TYPE_* @return bool """ if self.logged_in: if media_type in self._user_data['premium']: return True ...
Get if the session is premium for a given media type @param str media_type Should be one of ANDROID.MEDIA_TYPE_* @return bool
def int_gps_time_to_str(t): """Takes an integer GPS time, either given as int or lal.LIGOTimeGPS, and converts it to a string. If a LIGOTimeGPS with nonzero decimal part is given, raises a ValueError.""" if isinstance(t, int): return str(t) elif isinstance(t, float): # Wouldn't this...
Takes an integer GPS time, either given as int or lal.LIGOTimeGPS, and converts it to a string. If a LIGOTimeGPS with nonzero decimal part is given, raises a ValueError.
def show(closeToo=False): """alternative to pylab.show() that updates IPython window.""" IPython.display.display(pylab.gcf()) if closeToo: pylab.close('all')
alternative to pylab.show() that updates IPython window.
def _init_map(self): """stub""" MultiChoiceAnswerFormRecord._init_map(self) FilesAnswerFormRecord._init_map(self) FeedbackAnswerFormRecord._init_map(self) super(MultiChoiceFeedbackAndFilesAnswerFormRecord, self)._init_map()
stub
def random_subset_ids_by_count(self, count_per_class=1): """ Returns a random subset of sample ids of specified size by count, within each class. Parameters ---------- count_per_class : int Exact number of samples per each class. Returns ...
Returns a random subset of sample ids of specified size by count, within each class. Parameters ---------- count_per_class : int Exact number of samples per each class. Returns ------- subset : list Combined list of sample ids from al...
def remove(name, **kwargs): ''' Remove system rc configuration variables CLI Example: .. code-block:: bash salt '*' sysrc.remove name=sshd_enable ''' cmd = 'sysrc -v' if 'file' in kwargs: cmd += ' -f '+kwargs['file'] if 'jail' in kwargs: cmd += ' -j '+kwar...
Remove system rc configuration variables CLI Example: .. code-block:: bash salt '*' sysrc.remove name=sshd_enable
def RegisterDefinition(self, data_type_definition): """Registers a data type definition. The data type definitions are identified based on their lower case name. Args: data_type_definition (DataTypeDefinition): data type definitions. Raises: KeyError: if data type definition is already se...
Registers a data type definition. The data type definitions are identified based on their lower case name. Args: data_type_definition (DataTypeDefinition): data type definitions. Raises: KeyError: if data type definition is already set for the corresponding name.
def helper(*commands): """Decorate a function to be the helper function of commands. Arguments: commands: Names of command that should trigger this function object. --------------------------- Interface of helper methods: @helper('some-command') def help_foo(self, args): ...
Decorate a function to be the helper function of commands. Arguments: commands: Names of command that should trigger this function object. --------------------------- Interface of helper methods: @helper('some-command') def help_foo(self, args): ''' Argumen...
def load_and_parse(self): """ Load the metrics file from the given path """ f = open(self.file_path, "r") metrics_json = f.read() self.metrics = json.loads(metrics_json)
Load the metrics file from the given path
def _set_dpod(self, v, load=False): """ Setter method for dpod, mapped from YANG variable /dpod (container) If this variable is read-only (config: false) in the source YANG file, then _set_dpod is considered as a private method. Backends looking to populate this variable should do so via calling...
Setter method for dpod, mapped from YANG variable /dpod (container) If this variable is read-only (config: false) in the source YANG file, then _set_dpod is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_dpod() directly.
def build_clustbits(data, ipyclient, force): """ Reconstitutes clusters from .utemp and htemp files and writes them to chunked files for aligning in muscle. """ ## If you run this step then we clear all tmp .fa and .indel.h5 files if os.path.exists(data.tmpdir): shutil.rmtree(data.tmpdi...
Reconstitutes clusters from .utemp and htemp files and writes them to chunked files for aligning in muscle.
def _compute_ogg_page_crc(page): """ Compute CRC of an Ogg page. """ page_zero_crc = page[:OGG_FIRST_PAGE_HEADER_CRC_OFFSET] + \ b"\00" * OGG_FIRST_PAGE_HEADER_CRC.size + \ page[OGG_FIRST_PAGE_HEADER_CRC_OFFSET + OGG_FIRST_PAGE_HEADER_CRC.size:] return ogg_page_crc(page_zero_crc)
Compute CRC of an Ogg page.
def update(self, capacity=values.unset, available=values.unset): """ Update the WorkerChannelInstance :param unicode capacity: The total number of Tasks worker should handle for this TaskChannel type. :param bool available: Toggle the availability of the WorkerChannel. :returns...
Update the WorkerChannelInstance :param unicode capacity: The total number of Tasks worker should handle for this TaskChannel type. :param bool available: Toggle the availability of the WorkerChannel. :returns: Updated WorkerChannelInstance :rtype: twilio.rest.taskrouter.v1.workspace.w...
def debug_mode(self, toggle): """ Toggle debug mode for more detailed output obj.debug_mode(True) - Turn debug mode on obj.debug_mode(False) - Turn debug mode off """ if toggle: self.log.setLevel(logging.DEBUG) else: self.log.setLevel(l...
Toggle debug mode for more detailed output obj.debug_mode(True) - Turn debug mode on obj.debug_mode(False) - Turn debug mode off
def httperror_handler(error): """Format error responses properly, return the response body. This function can be attached to the Bottle instance as the default_error_handler function. It is also used by the FormatExceptionMiddleware. """ status_code = error.status_code or 500 output = { ...
Format error responses properly, return the response body. This function can be attached to the Bottle instance as the default_error_handler function. It is also used by the FormatExceptionMiddleware.
def shared_options(rq): "Default class options to pass to the CLI commands." return { 'url': rq.redis_url, 'config': None, 'worker_class': rq.worker_class, 'job_class': rq.job_class, 'queue_class': rq.queue_class, 'connection_class': rq.connection_class, }
Default class options to pass to the CLI commands.
def node_radius(self, node): """ Computes the radial position of the node. """ return self.get_idx(node) * self.scale + self.internal_radius
Computes the radial position of the node.
def gradient(self): r"""Gradient of the log of the marginal likelihood. Returns ------- dict Map between variables to their gradient values. """ self._update_approx() g = self._ep.lml_derivatives(self._X) ed = exp(-self.logitdelta) es...
r"""Gradient of the log of the marginal likelihood. Returns ------- dict Map between variables to their gradient values.
def is_mouse_over(self, event): """ Check whether a MouseEvent is over thus scroll bar. :param event: The MouseEvent to check. :returns: True if the mouse event is over the scroll bar. """ return event.x == self._x and self._y <= event.y < self._y + self._height
Check whether a MouseEvent is over thus scroll bar. :param event: The MouseEvent to check. :returns: True if the mouse event is over the scroll bar.
def load_saved_records(self, status, records): """Load ALDB records from a set of saved records.""" if isinstance(status, ALDBStatus): self._status = status else: self._status = ALDBStatus(status) for mem_addr in records: rec = records[mem_addr] ...
Load ALDB records from a set of saved records.
def FromMicroseconds(self, micros): """Converts microseconds since epoch to Timestamp.""" self.seconds = micros // _MICROS_PER_SECOND self.nanos = (micros % _MICROS_PER_SECOND) * _NANOS_PER_MICROSECOND
Converts microseconds since epoch to Timestamp.
def get_details(self, language=None): """Retrieves full information on the place matching the place_id. Further attributes will be made available on the instance once this method has been invoked. keyword arguments: language -- The language code, indicating in which language th...
Retrieves full information on the place matching the place_id. Further attributes will be made available on the instance once this method has been invoked. keyword arguments: language -- The language code, indicating in which language the results should be returned,...
def get_client(self, name): """Like :meth:`.get`, but only mechanisms inheriting :class:`ClientMechanism` will be returned. Args: name: The SASL mechanism name. Returns: The mechanism object or ``None`` """ mech = self.get(name) return m...
Like :meth:`.get`, but only mechanisms inheriting :class:`ClientMechanism` will be returned. Args: name: The SASL mechanism name. Returns: The mechanism object or ``None``
def ICALImporter(ctx, filename, all, owner, calendar, create_calendar, clear_calendar, dry, execfilter): """Calendar Importer for iCal (ics) files """ log('iCal importer running') objectmodels = ctx.obj['db'].objectmodels if objectmodels['user'].count({'name': owner}) > 0: owner_object =...
Calendar Importer for iCal (ics) files
def ystep(self): r"""Minimise Augmented Lagrangian with respect to :math:`\mathbf{y}`.""" self.Y = sp.prox_l1(self.AX + self.U, (self.lmbda / self.rho) * self.wl1) super(ConvBPDN, self).ystep()
r"""Minimise Augmented Lagrangian with respect to :math:`\mathbf{y}`.
def time_to_first_byte(self): """ Time to first byte of the page request in ms """ # The unknown page is just a placeholder for entries with no page ID. # As such, it would not have a TTFB if self.page_id == 'unknown': return None ttfb = 0 for ...
Time to first byte of the page request in ms
def imatch(pattern, name): # type: (Text, Text) -> bool """Test whether a name matches a wildcard pattern (case insensitive). Arguments: pattern (str): A wildcard pattern, e.g. ``"*.py"``. name (bool): A filename. Returns: bool: `True` if the filename matches the pattern. ...
Test whether a name matches a wildcard pattern (case insensitive). Arguments: pattern (str): A wildcard pattern, e.g. ``"*.py"``. name (bool): A filename. Returns: bool: `True` if the filename matches the pattern.
def rgb_to_yiq(rgb): """ Convert an RGB color representation to a YIQ color representation. (r, g, b) :: r -> [0, 255] g -> [0, 255] b -> [0, 255] :param rgb: A tuple of three numeric values corresponding to the red, green, and blue value. :return: YIQ representat...
Convert an RGB color representation to a YIQ color representation. (r, g, b) :: r -> [0, 255] g -> [0, 255] b -> [0, 255] :param rgb: A tuple of three numeric values corresponding to the red, green, and blue value. :return: YIQ representation of the input RGB value. :...
def sspro8_results(self): """Parse the SSpro8 output file and return a dict of secondary structure compositions. """ return ssbio.protein.sequence.utils.fasta.load_fasta_file_as_dict_of_seqs(self.out_sspro8)
Parse the SSpro8 output file and return a dict of secondary structure compositions.
def cookie_get(self, name): """ Check for a cookie value by name. :param str name: Name of the cookie value to retreive. :return: Returns the cookie value if it's set or None if it's not found. """ if not hasattr(self, 'cookies'): return None if self.cookies.get(name): return self.cookies.get(name)...
Check for a cookie value by name. :param str name: Name of the cookie value to retreive. :return: Returns the cookie value if it's set or None if it's not found.
def load_commands(self, parser): """ Load commands of this profile. :param parser: argparse parser on which to add commands """ entrypoints = self._get_entrypoints() already_loaded = set() for entrypoint in entrypoints: if entrypoint.name not in already_loa...
Load commands of this profile. :param parser: argparse parser on which to add commands
def transmit(self, channel, message): """ Send the message to Slack. :param channel: channel or user to whom the message should be sent. If a ``thread`` attribute is present, that thread ID is used. :param str message: message to send. """ target = ( self.slack.server.channels.find(channel) or sel...
Send the message to Slack. :param channel: channel or user to whom the message should be sent. If a ``thread`` attribute is present, that thread ID is used. :param str message: message to send.
def top_sections(self): """ The number of sections that touch the top side. Returns ------- sections : int The number of sections on the top """ top_line = self.text.split('\n')[0] sections = len(top_line.split('+')) - 2 return secti...
The number of sections that touch the top side. Returns ------- sections : int The number of sections on the top
def is_current_manager_equals_to(cls, pm): """Returns True if this package manager is usable, False otherwise.""" if hasattr(cls, 'works_result'): return cls.works_result is_ok = bool(cls._try_get_current_manager() == pm) setattr(cls, 'works_result', is_ok) return is_...
Returns True if this package manager is usable, False otherwise.
def get_storage(self, script_hash, key, **kwargs): """ Returns the value stored in the storage of a contract script hash for a given key. :param script_hash: contract script hash :param key: key to look up in the storage :type script_hash: str :type key: str :return: val...
Returns the value stored in the storage of a contract script hash for a given key. :param script_hash: contract script hash :param key: key to look up in the storage :type script_hash: str :type key: str :return: value associated with the storage key :rtype: bytearray
def create_dashboard(self, panel_file, data_sources=None, strict=True): """Upload a panel to Elasticsearch if it does not exist yet. If a list of data sources is specified, upload only those elements (visualizations, searches) that match that data source. :param panel_file: file name o...
Upload a panel to Elasticsearch if it does not exist yet. If a list of data sources is specified, upload only those elements (visualizations, searches) that match that data source. :param panel_file: file name of panel (dashobard) to upload :param data_sources: list of data sources ...
def _check_configs(self): """ Reloads the configuration files. """ configs = set(self._find_configs()) known_configs = set(self.configs.keys()) new_configs = configs - known_configs for cfg in (known_configs - configs): self.log.debug("Compass configur...
Reloads the configuration files.
def yield_expr__26(self, yield_loc, exprs): """(2.6, 2.7, 3.0, 3.1, 3.2) yield_expr: 'yield' [testlist]""" if exprs is not None: return ast.Yield(value=exprs, yield_loc=yield_loc, loc=yield_loc.join(exprs.loc)) else: return ast.Yield(value=Non...
(2.6, 2.7, 3.0, 3.1, 3.2) yield_expr: 'yield' [testlist]
def getAttributeData(self, name, channel=None): """ Returns a attribut """ return self._getNodeData(name, self._ATTRIBUTENODE, channel)
Returns a attribut
def delete(self, *args, **kwargs): """ Delete clonable relations first, since they may be objects that wouldn't otherwise be deleted. Calls super to actually delete the object. """ skip_reverses = kwargs.pop('skip_reverses', False) if not skip_reverses: ...
Delete clonable relations first, since they may be objects that wouldn't otherwise be deleted. Calls super to actually delete the object.
def get_custom_annotations_for_alias(data_type): """ Given a Stone data type, returns all custom annotations applied to it. """ # annotations can only be applied to Aliases, but they can be wrapped in # Nullable. also, Aliases pointing to other Aliases don't automatically # inherit their custom ...
Given a Stone data type, returns all custom annotations applied to it.
def load_waypoints(self, filename): '''load waypoints from a file''' self.wploader.target_system = self.target_system self.wploader.target_component = self.target_component try: self.wploader.load(filename) except Exception as msg: print("Unable to load %s...
load waypoints from a file
def to_text(value, encoding='utf-8'): """Convert value to unicode, default encoding is utf-8 :param value: Value to be converted :param encoding: Desired encoding """ if not value: return '' if isinstance(value, six.text_type): return value if isinstance(value, six.binary_ty...
Convert value to unicode, default encoding is utf-8 :param value: Value to be converted :param encoding: Desired encoding
def legacy_decrypt(jwe, jwk, adata='', validate_claims=True, expiry_seconds=None): """ Decrypts a deserialized :class:`~jose.JWE` :param jwe: An instance of :class:`~jose.JWE` :param jwk: A `dict` representing the JWK required to decrypt the content of the :class:`~jose.J...
Decrypts a deserialized :class:`~jose.JWE` :param jwe: An instance of :class:`~jose.JWE` :param jwk: A `dict` representing the JWK required to decrypt the content of the :class:`~jose.JWE`. :param adata: Arbitrary string data used during encryption for additional authentic...
def get_argument_values( arg_defs, # type: Union[Dict[str, GraphQLArgument], Dict] arg_asts, # type: Optional[List[Argument]] variables=None, # type: Optional[Dict[str, Union[List, Dict, int, float, bool, str, None]]] ): # type: (...) -> Dict[str, Any] """Prepares an object map of argument values...
Prepares an object map of argument values given a list of argument definitions and list of argument AST nodes.
def remove_usb_device_source(self, id_p): """Removes a previously added USB device source. in id_p of type str The identifier used when the source was added. """ if not isinstance(id_p, basestring): raise TypeError("id_p can only be an instance of type basestrin...
Removes a previously added USB device source. in id_p of type str The identifier used when the source was added.
def sigusr2_handler(self, unused_signum, unused_frame): """ Handle SIGUSR2 signal. Call function which is defined in the **settings.SIGUSR2_HANDLER**. """ if self._sigusr1_handler_func is not None: self._sigusr2_handler_func(self.context)
Handle SIGUSR2 signal. Call function which is defined in the **settings.SIGUSR2_HANDLER**.
def assign_default_log_values(self, fpath, line, formatter): ''' >>> lc = LogCollector('file=/path/to/log_file.log:formatter=logagg.formatters.basescript', 30) >>> from pprint import pprint >>> formatter = 'logagg.formatters.mongodb' >>> fpath = '/var/log/mongodb/mongodb.log' ...
>>> lc = LogCollector('file=/path/to/log_file.log:formatter=logagg.formatters.basescript', 30) >>> from pprint import pprint >>> formatter = 'logagg.formatters.mongodb' >>> fpath = '/var/log/mongodb/mongodb.log' >>> line = 'some log line here' >>> default_log = lc.assign_defaul...
def getCovariance(self,normalize=True,i0=None,i1=None,pos0=None,pos1=None,chrom=None,center=True,unit=True,pos_cum0=None,pos_cum1=None,blocksize=None,X=None,**kw_args): """calculate the empirical genotype covariance in a region""" if X is not None: K=X.dot(X.T) Nsnp=X.shape[1] ...
calculate the empirical genotype covariance in a region
def add_document(self, key, url, **kwargs): """ Adds document to record Args: key (string): document key url (string): document url Keyword Args: description (string): simple description fulltext (bool): mark if this is a full text ...
Adds document to record Args: key (string): document key url (string): document url Keyword Args: description (string): simple description fulltext (bool): mark if this is a full text hidden (bool): is document should be hidden mate...
def data(self, namespace): """ Gets the thread.local data (dict) for a given namespace. Args: namespace (string): The namespace, or key, of the data dict. Returns: (dict) """ assert namespace if namespace in self._data: retu...
Gets the thread.local data (dict) for a given namespace. Args: namespace (string): The namespace, or key, of the data dict. Returns: (dict)
def add_native(cls, name, func, ret, interp=None, send_interp=False): """Add the native python function ``func`` into the pfp interpreter with the name ``name`` and return value ``ret`` so that it can be called from within a template script. .. note:: The :any:`@native <pfp....
Add the native python function ``func`` into the pfp interpreter with the name ``name`` and return value ``ret`` so that it can be called from within a template script. .. note:: The :any:`@native <pfp.native.native>` decorator exists to simplify this. All native functions ...
def show(): """ Show the modifiers and colors """ # modifiers sys.stdout.write(colorful.bold('bold') + ' ') sys.stdout.write(colorful.dimmed('dimmed') + ' ') sys.stdout.write(colorful.italic('italic') + ' ') sys.stdout.write(colorful.underlined('underlined') + ' ') sys.stdout.write(c...
Show the modifiers and colors
def autocrop(im, bgcolor): "Crop away a border of the given background color." if im.mode != "RGB": im = im.convert("RGB") bg = Image.new("RGB", im.size, bgcolor) diff = ImageChops.difference(im, bg) bbox = diff.getbbox() if bbox: return im.crop(bbox) return im
Crop away a border of the given background color.
def definition_to_message( definition, message=None, table_of_contents=None, heading_level=None): """Helper function to render a definition to a message. :param definition: A definition dictionary (see definitions package). :type definition: dict :param message: The message that the definition...
Helper function to render a definition to a message. :param definition: A definition dictionary (see definitions package). :type definition: dict :param message: The message that the definition should be appended to. :type message: parameters.message.Message :param table_of_contents: Table of con...
def _from_any(cls, spec): """Generic creation method for all types accepted as ``spec``""" if isinstance(spec, str): spec = cls.from_file(spec) elif isinstance(spec, dict): spec = cls.from_dict(spec) elif not isinstance(spec, cls): raise context.TypeEr...
Generic creation method for all types accepted as ``spec``
def show(thing, domain=(0, 1), **kwargs): """Display a nupmy array without having to specify what it represents. This module will attempt to infer how to display your tensor based on its rank, shape and dtype. rank 4 tensors will be displayed as image grids, rank 2 and 3 tensors as images. """ if isinstanc...
Display a nupmy array without having to specify what it represents. This module will attempt to infer how to display your tensor based on its rank, shape and dtype. rank 4 tensors will be displayed as image grids, rank 2 and 3 tensors as images.
def _generate_docstring_for_func(self, namespace, arg_data_type, result_data_type=None, error_data_type=None, overview=None, extra_request_args=None, extra_return_arg=None, footer=None): """ Ge...
Generates a docstring for a function or method. This function is versatile. It will create a docstring using all the data that is provided. :param arg_data_type: The data type describing the argument to the route. The data type should be a struct, and each field will be ...
def compute_from_text(self,text,beta=0.001): """ m.compute_from_text(,text,beta=0.001) -- Compute a matrix values from a text string of ambiguity codes. Use Motif_from_text utility instead to build motifs on the fly. """ prevlett = {'B':...
m.compute_from_text(,text,beta=0.001) -- Compute a matrix values from a text string of ambiguity codes. Use Motif_from_text utility instead to build motifs on the fly.
def _split_chemical_equations(value): """ Split a string with sequential chemical equations into separate strings. Each string in the returned iterable represents a single chemical equation of the input. See the docstrings of `ChemicalEquation` and `ChemicalSystem` for more. Parameters ---...
Split a string with sequential chemical equations into separate strings. Each string in the returned iterable represents a single chemical equation of the input. See the docstrings of `ChemicalEquation` and `ChemicalSystem` for more. Parameters ---------- value : `str` A string with se...
def set_hook(fn, key, **kwargs): """Mark decorated function as a hook to be picked up later. .. note:: Currently only works with functions and instance methods. Class and static methods are not supported. :return: Decorated function if supplied, else this decorator with its args bo...
Mark decorated function as a hook to be picked up later. .. note:: Currently only works with functions and instance methods. Class and static methods are not supported. :return: Decorated function if supplied, else this decorator with its args bound.
def _golden(self, triplet, fun): """Reduce the size of the bracket until the minimum is found""" self.num_golden = 0 (qa, fa), (qb, fb), (qc, fc) = triplet while True: self.num_golden += 1 qd = qa + (qb-qa)*phi/(1+phi) fd = fun(qd) if fd < ...
Reduce the size of the bracket until the minimum is found
def dump_img(fname): """ output the image as text """ img = Image.open(fname) width, _ = img.size txt = '' pixels = list(img.getdata()) for col in range(width): txt += str(pixels[col:col+width]) return txt
output the image as text
def perform(action_name, container, **kwargs): """ Performs an action on the given container map and configuration. :param action_name: Name of the action (e.g. ``update``). :param container: Container configuration name. :param kwargs: Keyword arguments for the action implementation. """ c...
Performs an action on the given container map and configuration. :param action_name: Name of the action (e.g. ``update``). :param container: Container configuration name. :param kwargs: Keyword arguments for the action implementation.
def generate(env,**kw): """ Generate the `msginit` tool """ import SCons.Util from SCons.Tool.GettextCommon import _detect_msginit try: env['MSGINIT'] = _detect_msginit(env) except: env['MSGINIT'] = 'msginit' msginitcom = '$MSGINIT ${_MSGNoTranslator(__env__)} -l ${_MSGINITLOCALE}' \ + ...
Generate the `msginit` tool
def _check_team_login(team): """ Disallow simultaneous public cloud and team logins. """ contents = _load_auth() for auth in itervalues(contents): existing_team = auth.get('team') if team and team != existing_team: raise CommandException( "Can't log in as...
Disallow simultaneous public cloud and team logins.
def serialize_footer(signer): """Uses the signer object which has been used to sign the message to generate the signature, then serializes that signature. :param signer: Cryptographic signer object :type signer: aws_encryption_sdk.internal.crypto.Signer :returns: Serialized footer :rtype: bytes...
Uses the signer object which has been used to sign the message to generate the signature, then serializes that signature. :param signer: Cryptographic signer object :type signer: aws_encryption_sdk.internal.crypto.Signer :returns: Serialized footer :rtype: bytes
def _integrate_variable_trajectory(self, h, g, tol, step, relax): """Generates a solution trajectory of variable length.""" # initialize the solution using initial condition solution = np.hstack((self.t, self.y)) while self.successful(): self.integrate(self.t + h, step, rel...
Generates a solution trajectory of variable length.
def load_user_from_request(req): """ Just like the Flask.login load_user_from_request If you need to customize the user loading from your database, the FlaskBitjws.get_user_by_key method is the one to modify. :param req: The flask request to load a user based on. """ load_jws_from_request(...
Just like the Flask.login load_user_from_request If you need to customize the user loading from your database, the FlaskBitjws.get_user_by_key method is the one to modify. :param req: The flask request to load a user based on.
def add_backend(self, backend): "Add a RapidSMS backend to this tenant" if backend in self.get_backends(): return backend_link, created = BackendLink.all_tenants.get_or_create(backend=backend) self.backendlink_set.add(backend_link)
Add a RapidSMS backend to this tenant
def extract_payload(self): """Extract payload from request.""" if not self.check_signature(): raise InvalidSignature('Invalid Signature') if request.is_json: # Request.get_json() could be first called with silent=True. delete_cached_json_for(request) ...
Extract payload from request.
def _fingerprint_dict_with_files(self, option_val): """Returns a fingerprint of the given dictionary containing file paths. Any value which is a file path which exists on disk will be fingerprinted by that file's contents rather than by its path. This assumes the files are small enough to be read into...
Returns a fingerprint of the given dictionary containing file paths. Any value which is a file path which exists on disk will be fingerprinted by that file's contents rather than by its path. This assumes the files are small enough to be read into memory. NB: The keys of the dict are assumed to be st...
def _db_filename_from_dataframe(base_filename, df): """ Generate database filename for a sqlite3 database we're going to fill with the contents of a DataFrame, using the DataFrame's column names and types. """ db_filename = base_filename + ("_nrows%d" % len(df)) for column_name in df.columns...
Generate database filename for a sqlite3 database we're going to fill with the contents of a DataFrame, using the DataFrame's column names and types.
def blend(self, other, percent=0.5): """blend this color with the other one. Args: :other: the grapefruit.Color to blend with this one. Returns: A grapefruit.Color instance which is the result of blending this color on the other one. >>> c1 = Color.from_rgb(1, 0.5, 0, 0.2) ...
blend this color with the other one. Args: :other: the grapefruit.Color to blend with this one. Returns: A grapefruit.Color instance which is the result of blending this color on the other one. >>> c1 = Color.from_rgb(1, 0.5, 0, 0.2) >>> c2 = Color.from_rgb(1, 1, 1, 0.6) ...
def register_doi(self, submission_id, request_xml): """ This method registry a new DOI number in Crossref or update some DOI metadata. submission_id: Will be used as the submission file name. The file name could be used in future requests to retrieve the submission status. ...
This method registry a new DOI number in Crossref or update some DOI metadata. submission_id: Will be used as the submission file name. The file name could be used in future requests to retrieve the submission status. request_xml: The XML with the document metadata. It must be under ...
def column_reflection_fallback(self): """If we can't reflect the table, use a query to at least get column names.""" sql = sa.select([sa.text("*")]).select_from(self._table) col_names = self.engine.execute(sql).keys() col_dict = [{'name': col_name} for col_name in col_names] retu...
If we can't reflect the table, use a query to at least get column names.
def replace_body_vars(self, body): """Given a multiline string that is the body of the job script, replace the placeholders for environment variables with backend-specific realizations, and return the modified body. See the `job_vars` attribute for the mappings that are performed. ...
Given a multiline string that is the body of the job script, replace the placeholders for environment variables with backend-specific realizations, and return the modified body. See the `job_vars` attribute for the mappings that are performed.
def flatten_and_write(dotenv_path, dotenv_as_dict, quote_mode='always'): """ Writes dotenv_as_dict to dotenv_path, flattening the values :param dotenv_path: .env path :param dotenv_as_dict: dict :param quote_mode: :return: """ with open(dotenv_path, 'w') as f: for k, v in dotenv_...
Writes dotenv_as_dict to dotenv_path, flattening the values :param dotenv_path: .env path :param dotenv_as_dict: dict :param quote_mode: :return:
def _get_id_format(self): """ Return the id regex from the parameters""" id_format = gf.safe_get( self.parameters, gc.PPN_TASK_OS_FILE_ID_REGEX, self.DEFAULT_ID_FORMAT, can_return_none=False ) try: identifier = id_format % 1 ...
Return the id regex from the parameters
def create(self, create_missing=None): """Do extra work to fetch a complete set of attributes for this entity. For more information, see `Bugzilla #1223540 <https://bugzilla.redhat.com/show_bug.cgi?id=1223540>`_. """ return DockerComputeResource( self._server_config...
Do extra work to fetch a complete set of attributes for this entity. For more information, see `Bugzilla #1223540 <https://bugzilla.redhat.com/show_bug.cgi?id=1223540>`_.
def pairwise_point_combinations(xs, ys, anchors): """ Does an in-place addition of the four points that can be composed by combining coordinates from the two lists to the given list of anchors """ for i in xs: anchors.append((i, max(ys))) anchors.append((i, min(ys))) for i in ys:...
Does an in-place addition of the four points that can be composed by combining coordinates from the two lists to the given list of anchors
def check_missing_atoms(self, template=None, ha_only=True): """ Checks for missing atoms based on a template. Default: Searches for missing heavy atoms (not Hydrogen) based on Bio.Struct.protein_residues Arguments: - template, dictionary, keys are residue names, values...
Checks for missing atoms based on a template. Default: Searches for missing heavy atoms (not Hydrogen) based on Bio.Struct.protein_residues Arguments: - template, dictionary, keys are residue names, values list of atom names. - ha_only, boolean, default True, restrict check ...
def parse_instance(self, tup_tree): """ Return a CIMInstance. The instance contains the properties, qualifiers and classname for the instance. :: <!ELEMENT INSTANCE (QUALIFIER*, (PROPERTY | PROPERTY.ARRAY | PROPERTY.RE...
Return a CIMInstance. The instance contains the properties, qualifiers and classname for the instance. :: <!ELEMENT INSTANCE (QUALIFIER*, (PROPERTY | PROPERTY.ARRAY | PROPERTY.REFERENCE)*)> <!ATTLIST INSTANCE ...
def get_config_value(name, path_to_file='config.txt'): """ gets the value for "name" from "path_to_file" config file Args: name: name of varibale in config file path_to_file: path to config file Returns: path to dll if name exists in the file; otherwise, returns None """ # if ...
gets the value for "name" from "path_to_file" config file Args: name: name of varibale in config file path_to_file: path to config file Returns: path to dll if name exists in the file; otherwise, returns None
def area_top_orifice(self): """Estimate the orifice area corresponding to the top row of orifices. Another solution method is to use integration to solve this problem. Here we use the width of the stout weir in the center of the top row to estimate the area of the top orifice """...
Estimate the orifice area corresponding to the top row of orifices. Another solution method is to use integration to solve this problem. Here we use the width of the stout weir in the center of the top row to estimate the area of the top orifice
def _construct_options(options_bootstrapper, build_configuration): """Parse and register options. :returns: An Options object representing the full set of runtime options. """ # Now that plugins and backends are loaded, we can gather the known scopes. # Gather the optionables that are not scoped t...
Parse and register options. :returns: An Options object representing the full set of runtime options.
def collect(self): """ Collect s3 bucket stats """ if boto is None: self.log.error("Unable to import boto python module") return {} for s3instance in self.config['s3']: self.log.info("S3: byte_unit: %s" % self.config['byte_unit']) a...
Collect s3 bucket stats
def close(self): """Disconnects uWSGI from the client.""" uwsgi.disconnect() if self._req_ctx is None: # better kill it here in case wait() is not called again self._select_greenlet.kill() self._event.set()
Disconnects uWSGI from the client.
def disable_paging(self, command="terminal length 999", delay_factor=1): """Disable paging default to a Cisco CLI method.""" delay_factor = self.select_delay_factor(delay_factor) time.sleep(delay_factor * 0.1) self.clear_buffer() command = self.normalize_cmd(command) log....
Disable paging default to a Cisco CLI method.
def compute(self, x, yerr): """ Compute and factorize the covariance matrix. Args: x (ndarray[nsamples, ndim]): The independent coordinates of the data points. yerr (ndarray[nsamples] or float): The Gaussian uncertainties on the data point...
Compute and factorize the covariance matrix. Args: x (ndarray[nsamples, ndim]): The independent coordinates of the data points. yerr (ndarray[nsamples] or float): The Gaussian uncertainties on the data points at coordinates ``x``. These values will be ...
def write(self, page, data): """Send a WRITE command to store data on the tag. The *page* argument specifies the offset in multiples of 4 bytes. The *data* argument must be a string or bytearray of length 4. Command execution errors raise :exc:`Type2TagCommandError`. "...
Send a WRITE command to store data on the tag. The *page* argument specifies the offset in multiples of 4 bytes. The *data* argument must be a string or bytearray of length 4. Command execution errors raise :exc:`Type2TagCommandError`.
def patch(self, resource_endpoint, data={}): """Don't use it.""" url = self._create_request_url(resource_endpoint) return req.patch(url, headers=self.auth_header, json=data)
Don't use it.
def intersect(obj1, obj2): """ intersect two Vector objects Parameters ---------- obj1: Vector the first vector object; this object is reprojected to the CRS of obj2 if necessary obj2: Vector the second vector object Returns ------- Vector the intersect of o...
intersect two Vector objects Parameters ---------- obj1: Vector the first vector object; this object is reprojected to the CRS of obj2 if necessary obj2: Vector the second vector object Returns ------- Vector the intersect of obj1 and obj2