code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def insert(self, resource, value): """insert(resource, value) Insert a resource entry into the database. RESOURCE is a string and VALUE can be any Python value. """ # Split res into components and bindings parts = resource_parts_re.split(resource) # If the la...
insert(resource, value) Insert a resource entry into the database. RESOURCE is a string and VALUE can be any Python value.
def isPointVisible(self, x, y): """ Checks if a point is visible on any monitor. """ class POINT(ctypes.Structure): _fields_ = [("x", ctypes.c_long), ("y", ctypes.c_long)] pt = POINT() pt.x = x pt.y = y MONITOR_DEFAULTTONULL = 0 hmon = self._user32.Mon...
Checks if a point is visible on any monitor.
def setInverted(self, state): """ Sets whether or not to invert the check state for collapsing. :param state | <bool> """ collapsed = self.isCollapsed() self._inverted = state if self.isCollapsible(): self.setCollapsed(collapsed)
Sets whether or not to invert the check state for collapsing. :param state | <bool>
def to_profile_info(self, serialize_credentials=False): """Unlike to_project_config, this dict is not a mirror of any existing on-disk data structure. It's used when creating a new profile from an existing one. :param serialize_credentials bool: If True, serialize the credentials. ...
Unlike to_project_config, this dict is not a mirror of any existing on-disk data structure. It's used when creating a new profile from an existing one. :param serialize_credentials bool: If True, serialize the credentials. Otherwise, the Credentials object will be copied. :r...
def Diag(a): """ Diag op. """ r = np.zeros(2 * a.shape, dtype=a.dtype) for idx, v in np.ndenumerate(a): r[2 * idx] = v return r,
Diag op.
def failure_raiser(*validation_func, # type: ValidationFuncs **kwargs ): # type: (...) -> Callable """ This function is automatically used if you provide a tuple `(<function>, <msg>_or_<Failure_type>)`, to any of the methods in this page or to one of the `valid8` ...
This function is automatically used if you provide a tuple `(<function>, <msg>_or_<Failure_type>)`, to any of the methods in this page or to one of the `valid8` decorators. It transforms the provided `<function>` into a failure raiser, raising a subclass of `Failure` in case of failure (either not returning `Tr...
def _convert_to_tensor(value, dtype=None, dtype_hint=None, name=None): """Converts the given `value` to a (structure of) `Tensor`. This function converts Python objects of various types to a (structure of) `Tensor` objects. It accepts `Tensor` objects, numpy arrays, Python lists, and Python scalars. For exampl...
Converts the given `value` to a (structure of) `Tensor`. This function converts Python objects of various types to a (structure of) `Tensor` objects. It accepts `Tensor` objects, numpy arrays, Python lists, and Python scalars. For example: Args: value: An object whose structure matches that of `dtype ` an...
def save_to_file(self, path, filename, **params): """ Saves binary content to a file with name filename. filename should include the appropriate file extension, such as .xlsx or .txt, e.g., filename = 'sample.xlsx'. Useful for downloading .xlsx files. """ url = e...
Saves binary content to a file with name filename. filename should include the appropriate file extension, such as .xlsx or .txt, e.g., filename = 'sample.xlsx'. Useful for downloading .xlsx files.
def time(host=None, port=None, db=None, password=None): ''' Return the current server UNIX time in seconds CLI Example: .. code-block:: bash salt '*' redis.time ''' server = _connect(host, port, db, password) return server.time()[0]
Return the current server UNIX time in seconds CLI Example: .. code-block:: bash salt '*' redis.time
def K(self, parm): """ Returns the Gram Matrix Parameters ---------- parm : np.ndarray Parameters for the Gram Matrix Returns ---------- - Gram Matrix (np.ndarray) """ return ARD_K_matrix(self.X, parm) + np.identity(self.X.shape[0])*(...
Returns the Gram Matrix Parameters ---------- parm : np.ndarray Parameters for the Gram Matrix Returns ---------- - Gram Matrix (np.ndarray)
def _astorestr(ins): ''' Stores a string value into a memory address. It copies content of 2nd operand (string), into 1st, reallocating dynamic memory for the 1st str. These instruction DOES ALLOW immediate strings for the 2nd parameter, starting with '#'. ''' output = _addr(ins.quad[1]) op ...
Stores a string value into a memory address. It copies content of 2nd operand (string), into 1st, reallocating dynamic memory for the 1st str. These instruction DOES ALLOW immediate strings for the 2nd parameter, starting with '#'.
def apply(self, event = None): """Before self.onOk closes the window, it calls this function to sync the config changes from the GUI back to self.config.""" for section in self.config.sections(): # Run through the sections to check all the option values: for option, o in self.config.config[section].items(...
Before self.onOk closes the window, it calls this function to sync the config changes from the GUI back to self.config.
def send_status_response(environ, start_response, e, add_headers=None, is_head=False): """Start a WSGI response for a DAVError or status code.""" status = get_http_status_string(e) headers = [] if add_headers: headers.extend(add_headers) # if 'keep-alive' in environ.get('HTTP_CONNECTION',...
Start a WSGI response for a DAVError or status code.
def spec_formatter(cls, spec): " Formats the elements of an argument set appropriately" return type(spec)((k, str(v)) for (k,v) in spec.items())
Formats the elements of an argument set appropriately
def loadGmesh(filename, c="gold", alpha=1, wire=False, bc=None): """Reads a `gmesh` file format. Return an ``Actor(vtkActor)`` object.""" if not os.path.exists(filename): colors.printc("~noentry Error in loadGmesh: Cannot find", filename, c=1) return None f = open(filename, "r") lines =...
Reads a `gmesh` file format. Return an ``Actor(vtkActor)`` object.
def _maybe_assert_valid_concentration(self, concentration, validate_args): """Checks the validity of the concentration parameter.""" if not validate_args: return concentration return distribution_util.with_dependencies([ assert_util.assert_positive( concentration, message="Concentr...
Checks the validity of the concentration parameter.
def _create_relational_field(self, attr, options): """Creates the form element for working with entity relationships.""" options['entity_class'] = attr.py_type options['allow_empty'] = not attr.is_required return EntityField, options
Creates the form element for working with entity relationships.
def format(self, indent_level, indent_size=4): """Format this verifier Returns: string: A formatted string """ name = self.format_name('Literal', indent_size) if self.long_desc is not None: name += '\n' name += self.wrap_lines('value: %s\n' % s...
Format this verifier Returns: string: A formatted string
def after_request(self, fn): """ Register a function to be run after each request. Your function must take one parameter, an instance of :attr:`response_class` and return a new response object or the same (see :meth:`process_response`). As of Flask 0.7 this function mig...
Register a function to be run after each request. Your function must take one parameter, an instance of :attr:`response_class` and return a new response object or the same (see :meth:`process_response`). As of Flask 0.7 this function might not be executed at the end of the requ...
def state_create(history_id_key, table_name, collision_checker, always_set=[]): """ Decorator for the check() method on state-creating operations. Makes sure that: * there is a __preorder__ field set, which contains the state-creating operation's associated preorder * there is a __table__ field set,...
Decorator for the check() method on state-creating operations. Makes sure that: * there is a __preorder__ field set, which contains the state-creating operation's associated preorder * there is a __table__ field set, which contains the table into which to insert this state into * there is a __history_id...
def parse_match_settings(match_settings, config: ConfigObject): """ Parses the matching settings modifying the match settings object. :param match_settings: :param config: :return: """ match_settings.game_mode = config.get(MATCH_CONFIGURATION_HEADER, GAME_MODE) match_settings.game_map =...
Parses the matching settings modifying the match settings object. :param match_settings: :param config: :return:
def com_google_fonts_check_os2_metrics_match_hhea(ttFont): """Checking OS/2 Metrics match hhea Metrics. OS/2 and hhea vertical metric values should match. This will produce the same linespacing on Mac, GNU+Linux and Windows. Mac OS X uses the hhea values. Windows uses OS/2 or Win, depending on the OS or fsS...
Checking OS/2 Metrics match hhea Metrics. OS/2 and hhea vertical metric values should match. This will produce the same linespacing on Mac, GNU+Linux and Windows. Mac OS X uses the hhea values. Windows uses OS/2 or Win, depending on the OS or fsSelection bit value.
def missing_whitespace_around_operator(logical_line, tokens): r"""Surround operators with a single space on either side. - Always surround these binary operators with a single space on either side: assignment (=), augmented assignment (+=, -= etc.), comparisons (==, <, >, !=, <=, >=, in, not in, is...
r"""Surround operators with a single space on either side. - Always surround these binary operators with a single space on either side: assignment (=), augmented assignment (+=, -= etc.), comparisons (==, <, >, !=, <=, >=, in, not in, is, is not), Booleans (and, or, not). - If operators with...
def clear(self): """ Clear everything :rtype: Query """ self._filters = [] self._order_by = OrderedDict() self._selects = set() self._negation = False self._attribute = None self._chain = None self._search = None return self
Clear everything :rtype: Query
def predictions_variance(df, filepath=None): """ Plots the mean variance prediction for each readout Parameters ---------- df: `pandas.DataFrame`_ DataFrame with columns starting with `VAR:` filepath: str Absolute path to a folder where to write the plots Returns ----...
Plots the mean variance prediction for each readout Parameters ---------- df: `pandas.DataFrame`_ DataFrame with columns starting with `VAR:` filepath: str Absolute path to a folder where to write the plots Returns ------- plot Generated plot .. _pandas.Data...
def _code_line(self, line): """Add a code line.""" assert self._containers container = self._containers[-1] # Handle extra spaces. text = line while text: if text.startswith(' '): r = re.match(r'(^ +)', text) n = len(r.group(1)...
Add a code line.
def resolve_aliases(self, chunks): ''' Preserve backward compatibility by rewriting the 'state' key in the low chunks if it is using a legacy type. ''' for idx, _ in enumerate(chunks): new_state = self.aliases.get(chunks[idx]['state']) if new_state is not ...
Preserve backward compatibility by rewriting the 'state' key in the low chunks if it is using a legacy type.
def _unordered_iter(self): """iterator for results *as they arrive*, on FCFS basis, ignoring submission order.""" try: rlist = self.get(0) except error.TimeoutError: pending = set(self.msg_ids) while pending: try: self._clie...
iterator for results *as they arrive*, on FCFS basis, ignoring submission order.
def is_kanji(data): """\ Returns if the `data` can be encoded in "kanji" mode. :param bytes data: The data to check. :rtype: bool """ data_len = len(data) if not data_len or data_len % 2: return False if _PY2: data = (ord(c) for c in data) data_iter = iter(data) ...
\ Returns if the `data` can be encoded in "kanji" mode. :param bytes data: The data to check. :rtype: bool
def supported_alleles(self): """ Alleles for which predictions can be made. Returns ------- list of string """ if 'supported_alleles' not in self._cache: result = set(self.allele_to_allele_specific_models) if self.allele_to_fixed_l...
Alleles for which predictions can be made. Returns ------- list of string
def map_prop_value_as_index(prp, lst): """ Returns the given prop of each item in the list :param prp: :param lst: :return: """ return from_pairs(map(lambda item: (prop(prp, item), item), lst))
Returns the given prop of each item in the list :param prp: :param lst: :return:
def extend_right_to(self, window, max_size): """Adjust the size to make our window end where the right window begins, but don't get larger than max_size""" self.size = min(self.size + (window.ofs - self.ofs_end()), max_size)
Adjust the size to make our window end where the right window begins, but don't get larger than max_size
def get_facts(self): """Return a set of facts from the devices.""" # default values. vendor = u'Cisco' uptime = -1 serial_number, fqdn, os_version, hostname, domain_name = ('Unknown',) * 5 # obtain output from device show_ver = self._send_command('show version') ...
Return a set of facts from the devices.
def solvedbi_sm(ah, rho, b, c=None, axis=4): r""" Solve a diagonal block linear system with a scaled identity term using the Sherman-Morrison equation. The solution is obtained by independently solving a set of linear systems of the form (see :cite:`wohlberg-2016-efficient`) .. math:: (\...
r""" Solve a diagonal block linear system with a scaled identity term using the Sherman-Morrison equation. The solution is obtained by independently solving a set of linear systems of the form (see :cite:`wohlberg-2016-efficient`) .. math:: (\rho I + \mathbf{a} \mathbf{a}^H ) \; \mathbf{x} =...
def gridsearch(self, X, y, weights=None, return_scores=False, keep_best=True, objective='auto', progress=True, **param_grids): """ Performs a grid search over a space of parameters for a given objective Warnings -------- ``gridsearch...
Performs a grid search over a space of parameters for a given objective Warnings -------- ``gridsearch`` is lazy and will not remove useless combinations from the search space, eg. >>> n_splines=np.arange(5,10), fit_splines=[True, False] will result in 10 loops...
def copy_path_flat(self): """Return a flattened copy of the current path This method is like :meth:`copy_path` except that any curves in the path will be approximated with piecewise-linear approximations, (accurate to within the current tolerance value, see :meth:`set_to...
Return a flattened copy of the current path This method is like :meth:`copy_path` except that any curves in the path will be approximated with piecewise-linear approximations, (accurate to within the current tolerance value, see :meth:`set_tolerance`). That is, t...
def default_ubuntu_tr(mod): """ Default translation function for Ubuntu based systems """ pkg = 'python-%s' % mod.lower() py2pkg = pkg py3pkg = 'python3-%s' % mod.lower() return (pkg, py2pkg, py3pkg)
Default translation function for Ubuntu based systems
def run( draco_query: List[str], constants: Dict[str, str] = None, files: List[str] = None, relax_hard=False, silence_warnings=False, debug=False, clear_cache=False, ) -> Optional[Result]: """ Run clingo to compute a completion of a partial spec or violations. """ # Clear file cache...
Run clingo to compute a completion of a partial spec or violations.
def read(self, page): """Send a READ command to retrieve data from the tag. The *page* argument specifies the offset in multiples of 4 bytes (i.e. page number 1 will return bytes 4 to 19). The data returned is a byte array of length 16 or None if the block is outside the readabl...
Send a READ command to retrieve data from the tag. The *page* argument specifies the offset in multiples of 4 bytes (i.e. page number 1 will return bytes 4 to 19). The data returned is a byte array of length 16 or None if the block is outside the readable memory range. Command ...
def grid_linspace(bounds, count): """ Return a grid spaced inside a bounding box with edges spaced using np.linspace. Parameters --------- bounds: (2,dimension) list of [[min x, min y, etc], [max x, max y, etc]] count: int, or (dimension,) int, number of samples per side Returns -----...
Return a grid spaced inside a bounding box with edges spaced using np.linspace. Parameters --------- bounds: (2,dimension) list of [[min x, min y, etc], [max x, max y, etc]] count: int, or (dimension,) int, number of samples per side Returns ------- grid: (n, dimension) float, points in t...
def get_scaled_cutout_basic(self, x1, y1, x2, y2, scale_x, scale_y, method='basic'): """Extract a region of the image defined by corners (x1, y1) and (x2, y2) and scale it by scale factors (scale_x, scale_y). `method` describes the method of interpolation used, w...
Extract a region of the image defined by corners (x1, y1) and (x2, y2) and scale it by scale factors (scale_x, scale_y). `method` describes the method of interpolation used, where the default "basic" is nearest neighbor.
def polygon(self): """Returns an OGR Geometry for this envelope.""" ring = ogr.Geometry(ogr.wkbLinearRing) for coord in self.ll, self.lr, self.ur, self.ul, self.ll: ring.AddPoint_2D(*coord) polyg = ogr.Geometry(ogr.wkbPolygon) polyg.AddGeometryDirectly(ring) r...
Returns an OGR Geometry for this envelope.
def start(self): ''' Listen to messages and publish them. ''' # counter metrics for messages c_logs_ingested = Counter( 'napalm_logs_listener_logs_ingested', 'Count of ingested log messages', ['listener_type', 'address', 'port'], ) ...
Listen to messages and publish them.
def read_file_1st_col_only(fname): """ read a CSV file (ref_classes.csv) and return the list of names """ lst = [] with open(fname, 'r') as f: _ = f.readline() # read the header and ignore it for line in f: lst.append(line.split(',')[0]) return lst
read a CSV file (ref_classes.csv) and return the list of names
def complete(request, provider): """ After first step of net authentication, we must validate the response. If everything is ok, we must do the following: 1. If user is already authenticated: a. Try to login him again (strange variation but we must take it to account). ...
After first step of net authentication, we must validate the response. If everything is ok, we must do the following: 1. If user is already authenticated: a. Try to login him again (strange variation but we must take it to account). b. Create new netID record in database. ...
def sort_by_name(names): """Sort by last name, uniquely.""" def last_name_key(full_name): parts = full_name.split(' ') if len(parts) == 1: return full_name.upper() last_first = parts[-1] + ' ' + ' '.join(parts[:-1]) return last_first.upper() return sorted(set(na...
Sort by last name, uniquely.
def pairinplace(args): """ %prog pairinplace bulk.fastq Pair up the records in bulk.fastq by comparing the names for adjancent records. If they match, print to bulk.pairs.fastq, else print to bulk.frags.fastq. """ from jcvi.utils.iter import pairwise p = OptionParser(pairinplace.__doc_...
%prog pairinplace bulk.fastq Pair up the records in bulk.fastq by comparing the names for adjancent records. If they match, print to bulk.pairs.fastq, else print to bulk.frags.fastq.
def process_strings(self, string, docstrings=False): """Process escapes.""" m = RE_STRING_TYPE.match(string) stype = self.get_string_type(m.group(1) if m.group(1) else '') if not self.match_string(stype) and not docstrings: return '', False is_bytes = 'b' in stype ...
Process escapes.
def user_twitter_list_bag_of_words(twitter_list_corpus, sent_tokenize, _treebank_word_tokenize, tagger, lemmatizer, lemmatize, stopset, first_cap_re, all_cap_re, digits_punctuation_whitespace_re, ...
Extract a bag-of-words for a corpus of Twitter lists pertaining to a Twitter user. Inputs: - twitter_list_corpus: A python list of Twitter lists in json format. - lemmatizing: A string containing one of the following: "porter", "snowball" or "wordnet". Output: - bag_of_words: A bag-of-words in pyt...
def get_user(self, username): """ Get the user details from MAM. """ cmd = ["glsuser", "-u", username, "--raw"] results = self._read_output(cmd) if len(results) == 0: return None elif len(results) > 1: logger.error( "Command returned multi...
Get the user details from MAM.
def _collapse_preconditions(base_preconditions: List[List[Contract]], bases_have_func: bool, preconditions: List[List[Contract]], func: Callable[..., Any]) -> List[List[Contract]]: """ Collapse function preconditions with the preconditions collected from the base classes. :param...
Collapse function preconditions with the preconditions collected from the base classes. :param base_preconditions: preconditions collected from the base classes (grouped by base class) :param bases_have_func: True if one of the base classes has the function :param preconditions: preconditions of the functi...
def get_signin_url(self, service='ec2'): """ Get the URL where IAM users can use their login profile to sign in to this account's console. :type service: string :param service: Default service to go to in the console. """ alias = self.get_account_alias() ...
Get the URL where IAM users can use their login profile to sign in to this account's console. :type service: string :param service: Default service to go to in the console.
def _load_lib(): """Load LightGBM library.""" lib_path = find_lib_path() if len(lib_path) == 0: return None lib = ctypes.cdll.LoadLibrary(lib_path[0]) lib.LGBM_GetLastError.restype = ctypes.c_char_p return lib
Load LightGBM library.
def cast_from_bunq_response(cls, bunq_response): """ :type bunq_response: BunqResponse """ return cls( bunq_response.value, bunq_response.headers, bunq_response.pagination )
:type bunq_response: BunqResponse
def buildWorkbenchWithLauncher(): """Builds a workbench. The workbench has a launcher with all of the default tools. The launcher will be displayed on the workbench. """ workbench = ui.Workbench() tools = [exercises.SearchTool()] launcher = ui.Launcher(workbench, tools) workbench.disp...
Builds a workbench. The workbench has a launcher with all of the default tools. The launcher will be displayed on the workbench.
def not_next(e): """ Create a PEG function for negative lookahead. """ def match_not_next(s, grm=None, pos=0): try: e(s, grm, pos) except PegreError as ex: return PegreResult(s, Ignore, (pos, pos)) else: raise PegreError('Negative lookahead fai...
Create a PEG function for negative lookahead.
def get_config_value(name, fallback=None): """Gets a config by name. In the case where the config name is not found, will use fallback value.""" cli_config = CLIConfig(SF_CLI_CONFIG_DIR, SF_CLI_ENV_VAR_PREFIX) return cli_config.get('servicefabric', name, fallback)
Gets a config by name. In the case where the config name is not found, will use fallback value.
def get_indexed_node(manager, prop, value, node_type='Node', lookup_func='CONTAINS', legacy=True): """ :param manager: Neo4jDBSessionManager :param prop: Indexed property :param value: Indexed value :param node_type: Label used for index :param lookup_func: STARTS WITH | CONTAINS | ENDS WITH ...
:param manager: Neo4jDBSessionManager :param prop: Indexed property :param value: Indexed value :param node_type: Label used for index :param lookup_func: STARTS WITH | CONTAINS | ENDS WITH :param legacy: Backwards compatibility :type manager: Neo4jDBSessionManager :type prop: str :type...
def format_request_email_title(increq, **ctx): """Format the email message title for inclusion request notification. :param increq: Inclusion request object for which the request is made. :type increq: `invenio_communities.models.InclusionRequest` :param ctx: Optional extra context parameters passed to...
Format the email message title for inclusion request notification. :param increq: Inclusion request object for which the request is made. :type increq: `invenio_communities.models.InclusionRequest` :param ctx: Optional extra context parameters passed to formatter. :type ctx: dict. :returns: Email m...
def _init_grps(code2nt): """Return list of groups in same order as in code2nt""" seen = set() seen_add = seen.add groups = [nt.group for nt in code2nt.values()] return [g for g in groups if not (g in seen or seen_add(g))]
Return list of groups in same order as in code2nt
def revoke_auth(preserve_minion_cache=False): ''' The minion sends a request to the master to revoke its own key. Note that the minion session will be revoked and the minion may not be able to return the result of this command back to the master. If the 'preserve_minion_cache' flag is set to True, ...
The minion sends a request to the master to revoke its own key. Note that the minion session will be revoked and the minion may not be able to return the result of this command back to the master. If the 'preserve_minion_cache' flag is set to True, the master cache for this minion will not be removed. ...
def setup_menu(self): """Setup context menu.""" copy_action = create_action(self, _('Copy'), shortcut=keybinding('Copy'), icon=ima.icon('editcopy'), triggered=self.copy, ...
Setup context menu.
def boll(self, n, dev, array=False): """布林通道""" mid = self.sma(n, array) std = self.std(n, array) up = mid + std * dev down = mid - std * dev return up, down
布林通道
def date_to_epiweek(date=datetime.date.today()) -> Epiweek: """ Convert python date to Epiweek """ year = date.year start_dates = list(map(_start_date_of_year, [year - 1, year, year + 1])) start_date = start_dates[1] if start_dates[1] > date: start_date = start_dates[0] elif da...
Convert python date to Epiweek
def eth_sendTransaction(self, from_, to=None, gas=None, gas_price=None, value=None, data=None, nonce=None): """https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sendtransaction :param from_: From account address :type from_: str ...
https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sendtransaction :param from_: From account address :type from_: str :param to: To account address (optional) :type to: str :param gas: Gas amount for current transaction (optional) :type gas: int :param gas_pr...
def get_workflows() -> dict: """Get dict of ALL known workflow definitions. Returns list[dict] """ keys = DB.get_keys("workflow_definitions:*") known_workflows = dict() for key in keys: values = key.split(':') if values[1] not in known_workflows: known_workf...
Get dict of ALL known workflow definitions. Returns list[dict]
def input_validation(group_idx, a, size=None, order='C', axis=None, ravel_group_idx=True, check_bounds=True): """ Do some fairly extensive checking of group_idx and a, trying to give the user as much help as possible with what is wrong. Also, convert ndim-indexing to 1d indexing. ""...
Do some fairly extensive checking of group_idx and a, trying to give the user as much help as possible with what is wrong. Also, convert ndim-indexing to 1d indexing.
def get_sea_names(): ''' Returns a list of NODC sea names source of list: http://www.nodc.noaa.gov/General/NODC-Archive/seanames.xml ''' global _SEA_NAMES if _SEA_NAMES is None: resource_text = get_data("cc_plugin_ncei", "data/seanames.xml") parser = etree.XMLParser(remove_blank...
Returns a list of NODC sea names source of list: http://www.nodc.noaa.gov/General/NODC-Archive/seanames.xml
def import_app(files, category, overwrite, id, name): """ Upload application from file. By default, file name will be used as application name, with "-vXX.YYY" suffix stripped. Application is looked up by one of these classifiers, in order of priority: app-id, app-name, filename. If app-id is prov...
Upload application from file. By default, file name will be used as application name, with "-vXX.YYY" suffix stripped. Application is looked up by one of these classifiers, in order of priority: app-id, app-name, filename. If app-id is provided, looks up existing application and updates its manifest. ...
def print_params(self, allpars=False, loglevel=logging.INFO): """Print information about the model parameters (values, errors, bounds, scale).""" pars = self.get_params() o = '\n' o += '%4s %-20s%10s%10s%10s%10s%10s%5s\n' % ( 'idx', 'parname', 'value', 'error', ...
Print information about the model parameters (values, errors, bounds, scale).
def _content_blocks(self, r): """Number of content blocks in block row `r`.""" return (self._block_rows - self._left_zero_blocks(r) - self._right_zero_blocks(r))
Number of content blocks in block row `r`.
def reserve_udp_port(self, port, project): """ Reserve a specific UDP port number :param port: UDP port number :param project: Project instance """ if port in self._used_udp_ports: raise HTTPConflict(text="UDP port {} already in use on host {}".format(port, ...
Reserve a specific UDP port number :param port: UDP port number :param project: Project instance
def delete(self, num_iid, properties, session, item_price=None, item_num=None, lang=None): '''taobao.item.sku.delete 删除SKU 删除一个sku的数据 需要删除的sku通过属性properties进行匹配查找''' request = TOPRequest('taobao.item.sku.delete') request['num_iid'] = num_iid request['properties'] = prope...
taobao.item.sku.delete 删除SKU 删除一个sku的数据 需要删除的sku通过属性properties进行匹配查找
def get_description(self): """Get the description of a GObject.""" vo = ffi.cast('VipsObject *', self.pointer) return _to_string(vips_lib.vips_object_get_description(vo))
Get the description of a GObject.
def fetch_one(self, *args, **kwargs): """ return one document which match the structure of the object `fetch_one()` takes the same arguments than the the pymongo.collection.find method. If multiple documents are found, raise a MultipleResultsFound exception. If no document is fou...
return one document which match the structure of the object `fetch_one()` takes the same arguments than the the pymongo.collection.find method. If multiple documents are found, raise a MultipleResultsFound exception. If no document is found, return None The query is launch against the db...
def with_local_env_strategy(molecule, strategy, reorder=True, extend_structure=True): """ Constructor for MoleculeGraph, using a strategy from :Class: `pymatgen.analysis.local_env`. :param molecule: Molecule object :param strategy: an instance of ...
Constructor for MoleculeGraph, using a strategy from :Class: `pymatgen.analysis.local_env`. :param molecule: Molecule object :param strategy: an instance of a :Class: `pymatgen.analysis.local_env.NearNeighbors` object :param reorder: bool, representing if graph nodes need to...
def removeBinder(self, name): """Remove a binder from a table """ root = self.etree t_bindings = root.find('bindings') t_binder = t_bindings.find(name) if t_binder : t_bindings.remove(t_binder) return True return...
Remove a binder from a table
def clubConsumables(self, fast=False): """Return all consumables from club.""" method = 'GET' url = 'club/consumables/development' rc = self.__request__(method, url) events = [self.pin.event('page_view', 'Hub - Club')] self.pin.send(events, fast=fast) events = [...
Return all consumables from club.
def send_rpc(self, address, rpc_id, call_payload, timeout=3.0): """Send an rpc to our connected device. The device must already be connected and the rpc interface open. This method will synchronously send an RPC and wait for the response. Any RPC errors will be raised as exceptions an...
Send an rpc to our connected device. The device must already be connected and the rpc interface open. This method will synchronously send an RPC and wait for the response. Any RPC errors will be raised as exceptions and if there were no errors, the RPC's response payload will be retur...
def create(cls, community, record, user=None, expires_at=None, notify=True): """Create a record inclusion request to a community. :param community: Community object. :param record: Record API object. :param expires_at: Time after which the request expires and shouldn't ...
Create a record inclusion request to a community. :param community: Community object. :param record: Record API object. :param expires_at: Time after which the request expires and shouldn't be resolved anymore.
def _parse_extra(self, fp): """ Parse and store the config comments and create maps for dot notion lookup """ comment = '' section = '' fp.seek(0) for line in fp: line = line.rstrip() if not line: if comment: comment ...
Parse and store the config comments and create maps for dot notion lookup
def plotfft(s, fmax, doplot=False): """ This functions computes the fft of a signal, returning the frequency and their magnitude values. Parameters ---------- s: array-like the input signal. fmax: int the sampling frequency. doplot: boolean a variable to indicate whether t...
This functions computes the fft of a signal, returning the frequency and their magnitude values. Parameters ---------- s: array-like the input signal. fmax: int the sampling frequency. doplot: boolean a variable to indicate whether the plot is done or not. Returns ---...
def _publish(self, msg): """Publish, handling retries, a message in the queue. :param msg: Object which represents the message to be sent in the queue. Note that this object should be serializable in the configured format (by default JSON). """ connection = self....
Publish, handling retries, a message in the queue. :param msg: Object which represents the message to be sent in the queue. Note that this object should be serializable in the configured format (by default JSON).
def cli_form(self, *args): """Display a schemata's form definition""" if args[0] == '*': for schema in schemastore: self.log(schema, ':', schemastore[schema]['form'], pretty=True) else: self.log(schemastore[args[0]]['form'], pretty=True)
Display a schemata's form definition
def run(self): """ 线程启动 :return: """ try: super().run() except Exception as e: print(trace_info()) finally: if not self.no_ack: # 如果为True,任务结束后需要确认 self.ch.basic_ack(delivery_tag=self.method.deliv...
线程启动 :return:
def release(self, resource): """release(resource) Returns a resource to the pool. Most of the time you will want to use :meth:`transaction`, but if you use :meth:`acquire`, you must release the acquired resource back to the pool when finished. Failure to do so could result in de...
release(resource) Returns a resource to the pool. Most of the time you will want to use :meth:`transaction`, but if you use :meth:`acquire`, you must release the acquired resource back to the pool when finished. Failure to do so could result in deadlock. :param resource: Resour...
def extent_string_to_array(extent_text): """Convert an extent string to an array. .. versionadded: 2.2.0 :param extent_text: String representing an extent e.g. 109.829170982, -8.13333290561, 111.005344795, -7.49226294379 :type extent_text: str :returns: A list of floats, or None :rtyp...
Convert an extent string to an array. .. versionadded: 2.2.0 :param extent_text: String representing an extent e.g. 109.829170982, -8.13333290561, 111.005344795, -7.49226294379 :type extent_text: str :returns: A list of floats, or None :rtype: list, None
def columns(self): """Return names of all the addressable columns (including foreign keys) referenced in user supplied model""" res = [col['name'] for col in self.column_definitions] res.extend([col['name'] for col in self.foreign_key_definitions]) return res
Return names of all the addressable columns (including foreign keys) referenced in user supplied model
def set_back_led_output(self, value): """value can be between 0x00 and 0xFF""" return self.write(request.SetBackLEDOutput(self.seq, value))
value can be between 0x00 and 0xFF
def setting_ctx(num_gpus): """ Description : set gpu module """ if num_gpus > 0: ctx = [mx.gpu(i) for i in range(num_gpus)] else: ctx = [mx.cpu()] return ctx
Description : set gpu module
def _convert_from_thrift_endpoint(self, thrift_endpoint): """Accepts a thrift decoded endpoint and converts it to an Endpoint. :param thrift_endpoint: thrift encoded endpoint :type thrift_endpoint: thrift endpoint :returns: decoded endpoint :rtype: Encoding """ i...
Accepts a thrift decoded endpoint and converts it to an Endpoint. :param thrift_endpoint: thrift encoded endpoint :type thrift_endpoint: thrift endpoint :returns: decoded endpoint :rtype: Encoding
def get_authority(config, metrics, rrset_channel, **kwargs): """Get a GCEAuthority client. A factory function that validates configuration and creates a proper GCEAuthority. Args: config (dict): GCEAuthority related configuration. metrics (obj): :interface:`IMetricRelay` implementation...
Get a GCEAuthority client. A factory function that validates configuration and creates a proper GCEAuthority. Args: config (dict): GCEAuthority related configuration. metrics (obj): :interface:`IMetricRelay` implementation. rrset_channel (asyncio.Queue): Queue used for sending mess...
def slots_class_sealer(fields, defaults): """ This sealer makes a container class that uses ``__slots__`` (it uses :func:`class_sealer` internally). The resulting class has a metaclass that forcibly sets ``__slots__`` on subclasses. """ class __slots_meta__(type): def __new__(mcs, name, bas...
This sealer makes a container class that uses ``__slots__`` (it uses :func:`class_sealer` internally). The resulting class has a metaclass that forcibly sets ``__slots__`` on subclasses.
def process_gene_interaction(self, limit): """ The gene interaction file includes identified interactions, that are between two or more gene (products). In the case of interactions with >2 genes, this requires creating groups of genes that are involved in the interaction. ...
The gene interaction file includes identified interactions, that are between two or more gene (products). In the case of interactions with >2 genes, this requires creating groups of genes that are involved in the interaction. From the wormbase help list: In the example WBInteraction00000...
def _read_unquote(ctx: ReaderContext) -> LispForm: """Read an unquoted form and handle any special logic of unquoting. Unquoted forms can take two, well... forms: `~form` is read as `(unquote form)` and any nested forms are read literally and passed along to the compiler untouched. `~@form`...
Read an unquoted form and handle any special logic of unquoting. Unquoted forms can take two, well... forms: `~form` is read as `(unquote form)` and any nested forms are read literally and passed along to the compiler untouched. `~@form` is read as `(unquote-splicing form)` which tells the comp...
def mv_normal_cov_like(x, mu, C): R""" Multivariate normal log-likelihood parameterized by a covariance matrix. .. math:: f(x \mid \pi, C) = \frac{1}{(2\pi|C|)^{1/2}} \exp\left\{ -\frac{1}{2} (x-\mu)^{\prime}C^{-1}(x-\mu) \right\} :Parameters: - `x` : (n,k) - `mu` : (k) Locatio...
R""" Multivariate normal log-likelihood parameterized by a covariance matrix. .. math:: f(x \mid \pi, C) = \frac{1}{(2\pi|C|)^{1/2}} \exp\left\{ -\frac{1}{2} (x-\mu)^{\prime}C^{-1}(x-\mu) \right\} :Parameters: - `x` : (n,k) - `mu` : (k) Location parameter. - `C` : (k,k) Posit...
def reset(self): """ Reset all fields of this object to class defaults """ for name in self.__dict__: if name.startswith("_"): continue attr = getattr(self, name) setattr(self, name, attr and attr.__class__())
Reset all fields of this object to class defaults
def probe(self, ipaddr=None): """ Probe given address for bulb. """ if ipaddr is None: # no address so use broadcast ipaddr = self._broadcast_addr cmd = {"payloadtype": PayloadType.GET, "target": ipaddr} self._send_command(cmd)
Probe given address for bulb.
def check_packed_data(self, ds): """ 8.1 Simple packing may be achieved through the use of the optional NUG defined attributes scale_factor and add_offset. After the data values of a variable have been read, they are to be multiplied by the scale_factor, and have add_offset added to them...
8.1 Simple packing may be achieved through the use of the optional NUG defined attributes scale_factor and add_offset. After the data values of a variable have been read, they are to be multiplied by the scale_factor, and have add_offset added to them. The units of a variable should be represen...
def get_last_content(request, page_id): """Get the latest content for a particular type""" content_type = request.GET.get('content_type') language_id = request.GET.get('language_id') page = get_object_or_404(Page, pk=page_id) placeholders = get_placeholders(page.get_template()) _template = templ...
Get the latest content for a particular type