Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
14,500
def insert(self, resource, value): parts = resource_parts_re.split(resource) if parts[-1] == : return self.lock.acquire() db = self.db for i in range(1, len(parts), 2): if parts[i - 1] not in db: ...
insert(resource, value) Insert a resource entry into the database. RESOURCE is a string and VALUE can be any Python value.
14,501
def isPointVisible(self, x, y): 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.MonitorFromPoint(pt, MONITOR_DEFAULTTONULL) if ...
Checks if a point is visible on any monitor.
14,502
def setInverted(self, state): 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>
14,503
def to_profile_info(self, serialize_credentials=False): result = { : self.profile_name, : self.target_name, : self.config.to_dict(), : self.threads, : self.credentials.incorporate(), } if serialize_credentials: resu...
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...
14,504
def Diag(a): r = np.zeros(2 * a.shape, dtype=a.dtype) for idx, v in np.ndenumerate(a): r[2 * idx] = v return r,
Diag op.
14,505
def failure_raiser(*validation_func, **kwargs ): failure_type, help_msg = pop_kwargs(kwargs, [(, None), (, None)], allow_others=True) kw_context_args = kwargs main_func = _process_validation_function_s(list(validation_func)) return _failure_raiser...
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...
14,506
def _convert_to_tensor(value, dtype=None, dtype_hint=None, name=None): if (tf.nest.is_nested(dtype) or tf.nest.is_nested(dtype_hint)): if dtype is None: fn = lambda v, pd: tf.convert_to_tensor(v, dtype_hint=pd, name=name) return tf.nest.map_structure(fn, value, dtype_hint) elif dtype_hint...
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...
14,507
def save_to_file(self, path, filename, **params): url = ensure_trailing_slash(self.url + path.lstrip()) content = self._request(, url, params=params).content with open(filename, ) as f: f.write(content)
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.
14,508
def time(host=None, port=None, db=None, password=None): * 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
14,509
def K(self, parm): return ARD_K_matrix(self.X, parm) + np.identity(self.X.shape[0])*(10**-10)
Returns the Gram Matrix Parameters ---------- parm : np.ndarray Parameters for the Gram Matrix Returns ---------- - Gram Matrix (np.ndarray)
14,510
def _astorestr(ins): output = _addr(ins.quad[1]) op = ins.quad[2] indirect = op[0] == if indirect: op = op[1:] immediate = op[0] == if immediate: op = op[1:] temporal = op[0] != if not temporal: op = op[1:] if is_int(op): op = str(int(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 '#'.
14,511
def apply(self, event = None): for section in self.config.sections(): for option, o in self.config.config[section].items(): if not o[]: continue return False self.config.set(section, option, value) return True
Before self.onOk closes the window, it calls this function to sync the config changes from the GUI back to self.config.
14,512
def send_status_response(environ, start_response, e, add_headers=None, is_head=False): status = get_http_status_string(e) headers = [] if add_headers: headers.extend(add_headers) if e in (HTTP_NOT_MODIFIED, HTTP_NO_CONTENT): start_response( ...
Start a WSGI response for a DAVError or status code.
14,513
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
14,514
def loadGmesh(filename, c="gold", alpha=1, wire=False, bc=None): if not os.path.exists(filename): colors.printc("~noentry Error in loadGmesh: Cannot find", filename, c=1) return None f = open(filename, "r") lines = f.readlines() f.close() nnodes = 0 index_nodes = 0 for...
Reads a `gmesh` file format. Return an ``Actor(vtkActor)`` object.
14,515
def _maybe_assert_valid_concentration(self, concentration, validate_args): if not validate_args: return concentration return distribution_util.with_dependencies([ assert_util.assert_positive( concentration, message="Concentration parameter must be positive."), assert_util....
Checks the validity of the concentration parameter.
14,516
def _create_relational_field(self, attr, options): options[] = attr.py_type options[] = not attr.is_required return EntityField, options
Creates the form element for working with entity relationships.
14,517
def format(self, indent_level, indent_size=4): name = self.format_name(, indent_size) if self.long_desc is not None: name += name += self.wrap_lines( % str(self._literal), 1, indent_size) return self.wrap_lines(name, indent_level, indent_size)
Format this verifier Returns: string: A formatted string
14,518
def after_request(self, fn): self._defer(lambda app: app.after_request(fn)) return 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 might not be executed at the end of the requ...
14,519
def state_create(history_id_key, table_name, collision_checker, always_set=[]): def wrap( check ): def wrapped_check( state_engine, nameop, block_id, checked_ops ): rc = check( state_engine, nameop, block_id, checked_ops ) try: assert in n...
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...
14,520
def parse_match_settings(match_settings, config: ConfigObject): match_settings.game_mode = config.get(MATCH_CONFIGURATION_HEADER, GAME_MODE) match_settings.game_map = config.get(MATCH_CONFIGURATION_HEADER, GAME_MAP) match_settings.skip_replays = config.getboolean(MATCH_CONFIGURATION_HEADER, SKIP_REPLA...
Parses the matching settings modifying the match settings object. :param match_settings: :param config: :return:
14,521
def com_google_fonts_check_os2_metrics_match_hhea(ttFont): if ttFont["OS/2"].sTypoAscender != ttFont["hhea"].ascent: yield FAIL, Message("ascender", "OS/2 sTypoAscender and hhea ascent must be equal.") elif ttFont["OS/2"].sTypoDescender != ttFont["hhea"].descent: yield FAIL, Me...
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.
14,522
def missing_whitespace_around_operator(logical_line, tokens): r parens = 0 need_space = False prev_type = tokenize.OP prev_text = prev_end = None for token_type, text, start, end, line in tokens: if token_type in SKIP_COMMENTS: continue if text in (, ): pa...
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...
14,523
def clear(self): 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
14,524
def predictions_variance(df, filepath=None): df = df.filter(regex="^VAR:") by_readout = df.mean(axis=0).reset_index(level=0) by_readout.columns = [, ] by_readout[] = by_readout.Readout.map(lambda n: n[4:]) g1 = sns.factorplot(x=, y=, data=by_readout, kind=, aspect=2) for tick in g1.ax....
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...
14,525
def _code_line(self, line): assert self._containers container = self._containers[-1] text = line while text: if text.startswith(): r = re.match(r, text) n = len(r.group(1)) container.addElement(S(c=n)) ...
Add a code line.
14,526
def resolve_aliases(self, chunks): state for idx, _ in enumerate(chunks): new_state = self.aliases.get(chunks[idx][]) if new_state is not None: chunks[idx][] = new_state
Preserve backward compatibility by rewriting the 'state' key in the low chunks if it is using a legacy type.
14,527
def _unordered_iter(self): try: rlist = self.get(0) except error.TimeoutError: pending = set(self.msg_ids) while pending: try: self._client.wait(pending, 1e-3) except error.TimeoutError: ...
iterator for results *as they arrive*, on FCFS basis, ignoring submission order.
14,528
def is_kanji(data): 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) for i in range(0, data_len, 2): code = (next(data_iter) << 8) | next(data_iter) if not (0x8140 <= code <= 0x9ffc o...
\ Returns if the `data` can be encoded in "kanji" mode. :param bytes data: The data to check. :rtype: bool
14,529
def supported_alleles(self): if not in self._cache: result = set(self.allele_to_allele_specific_models) if self.allele_to_fixed_length_sequence: result = result.union(self.allele_to_fixed_length_sequence) self._cache["supported_alleles"] = sorted(res...
Alleles for which predictions can be made. Returns ------- list of string
14,530
def map_prop_value_as_index(prp, lst): 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:
14,531
def extend_right_to(self, window, 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
14,532
def get_facts(self): vendor = u uptime = -1 serial_number, fqdn, os_version, hostname, domain_name = (,) * 5 show_ver = self._send_command() show_hosts = self._send_command() show_ip_int_br = self._send_command() for line in s...
Return a set of facts from the devices.
14,533
def solvedbi_sm(ah, rho, b, c=None, axis=4): r a = np.conj(ah) if c is None: c = solvedbi_sm_c(ah, a, rho, axis) if have_numexpr: cb = inner(c, b, axis=axis) return ne.evaluate() else: return (b - (a * inner(c, b, axis=axis))) / rho
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} =...
14,534
def gridsearch(self, X, y, weights=None, return_scores=False, keep_best=True, objective=, progress=True, **param_grids): if not self._is_fitted: self._validate_params() self._validate_data_dep_params(X) y = check_y(y, self....
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...
14,535
def copy_path_flat(self): path = cairo.cairo_copy_path_flat(self._pointer) result = list(_iter_path(path)) cairo.cairo_path_destroy(path) return result
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...
14,536
def default_ubuntu_tr(mod): pkg = % mod.lower() py2pkg = pkg py3pkg = % mod.lower() return (pkg, py2pkg, py3pkg)
Default translation function for Ubuntu based systems
14,537
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]: if clear_cache and file_cache: logger.warning("Cleared file cache") file...
Run clingo to compute a completion of a partial spec or violations.
14,538
def read(self, page): log.debug("read pages {0} to {1}".format(page, page+3)) data = self.transceive("\x30"+chr(page % 256), timeout=0.005) if len(data) == 1 and data[0] & 0xFA == 0x00: log.debug("received nak response") self.target.sel_req = self.target.sdd_re...
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 ...
14,539
def grid_linspace(bounds, count): bounds = np.asanyarray(bounds, dtype=np.float64) if len(bounds) != 2: raise ValueError() count = np.asanyarray(count, dtype=np.int) if count.shape == (): count = np.tile(count, bounds.shape[1]) grid_elements = [np.linspace(*b, num=c) for b, c ...
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...
14,540
def get_scaled_cutout_basic(self, x1, y1, x2, y2, scale_x, scale_y, method=): new_wd = int(round(scale_x * (x2 - x1 + 1))) new_ht = int(round(scale_y * (y2 - y1 + 1))) return self.get_scaled_cutout_wdht(x1, y1, x2, y2, new_wd, new_ht, ...
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.
14,541
def polygon(self): 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) return polyg
Returns an OGR Geometry for this envelope.
14,542
def start(self): c_logs_ingested = Counter( , , [, , ], ) c_messages_published = Counter( , , [, , ], ) self._setup_ipc() log.debug(, self._listener_type) self._setup_listene...
Listen to messages and publish them.
14,543
def read_file_1st_col_only(fname): lst = [] with open(fname, ) as f: _ = f.readline() for line in f: lst.append(line.split()[0]) return lst
read a CSV file (ref_classes.csv) and return the list of names
14,544
def complete(request, provider): data = request.GET.copy() data.update(request.POST) if not in request.session: request.session[] = request.GET.get("next") or settings.LOGIN_REDIRECT_URL backend = get_backend(provider) response = backend.validate(request, data) if isin...
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. ...
14,545
def sort_by_name(names): 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(names), key=last_name_key)
Sort by last name, uniquely.
14,546
def pairinplace(args): from jcvi.utils.iter import pairwise p = OptionParser(pairinplace.__doc__) p.set_rclip() p.set_tag() p.add_option("--base", help="Base name for the output files [default: %default]") opts, args = p.parse_args(args) if len(args) != 1: sys....
%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.
14,547
def process_strings(self, string, docstrings=False): 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 = in stype is_raw = in stype ...
Process escapes.
14,548
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...
14,549
def get_user(self, username): cmd = ["glsuser", "-u", username, "--raw"] results = self._read_output(cmd) if len(results) == 0: return None elif len(results) > 1: logger.error( "Command returned multiple results for ." % username) ...
Get the user details from MAM.
14,550
def _collapse_preconditions(base_preconditions: List[List[Contract]], bases_have_func: bool, preconditions: List[List[Contract]], func: Callable[..., Any]) -> List[List[Contract]]: if not base_preconditions and bases_have_func and preconditions: raise TypeError(("The functio...
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...
14,551
def get_signin_url(self, service=): alias = self.get_account_alias() if not alias: raise Exception() return "https://%s.signin.aws.amazon.com/console/%s" % (alias, service)
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.
14,552
def _load_lib(): 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.
14,553
def cast_from_bunq_response(cls, bunq_response): return cls( bunq_response.value, bunq_response.headers, bunq_response.pagination )
:type bunq_response: BunqResponse
14,554
def buildWorkbenchWithLauncher(): workbench = ui.Workbench() tools = [exercises.SearchTool()] launcher = ui.Launcher(workbench, tools) workbench.display(launcher) return workbench, launcher
Builds a workbench. The workbench has a launcher with all of the default tools. The launcher will be displayed on the workbench.
14,555
def not_next(e): 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(, pos) return match_not_next
Create a PEG function for negative lookahead.
14,556
def get_config_value(name, fallback=None): cli_config = CLIConfig(SF_CLI_CONFIG_DIR, SF_CLI_ENV_VAR_PREFIX) return cli_config.get(, name, fallback)
Gets a config by name. In the case where the config name is not found, will use fallback value.
14,557
def get_indexed_node(manager, prop, value, node_type=, lookup_func=, legacy=True): q = .format(label=node_type, prop=prop, lookup_func=lookup_func) with manager.session as s: for result in s.run(q, {: value}): if legacy: yield result[].properties else: ...
: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...
14,558
def format_request_email_title(increq, **ctx): template = current_app.config["COMMUNITIES_REQUEST_EMAIL_TITLE_TEMPLATE"], return format_request_email_templ(increq, template, **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 formatter. :type ctx: dict. :returns: Email m...
14,559
def _init_grps(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
14,560
def revoke_auth(preserve_minion_cache=False): preserve_minion_cache* masters = list() ret = True if in __opts__: for master_uri in __opts__[]: masters.append(master_uri) else: masters.append(__opts__[]) for master in masters: channel = salt.transport.client....
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. ...
14,561
def setup_menu(self): copy_action = create_action(self, _(), shortcut=keybinding(), icon=ima.icon(), triggered=self.copy, context=Qt.WidgetShortcut) ...
Setup context menu.
14,562
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
布林通道
14,563
def date_to_epiweek(date=datetime.date.today()) -> 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 date >= start_dates[2]: start_date = sta...
Convert python date to Epiweek
14,564
def eth_sendTransaction(self, from_, to=None, gas=None, gas_price=None, value=None, data=None, nonce=None): obj = {} obj[] = from_ if to is not None: obj[] = to if gas is not None: obj[] = hex(gas) ...
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...
14,565
def get_workflows() -> 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_workflows[values[1]] = list() known_workflows[values[1]].append(values[2]) return ...
Get dict of ALL known workflow definitions. Returns list[dict]
14,566
def input_validation(group_idx, a, size=None, order=, axis=None, ravel_group_idx=True, check_bounds=True): if not isinstance(a, (int, float, complex)): a = np.asanyarray(a) group_idx = np.asanyarray(group_idx) if not np.issubdtype(group_idx.dtype, np.integer): rais...
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.
14,567
def get_sea_names(): global _SEA_NAMES if _SEA_NAMES is None: resource_text = get_data("cc_plugin_ncei", "data/seanames.xml") parser = etree.XMLParser(remove_blank_text=True) root = etree.fromstring(resource_text, parser) buf = {} for seaname in root.findall(): ...
Returns a list of NODC sea names source of list: http://www.nodc.noaa.gov/General/NODC-Archive/seanames.xml
14,568
def import_app(files, category, overwrite, id, name): platform = _get_platform() org = platform.get_organization(QUBELL["organization"]) if category: category = org.categories[category] regex = re.compile(r"^(.*?)(-v(\d+)|)\.[^.]+$") if (id or name) and len(files) > 1: raise Exc...
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. ...
14,569
def print_params(self, allpars=False, loglevel=logging.INFO): pars = self.get_params() o = o += % ( , , , , , , , ) o += * 80 + src_pars = collections.OrderedDict() for p in pars: src_pars.setdefault(p[], []) ...
Print information about the model parameters (values, errors, bounds, scale).
14,570
def _content_blocks(self, r): return (self._block_rows - self._left_zero_blocks(r) - self._right_zero_blocks(r))
Number of content blocks in block row `r`.
14,571
def reserve_udp_port(self, port, project): if port in self._used_udp_ports: raise HTTPConflict(text="UDP port {} already in use on host {}".format(port, self._console_host)) if port < self._udp_port_range[0] or port > self._udp_port_range[1]: raise HTTPConflict(text="UD...
Reserve a specific UDP port number :param port: UDP port number :param project: Project instance
14,572
def delete(self, num_iid, properties, session, item_price=None, item_num=None, lang=None): request = TOPRequest() request[] = num_iid request[] = properties if item_num!=None: request[] = item_num if item_price!=None: request[] = item_price ...
taobao.item.sku.delete 删除SKU 删除一个sku的数据 需要删除的sku通过属性properties进行匹配查找
14,573
def get_description(self): vo = ffi.cast(, self.pointer) return _to_string(vips_lib.vips_object_get_description(vo))
Get the description of a GObject.
14,574
def fetch_one(self, *args, **kwargs): bson_obj = self.fetch(*args, **kwargs) count = bson_obj.count() if count > 1: raise MultipleResultsFound("%s results found" % count) elif count == 1: return next(bson_obj)
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...
14,575
def with_local_env_strategy(molecule, strategy, reorder=True, extend_structure=True): mg = MoleculeGraph.with_empty_graph(molecule, name="bonds", edge_weight_name="weight", edge_weig...
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...
14,576
def removeBinder(self, name): root = self.etree t_bindings = root.find() t_binder = t_bindings.find(name) if t_binder : t_bindings.remove(t_binder) return True return False
Remove a binder from a table
14,577
def clubConsumables(self, fast=False): method = url = rc = self.__request__(method, url) events = [self.pin.event(, )] self.pin.send(events, fast=fast) events = [self.pin.event(, )] self.pin.send(events, fast=fast) events = [self.pin.event(, )...
Return all consumables from club.
14,578
def send_rpc(self, address, rpc_id, call_payload, timeout=3.0): if not self.connected: raise HardwareError("Cannot send an RPC if we are not in a connected state") if timeout is None: timeout = 3.0 status = -1 payload = b recording = None ...
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...
14,579
def create(cls, community, record, user=None, expires_at=None, notify=True): if expires_at and expires_at < datetime.utcnow(): raise InclusionRequestExpiryTimeError( community=community, record=record) if community.has_record(record): rais...
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.
14,580
def _parse_extra(self, fp): comment = section = fp.seek(0) for line in fp: line = line.rstrip() if not line: if comment: comment += continue if line.startswith(): com...
Parse and store the config comments and create maps for dot notion lookup
14,581
def plotfft(s, fmax, doplot=False): fs = abs(np.fft.fft(s)) f = linspace(0, fmax / 2, len(s) / 2) if doplot: pass return (f[1:int(len(s) / 2)].copy(), fs[1:int(len(s) / 2)].copy())
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 ---...
14,582
def _publish(self, msg): connection = self._connection.clone() publish = connection.ensure(self.producer, self.producer.publish, errback=self.__error_callback, max_retries=MQ_PRODUCER_MAX_RETRIES) publish(json.dumps...
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).
14,583
def cli_form(self, *args): if args[0] == : for schema in schemastore: self.log(schema, , schemastore[schema][], pretty=True) else: self.log(schemastore[args[0]][], pretty=True)
Display a schemata's form definition
14,584
def run(self): try: super().run() except Exception as e: print(trace_info()) finally: if not self.no_ack: self.ch.basic_ack(delivery_tag=self.method.delivery_tag)
线程启动 :return:
14,585
def release(self, resource): with self.releaser: resource.claimed = False self.releaser.notify_all()
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...
14,586
def extent_string_to_array(extent_text): coordinates = extent_text.replace(, ).split() count = len(coordinates) if count != 4: message = ( % count) LOGGER.error(message) return None try: coordinates = [float(i) for i in coordinates] except Valu...
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
14,587
def columns(self): res = [col[] for col in self.column_definitions] res.extend([col[] for col in self.foreign_key_definitions]) return res
Return names of all the addressable columns (including foreign keys) referenced in user supplied model
14,588
def set_back_led_output(self, value): return self.write(request.SetBackLEDOutput(self.seq, value))
value can be between 0x00 and 0xFF
14,589
def setting_ctx(num_gpus): if num_gpus > 0: ctx = [mx.gpu(i) for i in range(num_gpus)] else: ctx = [mx.cpu()] return ctx
Description : set gpu module
14,590
def _convert_from_thrift_endpoint(self, thrift_endpoint): ipv4 = None ipv6 = None port = struct.unpack(, struct.pack(, thrift_endpoint.port))[0] if thrift_endpoint.ipv4 != 0: ipv4 = socket.inet_ntop( socket.AF_INET, struct.pack(, thri...
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
14,591
def get_authority(config, metrics, rrset_channel, **kwargs): builder = authority.GCEAuthorityBuilder( config, metrics, rrset_channel, **kwargs) return builder.build_authority()
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...
14,592
def slots_class_sealer(fields, defaults): class __slots_meta__(type): def __new__(mcs, name, bases, namespace): if "__slots__" not in namespace: namespace["__slots__"] = fields return type.__new__(mcs, name, bases, namespace) class __slots_base__(_with_metac...
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.
14,593
def process_gene_interaction(self, limit): raw = .join((self.rawdir, self.files[][])) if self.test_mode: graph = self.testgraph else: graph = self.graph model = Model(graph) LOG.info("Processing gene interaction associations") line_count...
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...
14,594
def _read_unquote(ctx: ReaderContext) -> LispForm: start = ctx.reader.advance() assert start == "~" with ctx.unquoted(): next_char = ctx.reader.peek() if next_char == "@": ctx.reader.advance() next_form = _read_next_consuming_comment(ctx) return llis...
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...
14,595
def mv_normal_cov_like(x, mu, C): R if len(np.shape(x)) > 1: return np.sum([flib.cov_mvnorm(r, mu, C) for r in x]) else: return flib.cov_mvnorm(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) Location parameter. - `C` : (k,k) Posit...
14,596
def reset(self): 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
14,597
def probe(self, ipaddr=None): if ipaddr is None: ipaddr = self._broadcast_addr cmd = {"payloadtype": PayloadType.GET, "target": ipaddr} self._send_command(cmd)
Probe given address for bulb.
14,598
def check_packed_data(self, ds): ret_val = [] for name, var in ds.variables.items(): add_offset = getattr(var, , None) scale_factor = getattr(var, , None) if not (add_offset or scale_factor): continue valid = True rea...
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...
14,599
def get_last_content(request, page_id): content_type = request.GET.get() language_id = request.GET.get() page = get_object_or_404(Page, pk=page_id) placeholders = get_placeholders(page.get_template()) _template = template.loader.get_template(page.get_template()) for placeholder in placehold...
Get the latest content for a particular type