code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def render_template(self, template_name, out_path=None): """Render a template based on this TileBus Block. The template has access to all of the attributes of this block as a dictionary (the result of calling self.to_dict()). You can optionally render to a file by passing out_path. ...
Render a template based on this TileBus Block. The template has access to all of the attributes of this block as a dictionary (the result of calling self.to_dict()). You can optionally render to a file by passing out_path. Args: template_name (str): The name of the templat...
def files(self): """List of Phasics tif file names in the input zip file""" if self._files is None: self._files = SeriesZipTifPhasics._index_files(self.path) return self._files
List of Phasics tif file names in the input zip file
def discover_single_case(self, module, case_attributes): """Find and load a single TestCase or TestCase method from a module. Parameters ---------- module : module The imported Python module containing the TestCase to be loaded. case_attributes : list ...
Find and load a single TestCase or TestCase method from a module. Parameters ---------- module : module The imported Python module containing the TestCase to be loaded. case_attributes : list A list (length 1 or 2) of str. The first component must be...
def _get_mean_deep_soil(self, mag, rake, rrup, is_reverse, imt): """ Calculate and return the mean intensity for deep soil sites. Implements an equation from table 4. """ if mag <= self.NEAR_FIELD_SATURATION_MAG: c4 = self.COEFFS_SOIL_IMT_INDEPENDENT['c4lowmag'] ...
Calculate and return the mean intensity for deep soil sites. Implements an equation from table 4.
def to_bytes(self): ''' Create bytes from properties ''' # Verify that properties make sense self.sanitize() # Start with the type bitstream = BitArray('uint:4=%d' % self.message_type) # Add the flags bitstream += BitArray('bool=%d, bool=%d, bool...
Create bytes from properties
def open(self): """ Search device on USB tree and set is as escpos device """ self.device = usb.core.find(idVendor=self.idVendor, idProduct=self.idProduct) if self.device is None: raise NoDeviceError() try: if self.device.is_kernel_driver_active(self.inte...
Search device on USB tree and set is as escpos device
def allowance (self, filename): """Preconditions: - our agent applies to this entry - filename is URL decoded Check if given filename is allowed to acces this entry. @return: True if allowed, else False @rtype: bool """ for line in self.rulelines: ...
Preconditions: - our agent applies to this entry - filename is URL decoded Check if given filename is allowed to acces this entry. @return: True if allowed, else False @rtype: bool
def get_plugins(modules, classobj): """Find all class objects in all modules. @param modules: the modules to search @ptype modules: iterator of modules @return: found classes @rytpe: iterator of class objects """ for module in modules: for plugin in get_module_plugins(module, classob...
Find all class objects in all modules. @param modules: the modules to search @ptype modules: iterator of modules @return: found classes @rytpe: iterator of class objects
def on_return(self, channel, method, properties, body): """Invoked by RabbitMQ when it returns a message that was published. :param channel: The channel the message was delivered on :type channel: pika.channel.Channel :param method: The AMQP method frame :type method: pika.frame...
Invoked by RabbitMQ when it returns a message that was published. :param channel: The channel the message was delivered on :type channel: pika.channel.Channel :param method: The AMQP method frame :type method: pika.frame.Frame :param properties: The AMQP message properties ...
def getNextSample(self, V): """ Given a ranking over the candidates, generate a new ranking by assigning each candidate at position i a Plakett-Luce weight of phi^i and draw a new ranking. :ivar list<int> V: Contains integer representations of each candidate in order of their ...
Given a ranking over the candidates, generate a new ranking by assigning each candidate at position i a Plakett-Luce weight of phi^i and draw a new ranking. :ivar list<int> V: Contains integer representations of each candidate in order of their ranking in a vote, from first to last.
def factors(self): """ Access the factors :returns: twilio.rest.authy.v1.service.entity.factor.FactorList :rtype: twilio.rest.authy.v1.service.entity.factor.FactorList """ if self._factors is None: self._factors = FactorList( self._version, ...
Access the factors :returns: twilio.rest.authy.v1.service.entity.factor.FactorList :rtype: twilio.rest.authy.v1.service.entity.factor.FactorList
def _add_deprecated_function_notice_to_docstring(doc, date, instructions): """Adds a deprecation notice to a docstring for deprecated functions.""" if instructions: deprecation_message = """ .. warning:: **THIS FUNCTION IS DEPRECATED:** It will be removed after %s. ...
Adds a deprecation notice to a docstring for deprecated functions.
def openSafeReplace(filepath, mode='w+b'): """Context manager to open a temporary file and replace the original file on closing. """ tempfileName = None #Check if the filepath can be accessed and is writable before creating the #tempfile if not _isFileAccessible(filepath): raise IOEr...
Context manager to open a temporary file and replace the original file on closing.
def _getDefaultCombinedL4Params(self, numInputBits, inputSize, numExternalInputBits, externalInputSize, L2CellCount): """ Returns a good default set of parameters to use in a combined L4 region. """ sampleSize = numExternalInputBits + n...
Returns a good default set of parameters to use in a combined L4 region.
def _handle_authentication_error(self): """ Return an authentication error. """ response = make_response('Access Denied') response.headers['WWW-Authenticate'] = self.auth.get_authenticate_header() response.status_code = 401 return response
Return an authentication error.
def page_view(url): """ Page view decorator. Put that around a state handler function in order to log a page view each time the handler gets called. :param url: simili-URL that you want to give to the state """ def decorator(func): @wraps(func) async def wrapper(self: Base...
Page view decorator. Put that around a state handler function in order to log a page view each time the handler gets called. :param url: simili-URL that you want to give to the state
def male_breeding_location_type(self): """This attribute defines whether a breeding male's current location is the same as the breeding cage. This attribute is used to color breeding table entries such that male mice which are currently in a different cage can quickly be identified.""" if int(s...
This attribute defines whether a breeding male's current location is the same as the breeding cage. This attribute is used to color breeding table entries such that male mice which are currently in a different cage can quickly be identified.
def sync_agg_metric(self, unique_identifier, metric, start_date, end_date): """ Uses the count for each day in the date range to recalculate the counters for the associated weeks and months for the ``metric`` for ``unique_identifier``. Useful for updating the counters for week and month after us...
Uses the count for each day in the date range to recalculate the counters for the associated weeks and months for the ``metric`` for ``unique_identifier``. Useful for updating the counters for week and month after using set_metric_by_day. The redis backend supports lists for both ``unique_identifier`` ...
def _data_update(subjects, queue, run_flag): """ Get data from backgound process and notify all subscribed observers with the new data """ while run_flag.running: while not queue.empty(): data = queue.get() for subject in [s for s in subjects i...
Get data from backgound process and notify all subscribed observers with the new data
def iter_work_specs(self, limit=None, start=None): ''' yield work spec dicts ''' count = 0 ws_list, start = self.list_work_specs(limit, start) while True: for name_spec in ws_list: yield name_spec[1] count += 1 i...
yield work spec dicts
def clear_context(pid_file): """Called at exit. Delete the context file to signal there is no active notebook. We don't delete the whole file, but leave it around for debugging purposes. Maybe later we want to pass some information back to the web site. """ return raise RuntimeError("Should not hap...
Called at exit. Delete the context file to signal there is no active notebook. We don't delete the whole file, but leave it around for debugging purposes. Maybe later we want to pass some information back to the web site.
def replace_cluster_custom_object(self, group, version, plural, name, body, **kwargs): # noqa: E501 """replace_cluster_custom_object # noqa: E501 replace the specified cluster scoped custom object # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynch...
replace_cluster_custom_object # noqa: E501 replace the specified cluster scoped custom object # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_cluster_custom_object(group, ve...
def get_case(word, correction): """ Best guess of intended case. manchester => manchester chilton => Chilton AAvTech => AAvTech THe => The imho => IMHO """ if word.istitle(): return correction.title() if word.isupper(): return correction.upper() if correctio...
Best guess of intended case. manchester => manchester chilton => Chilton AAvTech => AAvTech THe => The imho => IMHO
def get(cls, name=__name__): """Return a Mapper instance with the given name. If the name already exist return its instance. Does not work if a Mapper was created via its constructor. Using `Mapper.get()`_ is the prefered way. Args: name (str, optional): N...
Return a Mapper instance with the given name. If the name already exist return its instance. Does not work if a Mapper was created via its constructor. Using `Mapper.get()`_ is the prefered way. Args: name (str, optional): Name for the newly created instance. ...
def _set_log_level(self): """ Inspects config and sets the log level as instance attr. If not present in config, default is "INFO". """ # set log level on logger log_level = "INFO" if hasattr(self._config, "level") and self._config.level.upper() in ["DEBUG", "INFO...
Inspects config and sets the log level as instance attr. If not present in config, default is "INFO".
async def _dump_container_val(self, writer, elem, container_type, params=None): """ Single elem dump :param writer: :param elem: :param container_type: :param params: :return: """ elem_type = container_elem_type(container_type, params) awai...
Single elem dump :param writer: :param elem: :param container_type: :param params: :return:
def max_date(self, symbol): """ Return the maximum datetime stored for a particular symbol Parameters ---------- symbol : `str` symbol name for the item """ res = self._collection.find_one({SYMBOL: symbol}, projection={ID: 0, END: 1}, ...
Return the maximum datetime stored for a particular symbol Parameters ---------- symbol : `str` symbol name for the item
def select_action(self, state): """ Select the best action for the given state using e-greedy exploration to minimize overfitting :return: tuple(action, value) """ value = 0 if self.steps < self.min_steps: action = np.random.randint(self.actions) else: self.eps = max(self.ep...
Select the best action for the given state using e-greedy exploration to minimize overfitting :return: tuple(action, value)
def render_er(input, output, mode='auto', include_tables=None, include_columns=None, exclude_tables=None, exclude_columns=None, schema=None): """ Transform the metadata into a representation. :param input: Possible inputs are instances of: MetaData: SQLAlchemy Metadata Declarat...
Transform the metadata into a representation. :param input: Possible inputs are instances of: MetaData: SQLAlchemy Metadata DeclarativeMeta: SQLAlchemy declarative Base :param output: name of the file to output the :param mode: str in list: 'er': writes to a file the markup to genera...
def pool_function(p, nick, rutaDescarga, avoidProcessing=True, avoidDownload=True, verbosity=1): """ Wrapper for being able to launch all the threads of getPageWrapper. We receive the parameters for getPageWrapper as a tuple. Args: ----- pName: Platform where the information is stored. It ...
Wrapper for being able to launch all the threads of getPageWrapper. We receive the parameters for getPageWrapper as a tuple. Args: ----- pName: Platform where the information is stored. It is a string. nick: Nick to be searched. rutaDescarga: Local file where saving the obtained in...
def create(self, friendly_name=values.unset, domain_name=values.unset, disaster_recovery_url=values.unset, disaster_recovery_method=values.unset, recording=values.unset, secure=values.unset, cnam_lookup_enabled=values.unset): """ Create a new TrunkInstance ...
Create a new TrunkInstance :param unicode friendly_name: A string to describe the resource :param unicode domain_name: The unique address you reserve on Twilio to which you route your SIP traffic :param unicode disaster_recovery_url: The HTTP URL that we should call if an error occurs while sen...
def pci_contents(self, use_dict=None, as_class=dict): """Return the contents of an object as a dict.""" if _debug: PCI._debug("pci_contents use_dict=%r as_class=%r", use_dict, as_class) # make/extend the dictionary of content if use_dict is None: use_dict = as_class() ...
Return the contents of an object as a dict.
def coredump_configured(name, enabled, dump_ip, host_vnic='vmk0', dump_port=6500): ''' Ensures a host's core dump configuration. name Name of the state. enabled Sets whether or not ESXi core dump collection should be enabled. This is a boolean value set to ``True`` or ``False``...
Ensures a host's core dump configuration. name Name of the state. enabled Sets whether or not ESXi core dump collection should be enabled. This is a boolean value set to ``True`` or ``False`` to enable or disable core dumps. Note that ESXi requires that the core dump m...
def solve2x2(lhs, rhs): """Solve a square 2 x 2 system via LU factorization. This is meant to be a stand-in for LAPACK's ``dgesv``, which just wraps two calls to ``dgetrf`` and ``dgetrs``. We wrap for two reasons: * We seek to avoid exceptions as part of the control flow (which is what :func`num...
Solve a square 2 x 2 system via LU factorization. This is meant to be a stand-in for LAPACK's ``dgesv``, which just wraps two calls to ``dgetrf`` and ``dgetrs``. We wrap for two reasons: * We seek to avoid exceptions as part of the control flow (which is what :func`numpy.linalg.solve` does). * W...
def configure_savedsearch(self, ns, definition): """ Register a saved search endpoint. The definition's func should be a search function, which must: - accept kwargs for the request data - return a tuple of (items, count) where count is the total number of items availa...
Register a saved search endpoint. The definition's func should be a search function, which must: - accept kwargs for the request data - return a tuple of (items, count) where count is the total number of items available (in the case of pagination) The definition's request_sch...
def _setVirtualEnv(): """Attempt to set the virtualenv activate command, if it hasn't been specified. """ try: activate = options.virtualenv.activate_cmd except AttributeError: activate = None if activate is None: virtualenv = path(os.environ.get('VIRTUAL_ENV', '')) ...
Attempt to set the virtualenv activate command, if it hasn't been specified.
def split_iterable_as_unordered_iterable(self, values): """Group iterable into iterables, without regard for the ordering of self.index.unique key-group tuples are yielded as soon as they are complete Parameters ---------- values : iterable of length equal to keys it...
Group iterable into iterables, without regard for the ordering of self.index.unique key-group tuples are yielded as soon as they are complete Parameters ---------- values : iterable of length equal to keys iterable of values to be grouped Yields ------ ...
def toc_html(self): """Return the HTML for the current TOC. This expects the `_toc` attribute to have been set on this instance. """ if self._toc is None: return None def indent(): return ' ' * (len(h_stack) - 1) lines = [] h_stack = [0]...
Return the HTML for the current TOC. This expects the `_toc` attribute to have been set on this instance.
def sendcontrol(self, char): '''Helper method that wraps send() with mnemonic access for sending control character to the child (such as Ctrl-C or Ctrl-D). For example, to send Ctrl-G (ASCII 7, bell, '\a'):: child.sendcontrol('g') See also, sendintr() and sendeof(). ...
Helper method that wraps send() with mnemonic access for sending control character to the child (such as Ctrl-C or Ctrl-D). For example, to send Ctrl-G (ASCII 7, bell, '\a'):: child.sendcontrol('g') See also, sendintr() and sendeof().
def from_str(string, max_number=9, separator="."): """Parses string :param string: Version :param max_number: Max number reachable by sub :param separator: Version numbers are separated with this split :return: Parses string and returns object """ tokens = string...
Parses string :param string: Version :param max_number: Max number reachable by sub :param separator: Version numbers are separated with this split :return: Parses string and returns object
def _image_size(image_config, type_, target_size): """Find the closest available size for specified image type. Arguments: image_config (:py:class:`dict`): The image config data. type_ (:py:class:`str`): The type of image to create a URL for, (``'poster'`` or ``'profile'...
Find the closest available size for specified image type. Arguments: image_config (:py:class:`dict`): The image config data. type_ (:py:class:`str`): The type of image to create a URL for, (``'poster'`` or ``'profile'``). target_size (:py:class:`int`): The size of imag...
def linop_scale(w, op): """Creates weighted `LinOp` from existing `LinOp`.""" # We assume w > 0. (This assumption only relates to the is_* attributes.) with tf.name_scope("linop_scale"): # TODO(b/35301104): LinearOperatorComposition doesn't combine operators, so # special case combinations here. Once it d...
Creates weighted `LinOp` from existing `LinOp`.
def cli(ctx, verbose, fake, install, uninstall, config): """legit command line interface""" # Create a repo object and remember it as as the context object. From # this point onwards other commands can refer to it by using the # @pass_scm decorator. ctx.obj = SCMRepo() ctx.obj.fake = fake c...
legit command line interface
def create_new(self, body): """Configure a new custom domain Args: body (str): The domain, tye and verification method in json See: https://auth0.com/docs/api/management/v2#!/Custom_Domains/post_custom_domains """ return self.client.post(self._url(), data=body)
Configure a new custom domain Args: body (str): The domain, tye and verification method in json See: https://auth0.com/docs/api/management/v2#!/Custom_Domains/post_custom_domains
def create_code_cell(block): """Create a notebook code cell from a block.""" code_cell = nbbase.new_code_cell(source=block['content']) attr = block['attributes'] if not attr.is_empty: code_cell.metadata \ = nbbase.NotebookNode({'attributes': attr.to_dict()}) ...
Create a notebook code cell from a block.
def set_cmd_env_var(value): """Decorator that sets the temple command env var to value""" def func_decorator(function): @functools.wraps(function) def wrapper(*args, **kwargs): previous_cmd_env_var = os.getenv(temple.constants.TEMPLE_ENV_VAR) os.environ[temple.constants.T...
Decorator that sets the temple command env var to value
def getRoles(self): """Get all :class:`rtcclient.models.Role` objects in this project area If no :class:`Roles` are retrieved, `None` is returned. :return: a :class:`list` that contains all :class:`rtcclient.models.Role` objects :rtype: list """ # n...
Get all :class:`rtcclient.models.Role` objects in this project area If no :class:`Roles` are retrieved, `None` is returned. :return: a :class:`list` that contains all :class:`rtcclient.models.Role` objects :rtype: list
def namedb_state_transition( cur, opcode, op_data, block_id, vtxindex, txid, history_id, cur_record, record_table, constraints_ignored=[] ): """ Given an operation (opcode, op_data), a point in time (block_id, vtxindex, txid), and a current record (history_id, cur_record), apply the operation to the record ...
Given an operation (opcode, op_data), a point in time (block_id, vtxindex, txid), and a current record (history_id, cur_record), apply the operation to the record and save the delta to the record's history. Also, insert or update the new record into the db. The cur_record must exist already. Return t...
def delete_entity(self, partition_key, row_key, if_match='*'): ''' Adds a delete entity operation to the batch. See :func:`~azure.storage.table.tableservice.TableService.delete_entity` for more information on deletes. The operation will not be executed un...
Adds a delete entity operation to the batch. See :func:`~azure.storage.table.tableservice.TableService.delete_entity` for more information on deletes. The operation will not be executed until the batch is committed. :param str partition_key: The PartitionKey of the entity...
def render_to_json_response(self, context, **kwargs): """ Returns a JSON response, transforming 'context' to make the payload. """ return HttpResponse( self.convert_context_to_json(context), content_type='application/json', **kwargs )
Returns a JSON response, transforming 'context' to make the payload.
def value(self): """Returns the model's average precision for each class Return: ap (FloatTensor): 1xK tensor, with avg precision for each class k """ if self.scores.numel() == 0: return 0 ap = torch.zeros(self.scores.size(1)) rg = torch.arange(1,...
Returns the model's average precision for each class Return: ap (FloatTensor): 1xK tensor, with avg precision for each class k
def multi_index_df_to_component_dfs(multi_index_df, rid="rid", cid="cid"): """ Convert a multi-index df into 3 component dfs. """ # Id level of the multiindex will become the index rids = list(multi_index_df.index.get_level_values(rid)) cids = list(multi_index_df.columns.get_level_values(cid)) # I...
Convert a multi-index df into 3 component dfs.
def crossvalidate(self, foldsfile): """Train & Test using cross validation, testfile is a file that contains the filenames of all the folds!""" options = "-F " + self.format + " " + self.timbloptions + " -t cross_validate" print("Instantiating Timbl API : " + options,file=stderr) if sys...
Train & Test using cross validation, testfile is a file that contains the filenames of all the folds!
def to_env_vars(self): """Environment variable representation of the training environment Returns: dict: an instance of dictionary """ env = { 'hosts': self.hosts, 'network_interface_name': self.network_interface_name, 'hps': self.hyperparameters, 'u...
Environment variable representation of the training environment Returns: dict: an instance of dictionary
def upgrade(): """Upgrade database.""" # table ObjectVersion: modify primary_key if op.get_context().dialect.name == 'mysql': Fk = 'fk_files_object_bucket_id_files_bucket' op.execute( 'ALTER TABLE files_object ' 'DROP FOREIGN KEY {0}, DROP PRIMARY KEY, ' '...
Upgrade database.
def data2schema( _data=None, _force=False, _besteffort=True, _registry=None, _factory=None, _buildkwargs=None, **kwargs ): """Get the schema able to instanciate input data. The default value of schema will be data. Can be used such as a decorator: ..code-block:: python @data2...
Get the schema able to instanciate input data. The default value of schema will be data. Can be used such as a decorator: ..code-block:: python @data2schema def example(): pass # return a function schema @data2schema(_registry=myregistry) def example(): pass # return a...
def save_thumbnail(image_path_template, src_file, file_conf, gallery_conf): """Generate and Save the thumbnail image Parameters ---------- image_path_template : str holds the template where to save and how to name the image src_file : str path to source python file gallery_conf ...
Generate and Save the thumbnail image Parameters ---------- image_path_template : str holds the template where to save and how to name the image src_file : str path to source python file gallery_conf : dict Sphinx-Gallery configuration dictionary
def _parse_lti_data(self, courseid, taskid): """ Verify and parse the data for the LTI basic launch """ post_input = web.webapi.rawinput("POST") self.logger.debug('_parse_lti_data:' + str(post_input)) try: course = self.course_factory.get_course(courseid) except exce...
Verify and parse the data for the LTI basic launch
def get_tables(self): """ Returns a collection of this worksheet tables""" url = self.build_url(self._endpoints.get('get_tables')) response = self.session.get(url) if not response: return [] data = response.json() return [self.table_constructor(parent=self...
Returns a collection of this worksheet tables
def _parse_hello_extensions(data): """ Creates a generator returning tuples of information about each extension from a byte string of extension data contained in a ServerHello ores ClientHello message :param data: A byte string of a extension data from a TLS ServerHello or ClientHello ...
Creates a generator returning tuples of information about each extension from a byte string of extension data contained in a ServerHello ores ClientHello message :param data: A byte string of a extension data from a TLS ServerHello or ClientHello message :return: A generator th...
def read_config_file(self, file_name): """ Reads a CWR grammar config file. :param file_name: name of the text file :return: the file's contents """ with open(os.path.join(self.__path(), os.path.basename(file_name)), 'rt') as file_config: re...
Reads a CWR grammar config file. :param file_name: name of the text file :return: the file's contents
def spin(self): """ Perform a single spin """ for x in self.spinchars: self.string = self.msg + "...\t" + x + "\r" self.out.write(self.string.encode('utf-8')) self.out.flush() time.sleep(self.waittime)
Perform a single spin
def check_chunks(n_samples, n_features, chunks=None): """Validate and normalize the chunks argument for a dask.array Parameters ---------- n_samples, n_features : int Give the shape of the array chunks : int, sequence, optional, default None * For 'chunks=None', this picks a "good" ...
Validate and normalize the chunks argument for a dask.array Parameters ---------- n_samples, n_features : int Give the shape of the array chunks : int, sequence, optional, default None * For 'chunks=None', this picks a "good" default number of chunks based on the number of CPU...
def add_spectra(self, spectra_dict, key_sort_func=None): """ Add a dictionary of doses, with an optional sorting function for the keys. Args: dos_dict: dict of {label: Dos} key_sort_func: function used to sort the dos_dict keys. """ if key_sort_fu...
Add a dictionary of doses, with an optional sorting function for the keys. Args: dos_dict: dict of {label: Dos} key_sort_func: function used to sort the dos_dict keys.
def knot_removal_alpha_j(u, degree, knotvector, num, idx): """ Computes :math:`\\alpha_{j}` coefficient for knot removal algorithm. Please refer to Eq. 5.29 of The NURBS Book by Piegl & Tiller, 2nd Edition, p.184 for details. :param u: knot :type u: float :param degree: degree :type degree: in...
Computes :math:`\\alpha_{j}` coefficient for knot removal algorithm. Please refer to Eq. 5.29 of The NURBS Book by Piegl & Tiller, 2nd Edition, p.184 for details. :param u: knot :type u: float :param degree: degree :type degree: int :param knotvector: knot vector :type knotvector: tuple ...
def get_end_trigger(options): """ When to end the optimization based on input option. """ if options.endTriggerType.lower() == "epoch": return MaxEpoch(options.endTriggerNum) else: return MaxIteration(options.endTriggerNum)
When to end the optimization based on input option.
def load_dependencies(req, history=None): """ Load the dependency tree as a Python object tree, suitable for JSON serialization. >>> deps = load_dependencies('jaraco.packaging') >>> import json >>> doc = json.dumps(deps) """ if history is None: history = set() dist = pkg_res...
Load the dependency tree as a Python object tree, suitable for JSON serialization. >>> deps = load_dependencies('jaraco.packaging') >>> import json >>> doc = json.dumps(deps)
def coalesce_events(self, coalesce=True): """ Coalescing events. Events are usually processed by batchs, their size depend on various factors. Thus, before processing them, events received from inotify are aggregated in a fifo queue. If this coalescing option is enabled events ar...
Coalescing events. Events are usually processed by batchs, their size depend on various factors. Thus, before processing them, events received from inotify are aggregated in a fifo queue. If this coalescing option is enabled events are filtered based on their unicity, only unique events ...
def Update(self): """Commit current PublicIP definition to cloud. Usually called by the class to commit changes to port and source restriction policies. >>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0].Update().WaitUntilComplete() 0 """ return(clc.v2.Requests(clc.v2.API.Call('PUT','servers/%s/...
Commit current PublicIP definition to cloud. Usually called by the class to commit changes to port and source restriction policies. >>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0].Update().WaitUntilComplete() 0
def read_file(self): """ Grabs filename and enables it to be read. :return: raw_file = unaltered text; file_lines = text split by lines. """ with open(self.filename, mode='r+', encoding='utf8') as text_file: self.raw_file = text_file.read() # pylint: disable= attribu...
Grabs filename and enables it to be read. :return: raw_file = unaltered text; file_lines = text split by lines.
def iter_by_year(self): """Split the return objects by year and iterate""" for yr, details in self.txn_details.iter_by_year(): yield yr, Performance(details)
Split the return objects by year and iterate
def writeToDelimitedString(obj, stream=None): """ Stanford CoreNLP uses the Java "writeDelimitedTo" function, which writes the size (and offset) of the buffer before writing the object. This function handles parsing this message starting from offset 0. @returns how many bytes of @buf were consumed....
Stanford CoreNLP uses the Java "writeDelimitedTo" function, which writes the size (and offset) of the buffer before writing the object. This function handles parsing this message starting from offset 0. @returns how many bytes of @buf were consumed.
def parse_sentence(obj: dict) -> BioCSentence: """Deserialize a dict obj to a BioCSentence object""" sentence = BioCSentence() sentence.offset = obj['offset'] sentence.infons = obj['infons'] sentence.text = obj['text'] for annotation in obj['annotations']: sentence.add_annotation(...
Deserialize a dict obj to a BioCSentence object
def rdn_to_dn(changes: Changeset, name: str, base_dn: str) -> Changeset: """ Convert the rdn to a fully qualified DN for the specified LDAP connection. :param changes: The changes object to lookup. :param name: rdn to convert. :param base_dn: The base_dn to lookup. :return: fully qualified DN. ...
Convert the rdn to a fully qualified DN for the specified LDAP connection. :param changes: The changes object to lookup. :param name: rdn to convert. :param base_dn: The base_dn to lookup. :return: fully qualified DN.
def main(): """ Main function, called when run as an application. """ global args, server_address # parse the command line arguments parser = ArgumentParser(description=__doc__) parser.add_argument( "host", nargs='?', help="address of host (default %r)" % (SERVER_HOST,), ...
Main function, called when run as an application.
def get_cdd_hdd_candidate_models( data, minimum_non_zero_cdd, minimum_non_zero_hdd, minimum_total_cdd, minimum_total_hdd, beta_cdd_maximum_p_value, beta_hdd_maximum_p_value, weights_col, ): """ Return a list of candidate cdd_hdd models for a particular selection of cooling balanc...
Return a list of candidate cdd_hdd models for a particular selection of cooling balance point and heating balance point Parameters ---------- data : :any:`pandas.DataFrame` A DataFrame containing at least the column ``meter_value`` and 1 to n columns each of the form ``hdd_<heating_bala...
def handle_authorized(self, event): """Send the initial presence after log-in.""" request_software_version(self.client, self.target_jid, self.success, self.failure)
Send the initial presence after log-in.
def ffill(arr, dim=None, limit=None): '''forward fill missing values''' import bottleneck as bn axis = arr.get_axis_num(dim) # work around for bottleneck 178 _limit = limit if limit is not None else arr.shape[axis] return apply_ufunc(bn.push, arr, dask='parallelized', ...
forward fill missing values
def get_urlpatterns(self): """ Returns the URL patterns managed by the considered factory / application. """ return [ path( _('topic/<str:slug>-<int:pk>/lock/'), self.topic_lock_view.as_view(), name='topic_lock', ), path...
Returns the URL patterns managed by the considered factory / application.
def UpdateValues(self): """Update all displayed values""" # This sends an event to the grid table # to update all of the values msg = wx.grid.GridTableMessage(self, wx.grid.GRIDTABLE_REQUEST_VIEW_GET_VALUES) self.grid.ProcessTableMessage(msg)
Update all displayed values
def _Execute(statements, context, callback, trace): """Execute a bunch of template statements in a ScopedContext. Args: callback: Strings are "written" to this callback function. trace: Trace object, or None This is called in a mutually recursive fashion. """ # Every time we call _Execute, incre...
Execute a bunch of template statements in a ScopedContext. Args: callback: Strings are "written" to this callback function. trace: Trace object, or None This is called in a mutually recursive fashion.
def get_page_template(self, **kwargs): """Return the template name used for this request. Only called if *page_template* is not given as a kwarg of *self.as_view*. """ opts = self.object_list.model._meta return '{0}/{1}{2}{3}.html'.format( opts.app_label, ...
Return the template name used for this request. Only called if *page_template* is not given as a kwarg of *self.as_view*.
def get_flat(self): """Gets the weights and returns them as a flat array. Returns: 1D Array containing the flattened weights. """ self._check_sess() return np.concatenate([ v.eval(session=self.sess).flatten() for v in self.variables.values() ...
Gets the weights and returns them as a flat array. Returns: 1D Array containing the flattened weights.
def macronize_tags(self, text): """Return macronized form along with POS tags. E.g. "Gallia est omnis divisa in partes tres," -> [('gallia', 'n-s---fb-', 'galliā'), ('est', 'v3spia---', 'est'), ('omnis', 'a-s---mn-', 'omnis'), ('divisa', 't-prppnn-', 'dīvīsa'), ('in', 'r--------', 'in')...
Return macronized form along with POS tags. E.g. "Gallia est omnis divisa in partes tres," -> [('gallia', 'n-s---fb-', 'galliā'), ('est', 'v3spia---', 'est'), ('omnis', 'a-s---mn-', 'omnis'), ('divisa', 't-prppnn-', 'dīvīsa'), ('in', 'r--------', 'in'), ('partes', 'n-p---fa-', 'partēs'), ...
def disconnect(self, mol): """Break covalent bonds between metals and organic atoms under certain conditions. The algorithm works as follows: - Disconnect N, O, F from any metal. - Disconnect other non-metals from transition metals + Al (but not Hg, Ga, Ge, In, Sn, As, Tl, Pb, Bi, Po)....
Break covalent bonds between metals and organic atoms under certain conditions. The algorithm works as follows: - Disconnect N, O, F from any metal. - Disconnect other non-metals from transition metals + Al (but not Hg, Ga, Ge, In, Sn, As, Tl, Pb, Bi, Po). - For every bond broken, adju...
def apply_time_offset(time, years=0, months=0, days=0, hours=0): """Apply a specified offset to the given time array. This is useful for GFDL model output of instantaneous values. For example, 3 hourly data postprocessed to netCDF files spanning 1 year each will actually have time values that are offs...
Apply a specified offset to the given time array. This is useful for GFDL model output of instantaneous values. For example, 3 hourly data postprocessed to netCDF files spanning 1 year each will actually have time values that are offset by 3 hours, such that the first value is for 1 Jan 03:00 and the ...
def _filter_defs_at_call_sites(self, defs): """ If we are not tracing into the function that are called in a real execution, we should properly filter the defs to account for the behavior of the skipped function at this call site. This function is a WIP. See TODOs inside. :para...
If we are not tracing into the function that are called in a real execution, we should properly filter the defs to account for the behavior of the skipped function at this call site. This function is a WIP. See TODOs inside. :param defs: :return:
def _serialize_input_list(input_value): """Recursively serialize task input list""" input_list = [] for item in input_value: if isinstance(item, list): input_list.append(Task._serialize_input_list(item)) else: if isinstance(item, File): ...
Recursively serialize task input list
def get_ssm_parameter(parameter_name): ''' Get the decrypted value of an SSM parameter Args: parameter_name - the name of the stored parameter of interest Return: Value if allowed and present else None ''' try: response = boto3.client('ssm').get_parameters( ...
Get the decrypted value of an SSM parameter Args: parameter_name - the name of the stored parameter of interest Return: Value if allowed and present else None
def device_status(self): """Return the status of the device as string.""" try: return self.device_status_simple( self.data.get('status').get('status1')) except (KeyError, AttributeError): return self.device_status_simple('')
Return the status of the device as string.
def mutect_to_bed(df): """Convert MuTect results (read into dataframe) to BedTool object Parameters ---------- df : pandas.DataFrame Pandas DataFrame with MuTect results. Returns ------- bt : pybedtools.BedTool BedTool with variants. """ s = (df.contig.astype(str) ...
Convert MuTect results (read into dataframe) to BedTool object Parameters ---------- df : pandas.DataFrame Pandas DataFrame with MuTect results. Returns ------- bt : pybedtools.BedTool BedTool with variants.
def handle_assignattr_type(node, parent): """handle an astroid.assignattr node handle instance_attrs_type """ try: values = set(node.infer()) current = set(parent.instance_attrs_type[node.attrname]) parent.instance_attrs_type[node.attrname] = list(cur...
handle an astroid.assignattr node handle instance_attrs_type
def get_ref_dir(region, coordsys): """ Finds and returns the reference direction for a given HEALPix region string. region : a string describing a HEALPix region coordsys : coordinate system, GAL | CEL """ if region is None: if coordsys == "GAL": ...
Finds and returns the reference direction for a given HEALPix region string. region : a string describing a HEALPix region coordsys : coordinate system, GAL | CEL
def figureStimulus(abf,sweeps=[0]): """ Create a plot of one area of interest of a single sweep. """ stimuli=[2.31250, 2.35270] for sweep in sweeps: abf.setsweep(sweep) for stimulus in stimuli: S1=int(abf.pointsPerSec*stimulus) S2=int(abf.pointsPerSec*(stimul...
Create a plot of one area of interest of a single sweep.
def _group_raw(self, raw_scores, cur=None, level=1): """ Internal recursive method to group raw scores into a cascading score summary. Only top level items are tallied for scores. @param list raw_scores: list of raw scores (Result objects) """ # BEGIN INTERNAL FUNCS ####...
Internal recursive method to group raw scores into a cascading score summary. Only top level items are tallied for scores. @param list raw_scores: list of raw scores (Result objects)
def _update_yaw_and_pitch(self): """ Updates the camera vectors based on the current yaw and pitch """ front = Vector3([0.0, 0.0, 0.0]) front.x = cos(radians(self.yaw)) * cos(radians(self.pitch)) front.y = sin(radians(self.pitch)) front.z = sin(radians(self.yaw)) ...
Updates the camera vectors based on the current yaw and pitch
def convert_type(self, type): """Convert type to SQL """ # Default dialect mapping = { 'any': sa.Text, 'array': None, 'boolean': sa.Boolean, 'date': sa.Date, 'datetime': sa.DateTime, 'duration': None, 'g...
Convert type to SQL
def optimize_branch_length(self, mode='joint', **kwargs): """ Perform optimization for the branch lengths of the entire tree. This method only does a single path and needs to be iterated. **Note** this method assumes that each node stores information about its sequence as numpy....
Perform optimization for the branch lengths of the entire tree. This method only does a single path and needs to be iterated. **Note** this method assumes that each node stores information about its sequence as numpy.array object (node.sequence attribute). Therefore, before calling this...
def x_axis_rotation(theta): """Generates a 3x3 rotation matrix for a rotation of angle theta about the x axis. Parameters ---------- theta : float amount to rotate, in radians Returns ------- :obj:`numpy.ndarray` of float A random...
Generates a 3x3 rotation matrix for a rotation of angle theta about the x axis. Parameters ---------- theta : float amount to rotate, in radians Returns ------- :obj:`numpy.ndarray` of float A random 3x3 rotation matrix.
def promote_deployment_groups(self, id, groups=list()): """ This endpoint is used to promote task groups that have canaries for a deployment. This should be done when the placed canaries are healthy and the rolling upgrade of the remaining allocations should begin. https://www.nomadproje...
This endpoint is used to promote task groups that have canaries for a deployment. This should be done when the placed canaries are healthy and the rolling upgrade of the remaining allocations should begin. https://www.nomadproject.io/docs/http/deployments.html arguments: ...