code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def next(self): """Advance the cursor. This method blocks until the next change document is returned or an unrecoverable error is raised. Raises :exc:`StopAsyncIteration` if this change stream is closed. You can iterate the change stream by calling ``await change_strea...
Advance the cursor. This method blocks until the next change document is returned or an unrecoverable error is raised. Raises :exc:`StopAsyncIteration` if this change stream is closed. You can iterate the change stream by calling ``await change_stream.next()`` repeatedly, or w...
def modelresource_factory(model, resource_class=ModelResource): """ Factory for creating ``ModelResource`` class for given Django model. """ attrs = {'model': model} Meta = type(str('Meta'), (object,), attrs) class_name = model.__name__ + str('Resource') class_attrs = { 'Meta': Met...
Factory for creating ``ModelResource`` class for given Django model.
def validateBusName(n): """ Verifies that the supplied name is a valid DBus Bus name. Throws an L{error.MarshallingError} if the format is invalid @type n: C{string} @param n: A DBus bus name """ try: if '.' not in n: raise Exception('At least two components required') ...
Verifies that the supplied name is a valid DBus Bus name. Throws an L{error.MarshallingError} if the format is invalid @type n: C{string} @param n: A DBus bus name
def prepare_and_execute(self, connection_id, statement_id, sql, max_rows_total=None, first_frame_max_size=None): """Prepares and immediately executes a statement. :param connection_id: ID of the current connection. :param statement_id: ID of the statement to prepare. ...
Prepares and immediately executes a statement. :param connection_id: ID of the current connection. :param statement_id: ID of the statement to prepare. :param sql: SQL query. :param max_rows_total: The maximum number of rows that will b...
def get_electrode_node(self, electrode): """ For a given electrode (e.g. from a config.dat file), return the true node number as in self.nodes['sorted'] """ elec_node_raw = int(self.electrodes[electrode - 1][0]) if(self.header['cutmck']): elec_node = self.node...
For a given electrode (e.g. from a config.dat file), return the true node number as in self.nodes['sorted']
def optimal_variational_posterior( kernel, inducing_index_points, observation_index_points, observations, observation_noise_variance, mean_fn=None, jitter=1e-6, name=None): """Model selection for optimal variational hyperparameters. Given the full training set (p...
Model selection for optimal variational hyperparameters. Given the full training set (parameterized by `observations` and `observation_index_points`), compute the optimal variational location and scale for the VGP. This is based of the method suggested in [Titsias, 2009][1]. Args: kernel: `P...
def _get_handlers(self): """ 获取 action.handlers 添加路径 __conf__.ACTION_DIR_NAME 列表中的 action by ABeen """ # 查找所有 Handler。 members = {} for d in __conf__.ACTION_DIR_NAME: members.update(get_members(d, None, ...
获取 action.handlers 添加路径 __conf__.ACTION_DIR_NAME 列表中的 action by ABeen
def join(self, t2, unique=False): """ Join this triangulation with another. If the points are known to have no duplicates, then set unique=False to skip the testing and duplicate removal """ x_v1 = np.concatenate((self.x, t2.x), axis=0) y_v1 = np.concatenate((self.y, t2....
Join this triangulation with another. If the points are known to have no duplicates, then set unique=False to skip the testing and duplicate removal
def sort_func(self, key): """Sorting logic for `Quantity` objects.""" if key == self._KEYS.VALUE: return 'aaa' if key == self._KEYS.SOURCE: return 'zzz' return key
Sorting logic for `Quantity` objects.
def send_button(recipient): """ Shortcuts are supported page.send(recipient, Template.Buttons("hello", [ {'type': 'web_url', 'title': 'Open Web URL', 'value': 'https://www.oculus.com/en-us/rift/'}, {'type': 'postback', 'title': 'tigger Postback', 'value': 'DEVELOPED_DEFINED_PAYLOAD'}, ...
Shortcuts are supported page.send(recipient, Template.Buttons("hello", [ {'type': 'web_url', 'title': 'Open Web URL', 'value': 'https://www.oculus.com/en-us/rift/'}, {'type': 'postback', 'title': 'tigger Postback', 'value': 'DEVELOPED_DEFINED_PAYLOAD'}, {'type': 'phone_number', 'title': 'Cal...
def proof_req_briefs2req_creds(proof_req: dict, briefs: Union[dict, Sequence[dict]]) -> dict: """ Given a proof request and cred-brief(s), return a requested-creds structure. The proof request must have cred def id restrictions on all requested attribute specifications. :param proof_req: proof request...
Given a proof request and cred-brief(s), return a requested-creds structure. The proof request must have cred def id restrictions on all requested attribute specifications. :param proof_req: proof request :param briefs: credential brief, sequence thereof (as indy-sdk wallet credential search returns), ...
def _put_bucket_lifecycle(self): """Adds bucket lifecycle configuration.""" status = 'deleted' if self.s3props['lifecycle']['enabled']: lifecycle_config = { 'Rules': self.s3props['lifecycle']['lifecycle_rules'] } LOG.debug('Lifecycle Config: %s...
Adds bucket lifecycle configuration.
def vel_grad_avg(self): """Calculate the average velocity gradient (G-bar) of water flowing through the flocculator. :returns: Average velocity gradient (G-bar) :rtype: float * 1 / second """ return ((u.standard_gravity * self.HL) / (pc.viscosity_kinematic(...
Calculate the average velocity gradient (G-bar) of water flowing through the flocculator. :returns: Average velocity gradient (G-bar) :rtype: float * 1 / second
def checkValue(self,value,strict=0): """Check and convert a parameter value. Raises an exception if the value is not permitted for this parameter. Otherwise returns the value (converted to the right type.) """ v = self._coerceValue(value,strict) return self.chec...
Check and convert a parameter value. Raises an exception if the value is not permitted for this parameter. Otherwise returns the value (converted to the right type.)
def get_string(self, betas: List[float], gammas: List[float], samples: int = 100): """ Compute the most probable string. The method assumes you have passed init_betas and init_gammas with your pre-computed angles or you have run the VQE loop to determine the angles. If you have...
Compute the most probable string. The method assumes you have passed init_betas and init_gammas with your pre-computed angles or you have run the VQE loop to determine the angles. If you have not done this you will be returning the output for a random set of angles. :param bet...
def _script_to_har_entry(cls, script, url): ''' Return entry for embed script ''' entry = { 'request': {'url': url}, 'response': {'url': url, 'content': {'text': script}} } cls._set_entry_type(entry, INLINE_SCRIPT_ENTRY) return entry
Return entry for embed script
def resource_to_portal_type(resource): """Converts a resource to a portal type :param resource: Resource name as it is used in the content route :type name: string :returns: Portal type name :rtype: string """ if resource is None: return None resource_mapping = get_resource_map...
Converts a resource to a portal type :param resource: Resource name as it is used in the content route :type name: string :returns: Portal type name :rtype: string
def metric_delete(self, project, metric_name): """API call: delete a metric resource. :type project: str :param project: ID of the project containing the metric. :type metric_name: str :param metric_name: the name of the metric """ path = "projects/%s/metrics/%...
API call: delete a metric resource. :type project: str :param project: ID of the project containing the metric. :type metric_name: str :param metric_name: the name of the metric
def drawItem(self, item, painter, option): """ Draws the inputed item as a bar graph. :param item | <XChartDatasetItem> painter | <QPainter> option | <QStyleOptionGraphicsItem> """ dataset = item.dataset() ...
Draws the inputed item as a bar graph. :param item | <XChartDatasetItem> painter | <QPainter> option | <QStyleOptionGraphicsItem>
def write_jsonl_file(fname, data): """Writes a jsonl file. Args: data: list of json encoded data """ if not isinstance(data, list): print('warning: malformed json data for file', fname) return with open(fname, 'w') as of: for row in data: # TODO: other ma...
Writes a jsonl file. Args: data: list of json encoded data
def fetch(self, category=CATEGORY_COMMIT, from_date=DEFAULT_DATETIME, to_date=DEFAULT_LAST_DATETIME, branches=None, latest_items=False, no_update=False): """Fetch commits. The method retrieves from a Git repository or a log file a list of commits. Commits are returned in the same ...
Fetch commits. The method retrieves from a Git repository or a log file a list of commits. Commits are returned in the same order they were obtained. When `from_date` parameter is given it returns items commited since the given date. The list of `branches` is a list of...
def key_value(self, **kwargs): """ Set fields to be key-value represented. :rtype: Column :Example: >>> new_ds = df.key_value('f1 f2', kv=':', item=',') """ field_name = self.name new_df = copy_df(self) new_df._perform_operation(op.FieldKVConfig...
Set fields to be key-value represented. :rtype: Column :Example: >>> new_ds = df.key_value('f1 f2', kv=':', item=',')
def project_data_source_path(cls, project, data_source): """Return a fully-qualified project_data_source string.""" return google.api_core.path_template.expand( "projects/{project}/dataSources/{data_source}", project=project, data_source=data_source, )
Return a fully-qualified project_data_source string.
def get_time(self, idx): """Return time of data at index `idx` Returns nan if the time is not defined""" # raw data qpi = self.get_qpimage_raw(idx) if "time" in qpi.meta: thetime = qpi.meta["time"] else: thetime = np.nan return thetime
Return time of data at index `idx` Returns nan if the time is not defined
def _generate_prime(bits, rng): "primtive attempt at prime generation" hbyte_mask = pow(2, bits % 8) - 1 while True: # loop catches the case where we increment n into a higher bit-range x = rng.read((bits+7) // 8) if hbyte_mask > 0: x = chr(ord(x[0]) & hbyte_mask) + x[1:]...
primtive attempt at prime generation
def point_lm(self, context): """ Return a lm coordinate array to montblanc """ lm = np.empty(context.shape, context.dtype) # Print the array schema montblanc.log.info(context.array_schema.shape) # Print the space of iteration montblanc.log.info(context.iter_args) ...
Return a lm coordinate array to montblanc
def visit_tuple(self, node): """return an astroid.Tuple node as string""" if len(node.elts) == 1: return "(%s, )" % node.elts[0].accept(self) return "(%s)" % ", ".join(child.accept(self) for child in node.elts)
return an astroid.Tuple node as string
def setup_logging( default_level=logging.INFO, default_path=None, env_key='LOG_CFG', handler_name='console', handlers_dict=None, log_dict=None, config_name=None, splunk_host=None, splunk_port=None, splunk_index=None, splunk_token=No...
setup_logging Setup logging configuration :param default_level: level to log :param default_path: path to config (optional) :param env_key: path to config in this env var :param handler_name: handler name in the config :param handlers_dict: handlers dict :param log_dict: full log dictionar...
def create(self, name, incident_preference): """ This API endpoint allows you to create an alert policy :type name: str :param name: The name of the policy :type incident_preference: str :param incident_preference: Can be PER_POLICY, PER_CONDITION or PER_CON...
This API endpoint allows you to create an alert policy :type name: str :param name: The name of the policy :type incident_preference: str :param incident_preference: Can be PER_POLICY, PER_CONDITION or PER_CONDITION_AND_TARGET :rtype: dict :return: The JSON...
def update_option_value_by_id(cls, option_value_id, option_value, **kwargs): """Update OptionValue Update attributes of OptionValue This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_optio...
Update OptionValue Update attributes of OptionValue This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_option_value_by_id(option_value_id, option_value, async=True) >>> result = thread.get...
def put_connection_filename(filename, working_filename, verbose = False): """ This function reverses the effect of a previous call to get_connection_filename(), restoring the working copy to its original location if the two are different. This function should always be called after calling get_connection_filename...
This function reverses the effect of a previous call to get_connection_filename(), restoring the working copy to its original location if the two are different. This function should always be called after calling get_connection_filename() when the file is no longer in use. During the move operation, this functio...
def _cast(self, value, format=None, **opts): """Optionally apply a format string.""" if format is not None: return datetime.strptime(value, format) return dateutil.parser.parse(value)
Optionally apply a format string.
def get_init_container(self, init_command, init_args, env_vars, context_mounts, persistence_outputs, persistence_data): """Pod init container for sett...
Pod init container for setting outputs path.
async def wait_read(self, message=None, *, timeout=None): """ Awaits for the sent message to be read. Note that receiving a response doesn't imply the message was read, and this action will also trigger even without a response. """ start_time = time.time() future ...
Awaits for the sent message to be read. Note that receiving a response doesn't imply the message was read, and this action will also trigger even without a response.
def to_df(self) -> pd.DataFrame: """Generate shallow :class:`~pandas.DataFrame`. The data matrix :attr:`X` is returned as :class:`~pandas.DataFrame`, where :attr:`obs_names` initializes the index, and :attr:`var_names` the columns. * No annotations are maintained in the returne...
Generate shallow :class:`~pandas.DataFrame`. The data matrix :attr:`X` is returned as :class:`~pandas.DataFrame`, where :attr:`obs_names` initializes the index, and :attr:`var_names` the columns. * No annotations are maintained in the returned object. * The data matrix is densi...
def get_context(self, value): """Ensure `image_rendition` is added to the global context.""" context = super(RenditionAwareStructBlock, self).get_context(value) context['image_rendition'] = self.rendition.\ image_rendition or 'original' return context
Ensure `image_rendition` is added to the global context.
def _get_relation(self, related_model: type, relations: List[str]) -> Tuple[Optional[List[type]], Optional[type]]: """Transform the list of relation to list of class. :param related_mode: The model of the query. :type related_mode: type :param relations: The relation list get from the ...
Transform the list of relation to list of class. :param related_mode: The model of the query. :type related_mode: type :param relations: The relation list get from the `_extract_relations`. :type relations: List[str] :return: Tuple with the list of relations (class) and the se...
def nbopen(filename): """ Open a notebook using the best available server. Returns information about the selected server. """ filename = osp.abspath(filename) home_dir = get_home_dir() server_info = find_best_server(filename) if server_info is not None: print("Using existing se...
Open a notebook using the best available server. Returns information about the selected server.
def process_raw_data(self, fname, max_size): """ Loads data from the input file. :param fname: input file name :param max_size: loads at most 'max_size' samples from the input file, if None loads the entire dataset """ logging.info(f'Processing data from {fna...
Loads data from the input file. :param fname: input file name :param max_size: loads at most 'max_size' samples from the input file, if None loads the entire dataset
def flush_content(self): """ Flushes the cache content. Usage:: >>> cache = Cache() >>> cache.add_content(John="Doe", Luke="Skywalker") True >>> cache.flush_content() True >>> cache {} :return: Method ...
Flushes the cache content. Usage:: >>> cache = Cache() >>> cache.add_content(John="Doe", Luke="Skywalker") True >>> cache.flush_content() True >>> cache {} :return: Method success. :rtype: bool
def from_type_name(cls, typ, name): """Build the object from (type, name).""" # Try aliases first. for k, nt in cls.defined_aliases.items(): if typ is not None and typ != nt.type: continue #print(name, nt.name) if name == nt.name: if len(k) == ...
Build the object from (type, name).
def episode_list(a): """List of all episodes of a season""" html = get_html(ROOT + a.get('href')) div = html.find('div', {'class': "list detail eplist"}) links = [] for tag in div.find_all('a', {'itemprop': "name"}): links.append(tag) return links
List of all episodes of a season
def shake_shake_layer(x, output_filters, num_blocks, stride, hparams): """Builds many sub layers into one full layer.""" for block_num in range(num_blocks): curr_stride = stride if (block_num == 0) else 1 with tf.variable_scope("layer_{}".format(block_num)): x = shake_shake_block(x, output_filters, cu...
Builds many sub layers into one full layer.
def get_flow(self, name): """ Returns a FlowConfig """ config = getattr(self, "flows__{}".format(name)) if not config: raise FlowNotFoundError("Flow not found: {}".format(name)) return FlowConfig(config)
Returns a FlowConfig
def message_archive(self, project_id, category_id=None): """ This will return a summary record for each message in a project. If you specify a category_id, only messages in that category will be returned. (Note that a summary record includes only a few bits of information about a...
This will return a summary record for each message in a project. If you specify a category_id, only messages in that category will be returned. (Note that a summary record includes only a few bits of information about a post, not the complete record.)
def make_report(self, sections_first=True, section_header_params=None): """Create the pdf document with name `self.name + '.pdf'`. Parameters ---------- sections_first : bool If True (default), text and images with sections are presented first and un-sectioned co...
Create the pdf document with name `self.name + '.pdf'`. Parameters ---------- sections_first : bool If True (default), text and images with sections are presented first and un-sectioned content is appended afterword. If False, sectioned text and images will b...
def __replace_all(repls: dict, input: str) -> str: """ Replaces from a string **input** all the occurrences of some symbols according to mapping **repls**. :param dict repls: where #key is the old character and #value is the one to substitute with; :param str input: original string where to apply t...
Replaces from a string **input** all the occurrences of some symbols according to mapping **repls**. :param dict repls: where #key is the old character and #value is the one to substitute with; :param str input: original string where to apply the replacements; :return: *(str)* the string with t...
def date(fmt=None,timestamp=None): "Manejo de fechas (simil PHP)" if fmt=='U': # return timestamp t = datetime.datetime.now() return int(time.mktime(t.timetuple())) if fmt=='c': # return isoformat d = datetime.datetime.fromtimestamp(timestamp) return d.isoformat() if fmt...
Manejo de fechas (simil PHP)
def agg_shape(self, shp, aggregate_by): """ :returns: a shape shp + (T, ...) depending on the tagnames """ return shp + tuple( len(getattr(self, tagname)) - 1 for tagname in aggregate_by)
:returns: a shape shp + (T, ...) depending on the tagnames
def set(self, align='left', font='a', type='normal', width=1, height=1): """ Set text properties """ # Align if align.upper() == "CENTER": self._raw(TXT_ALIGN_CT) elif align.upper() == "RIGHT": self._raw(TXT_ALIGN_RT) elif align.upper() == "LEFT": ...
Set text properties
def create_queue( self, parent, queue, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a queue. Queues created with this method allow tasks to live for a maximum of ...
Creates a queue. Queues created with this method allow tasks to live for a maximum of 31 days. After a task is 31 days old, the task will be deleted regardless of whether it was dispatched or not. WARNING: Using this method may have unintended side effects if you are using an A...
def allow_buttons(self, message="", link=True, back=True): """ Function allows buttons """ self.info_label.set_label(message) self.allow_close_window() if link and self.link is not None: self.link.set_sensitive(True) self.link.show_all() if...
Function allows buttons
def retry(self, func, partition_id, retry_message, final_failure_message, max_retries, host_id): """ Make attempt_renew_lease async call sync. """ loop = asyncio.new_event_loop() loop.run_until_complete(self.retry_async(func, partition_id, retry_message, ...
Make attempt_renew_lease async call sync.
def print_packet_count(): """Print the number of packets grouped by packet name.""" for name in archive.list_packet_names(): packet_count = 0 for group in archive.list_packet_histogram(name): for rec in group.records: packet_count += rec.count print(' {: <40}...
Print the number of packets grouped by packet name.
def gen_send_stdout_url(ip, port): '''Generate send stdout url''' return '{0}:{1}{2}{3}/{4}/{5}'.format(BASE_URL.format(ip), port, API_ROOT_URL, STDOUT_API, NNI_EXP_ID, NNI_TRIAL_JOB_ID)
Generate send stdout url
def install(self): # pragma: no cover """Install/download ssh keys from LDAP for consumption by SSH.""" keys = self.get_keys_from_ldap() for user, ssh_keys in keys.items(): user_dir = API.__authorized_keys_path(user) if not os.path.isdir(user_dir): os.mak...
Install/download ssh keys from LDAP for consumption by SSH.
def delete_async(blob_key, **options): """Async version of delete().""" if not isinstance(blob_key, (basestring, BlobKey)): raise TypeError('Expected blob key, got %r' % (blob_key,)) rpc = blobstore.create_rpc(**options) yield blobstore.delete_async(blob_key, rpc=rpc)
Async version of delete().
def generic_visit(self, node): """ Other nodes are not known and range value neither. """ super(RangeValues, self).generic_visit(node) return self.add(node, UNKNOWN_RANGE)
Other nodes are not known and range value neither.
def runSearchCallSets(self, request): """ Runs the specified SearchCallSetsRequest. """ return self.runSearchRequest( request, protocol.SearchCallSetsRequest, protocol.SearchCallSetsResponse, self.callSetsGenerator)
Runs the specified SearchCallSetsRequest.
def wait_until_not_visible(self, timeout=None): """Search element and wait until it is not visible :param timeout: max time to wait :returns: page element instance """ try: self.utils.wait_until_element_not_visible(self, timeout) except TimeoutException as ex...
Search element and wait until it is not visible :param timeout: max time to wait :returns: page element instance
def get_groups(self, env, token): """Get groups for the given token. :param env: The current WSGI environment dictionary. :param token: Token to validate and return a group string for. :returns: None if the token is invalid or a string containing a comma separated lis...
Get groups for the given token. :param env: The current WSGI environment dictionary. :param token: Token to validate and return a group string for. :returns: None if the token is invalid or a string containing a comma separated list of groups the authenticated user is a membe...
def gc2gdlat(gclat): """Converts geocentric latitude to geodetic latitude using WGS84. Parameters ========== gclat : array_like Geocentric latitude Returns ======= gdlat : ndarray or float Geodetic latitude """ WGS84_e2 = 0.006694379990141317 # WGS84 first eccentr...
Converts geocentric latitude to geodetic latitude using WGS84. Parameters ========== gclat : array_like Geocentric latitude Returns ======= gdlat : ndarray or float Geodetic latitude
def render(filename, obj): """Render a template, maybe mixing in extra variables""" template_path = abspath(filename) env = jinja_env(template_path) template_base = os.path.basename(template_path) try: parsed_content = env.parse(env .loader ...
Render a template, maybe mixing in extra variables
def updateSolutionTerminal(self): ''' Update the terminal period solution. This method should be run when a new AgentType is created or when CRRA changes. Parameters ---------- None Returns ------- None ''' self.solution_terminal...
Update the terminal period solution. This method should be run when a new AgentType is created or when CRRA changes. Parameters ---------- None Returns ------- None
def findSynonymsArray(self, word, num): """ Find "num" number of words closest in similarity to "word". word can be a string or vector representation. Returns an array with two fields word and similarity (which gives the cosine similarity). """ if not isinstance(w...
Find "num" number of words closest in similarity to "word". word can be a string or vector representation. Returns an array with two fields word and similarity (which gives the cosine similarity).
def processDatasetBlocks(self, url, conn, inputdataset, order_counter): """ Utility function, that comapares blocks of a dataset at source and dst and returns an ordered list of blocks not already at dst for migration """ ordered_dict = {} srcblks = self.getSrcBlocks(url,...
Utility function, that comapares blocks of a dataset at source and dst and returns an ordered list of blocks not already at dst for migration
def msg_debug(message): """ Log a debug message :param message: the message to be logged """ if _log_lvl == logging.DEBUG: to_stdout(" (*) {message}".format(message=message), colorf=cyan) if _logger: _logger.debug(message)
Log a debug message :param message: the message to be logged
def list_rocs_files(url=ROCS_URL): """Gets the contents of the given url. """ soup = BeautifulSoup(get(url)) if not url.endswith('/'): url += '/' files = [] for elem in soup.findAll('a'): if elem['href'].startswith('?'): continue if elem.string.lower() == 'par...
Gets the contents of the given url.
def get_subpackages(app, module): """Get all subpackages for the given module/package :param app: the sphinx app :type app: :class:`sphinx.application.Sphinx` :param module: the module to query or module path :type module: module | str :returns: list of packages names :rtype: list :rais...
Get all subpackages for the given module/package :param app: the sphinx app :type app: :class:`sphinx.application.Sphinx` :param module: the module to query or module path :type module: module | str :returns: list of packages names :rtype: list :raises: TypeError
def combine_or(matcher, *more_matchers): """Combines more than one matcher together (first that matches wins).""" def matcher(cause): for sub_matcher in itertools.chain([matcher], more_matchers): cause_cls = sub_matcher(cause) if cause_cls is not None: return cau...
Combines more than one matcher together (first that matches wins).
def archive_query_interval(self, _from, to): ''' :param _from: Start of interval (int) (inclusive) :param to: End of interval (int) (exclusive) :raises: IOError ''' with self.session as session: table = self.tables.archive try: res...
:param _from: Start of interval (int) (inclusive) :param to: End of interval (int) (exclusive) :raises: IOError
def _get_submodules(app, module): """Get all submodules for the given module/package :param app: the sphinx app :type app: :class:`sphinx.application.Sphinx` :param module: the module to query or module path :type module: module | str :returns: list of module names and boolean whether its a pac...
Get all submodules for the given module/package :param app: the sphinx app :type app: :class:`sphinx.application.Sphinx` :param module: the module to query or module path :type module: module | str :returns: list of module names and boolean whether its a package :rtype: list :raises: TypeEr...
def raise_server_error(self): """ Raise errors encountered by the server. """ if self.server and self.server.error: try: if capybara.raise_server_errors: raise self.server.error finally: self.server.reset_error()
Raise errors encountered by the server.
def _parse_bro_header(self, logfile): """This method tries to parse the Bro log header section. Note: My googling is failing me on the documentation on the format, so just making a lot of assumptions and skipping some shit. Assumption 1: The delimeter is a tab. Assumption 2: Typ...
This method tries to parse the Bro log header section. Note: My googling is failing me on the documentation on the format, so just making a lot of assumptions and skipping some shit. Assumption 1: The delimeter is a tab. Assumption 2: Types are either time, string, int or float ...
def parse(self, message, schema): """Parse message according to schema. `message` should already be validated against the given schema. See :ref:`schemadef` for more information. Args: message (dict): message data to parse. schema (str): valid message schema. ...
Parse message according to schema. `message` should already be validated against the given schema. See :ref:`schemadef` for more information. Args: message (dict): message data to parse. schema (str): valid message schema. Returns: (dict): parsed mes...
def replace_group(self, index, func_grp, strategy, bond_order=1, graph_dict=None, strategy_params=None, reorder=True, extend_structure=True): """ Builds off of Molecule.substitute and MoleculeGraph.substitute_group to replace a functional group in self...
Builds off of Molecule.substitute and MoleculeGraph.substitute_group to replace a functional group in self.molecule with a functional group. This method also amends self.graph to incorporate the new functional group. TODO: Figure out how to replace into a ring structure. :param...
def _AddOption(self, name): """Add an option to this Value. Args: name: (str), the name of the Option to add. Raises: TextFSMTemplateError: If option is already present or the option does not exist. """ # Check for duplicate option declaration if name in [option.name for o...
Add an option to this Value. Args: name: (str), the name of the Option to add. Raises: TextFSMTemplateError: If option is already present or the option does not exist.
def authenticate(self, verify=True): """ Creates an authenticated and internal oauth2 handler needed for \ queries to Twitter and verifies credentials if needed. If ``verify`` \ is true, it also checks if the user credentials are valid. \ The **default** value is *True* :param...
Creates an authenticated and internal oauth2 handler needed for \ queries to Twitter and verifies credentials if needed. If ``verify`` \ is true, it also checks if the user credentials are valid. \ The **default** value is *True* :param verify: boolean variable to \ directly c...
def get(self): """API endpoint to get validators set. Return: A JSON string containing the validator set of the current node. """ pool = current_app.config['bigchain_pool'] with pool() as bigchain: validators = bigchain.get_validators() return ...
API endpoint to get validators set. Return: A JSON string containing the validator set of the current node.
def breakfast(self, message="Breakfast is ready", shout: bool = False): """Say something in the morning""" return self.helper.output(message, shout)
Say something in the morning
def list_resources(self, session, query='?*::INSTR'): """Returns a tuple of all connected devices matching query. :param query: regular expression used to match devices. """ # For each session type, ask for the list of connected resources and merge them into a single list. res...
Returns a tuple of all connected devices matching query. :param query: regular expression used to match devices.
def set_maxsize(self, maxsize, **kwargs): """ Set maxsize. This involves creating a new cache and transferring the items. """ new_cache = self._get_cache_impl(self.impl_name, maxsize, **kwargs) self._populate_new_cache(new_cache) self.cache = new_cache
Set maxsize. This involves creating a new cache and transferring the items.
def _get_combined_keywords(_keywords, split_text): """ :param keywords:dict of keywords:scores :param split_text: list of strings :return: combined_keywords:list """ result = [] _keywords = _keywords.copy() len_text = len(split_text) for i in range(len_text): word = _strip_wo...
:param keywords:dict of keywords:scores :param split_text: list of strings :return: combined_keywords:list
def edit_form(self, obj): """Customize edit form.""" form = super(OAISetModelView, self).edit_form(obj) del form.spec return form
Customize edit form.
def _get_filepaths(self): """Filters list of file paths to remove non-included, remove excluded files and concatenate full paths.""" self._printer(str(self.__len__()) + " file paths have been parsed in " + str(self.timer.end)) if self._hash_files: return pool_hash(self.filepaths) ...
Filters list of file paths to remove non-included, remove excluded files and concatenate full paths.
def get_outline(ds, t_srs=None, scale=1.0, simplify=False, convex=False): """Generate outline of unmasked values in input raster get_outline is an attempt to reproduce the PostGIS Raster ST_MinConvexHull function Could potentially do the following: Extract random pts from unmasked elements, get indices, R...
Generate outline of unmasked values in input raster get_outline is an attempt to reproduce the PostGIS Raster ST_MinConvexHull function Could potentially do the following: Extract random pts from unmasked elements, get indices, Run scipy convex hull, Convert hull indices to mapped coords See this: http:/...
def visit_Try(self, node: ast.Try) -> Optional[ast.AST]: """Eliminate dead code from except try bodies.""" new_node = self.generic_visit(node) assert isinstance(new_node, ast.Try) return ast.copy_location( ast.Try( body=_filter_dead_code(new_node.body), ...
Eliminate dead code from except try bodies.
def _default_ns_prefix(nsmap): """ XML doc may have several prefix:namespace_url pairs, can also specify a namespace_url as default, tags in that namespace don't need a prefix NOTE: we rely on default namespace also present in prefixed form, I'm not sure if this is an XML certainty or a quirk of...
XML doc may have several prefix:namespace_url pairs, can also specify a namespace_url as default, tags in that namespace don't need a prefix NOTE: we rely on default namespace also present in prefixed form, I'm not sure if this is an XML certainty or a quirk of the eBay WSDLs in our case the WSDL c...
def pick_kmersize(fq): """ pick an appropriate kmer size based off of https://www.biostars.org/p/201474/ tl;dr version: pick 31 unless the reads are very small, if not then guess that readlength / 2 is about right. """ if bam.is_bam(fq): readlength = bam.estimate_read_length(fq) else...
pick an appropriate kmer size based off of https://www.biostars.org/p/201474/ tl;dr version: pick 31 unless the reads are very small, if not then guess that readlength / 2 is about right.
def __write(self, thePath, theData): """ Write data to a file. @type thePath: str @param thePath: The file path. @type theData: str @param theData: The data to write. """ fd = open(thePath, "wb") fd.write(theData) fd.c...
Write data to a file. @type thePath: str @param thePath: The file path. @type theData: str @param theData: The data to write.
def fkapply(models,pool,fn,missing_fn,(nombre,pkey,field),*args): "wrapper for do_* funcs to call process_* with missing handler. Unpacks the FieldKey." if (nombre,pkey) in models: return fn(pool,models[nombre,pkey],field,*args) else: return missing_fn(pool,field,*args) if missing_fn else ['missing']
wrapper for do_* funcs to call process_* with missing handler. Unpacks the FieldKey.
def mask(self, mask): """ The mask values. Must be an array or a boolean scalar.""" check_class(mask, (np.ndarray, bool, np.bool_)) if isinstance(mask, (bool, np.bool_)): self._mask = bool(mask) else: self._mask = mask
The mask values. Must be an array or a boolean scalar.
def dtype_repr(dtype): """Stringify ``dtype`` for ``repr`` with default for int and float.""" dtype = np.dtype(dtype) if dtype == np.dtype(int): return "'int'" elif dtype == np.dtype(float): return "'float'" elif dtype == np.dtype(complex): return "'complex'" elif dtype.s...
Stringify ``dtype`` for ``repr`` with default for int and float.
def inject_params(model_name: str) -> ListenerParams: """Set the global listener params to a saved model""" params_file = model_name + '.params' try: with open(params_file) as f: pr.__dict__.update(compatibility_params, **json.load(f)) except (OSError, ValueError, TypeError): ...
Set the global listener params to a saved model
def sync_folder_to_container(self, folder_path, container, delete=False, include_hidden=False, ignore=None, ignore_timestamps=False, object_prefix="", verbose=False): """ Compares the contents of the specified folder, and checks to make sure that the corresponding object ...
Compares the contents of the specified folder, and checks to make sure that the corresponding object is present in the specified container. If there is no remote object matching the local file, it is created. If a matching object exists, the etag is examined to determine if the object in...
def check_client_key(self, client_key): """Check that the client key only contains safe characters and is no shorter than lower and no longer than upper. """ lower, upper = self.client_key_length return (set(client_key) <= self.safe_characters and lower <= len(cli...
Check that the client key only contains safe characters and is no shorter than lower and no longer than upper.
def parse_args(args): """ Parse command line parameters :param args: command line parameters as list of strings :return: command line parameters as :obj:`argparse.Namespace` """ parser = argparse.ArgumentParser( description="Just a Hello World demonstration") parser.add_argument( ...
Parse command line parameters :param args: command line parameters as list of strings :return: command line parameters as :obj:`argparse.Namespace`
def query(self, query_str, *query_args, **query_options): """ run a raw query on the db query_str -- string -- the query to run *query_args -- if the query_str is a formatting string, pass the values in this **query_options -- any query options can be passed in by using key=val ...
run a raw query on the db query_str -- string -- the query to run *query_args -- if the query_str is a formatting string, pass the values in this **query_options -- any query options can be passed in by using key=val syntax
def _yield_week_day(self, enumeration=False): """A helper function to reduce the number of nested loops. Parameters ---------- enumeration Whether or not to wrap the days in enumerate(). Yields ------- tuple A tup...
A helper function to reduce the number of nested loops. Parameters ---------- enumeration Whether or not to wrap the days in enumerate(). Yields ------- tuple A tuple with (week, day_index, day) or (week, day), ...
def Similarity(self, value=None): # pylint: disable=C0103 """Constructor for new default Similarities.""" if value is None: value = 0.0 return Similarity(value, threshold=self.threshold)
Constructor for new default Similarities.