Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
374,000
def authenticate(self, username, password): self._username = username self._password = password resp = requests.get( self._url, auth=(username, password), **self._default_request_kwargs ) try: i...
Authenticate against the ObjectRocket API. :param str username: The username to perform basic authentication against the API with. :param str password: The password to perform basic authentication against the API with. :returns: A token used for authentication against token protected resources....
374,001
def _request_toc_element(self, index): logger.debug(, index, self.port) pk = CRTPPacket() if self._useV2: pk.set_header(self.port, TOC_CHANNEL) pk.data = (CMD_TOC_ITEM_V2, index & 0x0ff, (index >> 8) & 0x0ff) self.cf.send_packet(pk, expected_reply=( ...
Request information about a specific item in the TOC
374,002
def validate_template(template_body=None, template_url=None, region=None, key=None, keyid=None, profile=None): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.validate_template(template_body, template_url) except BotoServerError as e: lo...
Validate cloudformation template .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_cfn.validate_template mystack-template
374,003
def setup(self, path=None): candidates = [, ] if (path): candidates = [path] selected = None for candidate in candidates: try: p = subprocess.Popen(candidate, shell=True, stdin=sub...
Look for SExtractor program ('sextractor', or 'sex'). If a full path is provided, only this path is checked. Raise a SExtractorException if it failed. Return program and version if it succeed.
374,004
def parse_add_loopback(): class Add(argparse.Action): def __call__(self, parser, args, values, option_string=None): try: ipaddress.IPv4Interface("{}/{}".format(values[1], values[2])) except ipaddress.AddressValueError as e: raise argparse.Argume...
Validate params when adding a loopback adapter
374,005
def Stop(self): if not self.__running: return logging.info(, self._host) headers = {: } response, _ = self._http.request( % self._host, method=, headers=headers) if response.status != 200: logging.warning(, response) self.__running = False ...
Stops the emulator instance.
374,006
def IsWalletTransaction(self, tx): for key, contract in self._contracts.items(): for output in tx.outputs: if output.ScriptHash.ToBytes() == contract.ScriptHash.ToBytes(): return True for script in tx.scripts: if script.Veri...
Verifies if a transaction belongs to the wallet. Args: tx (TransactionOutput):an instance of type neo.Core.TX.Transaction.TransactionOutput to verify. Returns: bool: True, if transaction belongs to wallet. False, if not.
374,007
def minimum(left, right): if isinstance(left, Symbol) and isinstance(right, Symbol): return _internal._Minimum(left, right) if isinstance(left, Symbol) and isinstance(right, Number): return _internal._MinimumScalar(left, scalar=right) if isinstance(left, Number) and isinstance(right, Sy...
Returns element-wise minimum of the input elements. Both inputs can be Symbol or scalar number. Broadcasting is not supported. Parameters --------- left : Symbol or scalar First symbol to be compared. right : Symbol or scalar Second symbol to be compared. Returns ------- ...
374,008
def xpnsl(h1, h2, use_threads=True): h1 = asarray_ndim(h1, 2) check_integer_dtype(h1) h2 = asarray_ndim(h2, 2) check_integer_dtype(h2) check_dim0_aligned(h1, h2) h1 = memoryview_safe(h1) h2 = memoryview_safe(h2) if use_threads and multiprocessing.cpu_count() > 1: ...
Cross-population version of the NSL statistic. Parameters ---------- h1 : array_like, int, shape (n_variants, n_haplotypes) Haplotype array for the first population. h2 : array_like, int, shape (n_variants, n_haplotypes) Haplotype array for the second population. use_threads : bool,...
374,009
def parse_content(self, content): data = {} data = split_kv_pairs(content, use_partition=False) self.data = dict((k, v) for k, v in data.items() if not v == )
Sample Input:: TimeoutStartUSec=1min 30s LimitNOFILE=65536 LimitMEMLOCK= LimitLOCKS=18446744073709551615 Sample Output:: {"LimitNOFILE" : "65536", "TimeoutStartUSec" : "1min 30s", "LimitLOCKS" : "1844674407370955161...
374,010
def unsubscribe(self, code_list, subtype_list): ret, msg, code_list, subtype_list = self._check_subscribe_param(code_list, subtype_list) if ret != RET_OK: return ret, msg query_processor = self._get_sync_query_processor(SubscriptionQuery.pack_unsubscribe_req, ...
取消订阅 :param code_list: 取消订阅的股票代码列表 :param subtype_list: 取消订阅的类型,参见SubType :return: (ret, err_message) ret == RET_OK err_message为None ret != RET_OK err_message为错误描述字符串
374,011
def _connect(self): if not self._db: import boto sdb = boto.connect_sdb() if not self.domain_name: self.domain_name = boto.config.get("DB", "sequence_db", boto.config.get("DB", "db_name", "default")) try: self._db = sdb.get...
Connect to our domain
374,012
def object(self, infotype, key): "Return the encoding, idletime, or refcount about the key" return self.execute_command(, infotype, key, infotype=infotype)
Return the encoding, idletime, or refcount about the key
374,013
async def _read_packet(self, packet_type=MysqlPacket): buff = b while True: try: packet_header = await self._read_bytes(4) except asyncio.CancelledError: self._close_on_cancel() raise btrl, btrh, packet_number ...
Read an entire "mysql packet" in its entirety from the network and return a MysqlPacket type that represents the results.
374,014
def check_model(self): for clique in self.nodes(): factors = filter(lambda x: set(x.scope()) == set(clique), self.factors) if not any(factors): raise ValueError() cardinalities = self.get_cardinality() if len(set((x for clique in self.nodes() for...
Check the model for various errors. This method checks for the following errors. * Checks if factors are defined for all the cliques or not. * Check for running intersection property is not done explicitly over here as it done in the add_edges method. * Checks if cardinality i...
374,015
def vatu0(self,E,Lz,u0,R,retv2=False): v2= (2.*(E-actionAngleStaeckel.potentialStaeckel(u0,numpy.pi/2., self._pot, self._delta)) -Lz**2./R**2.) ...
NAME: vatu0 PURPOSE: calculate the velocity at u0 INPUT: E - energy Lz - angular momentum u0 - u0 R - radius corresponding to u0,pi/2. retv2= (False), if True return v^2 OUTPUT: velocity HISTORY: ...
374,016
def _get_connection_from_url(self, url, timeout, **kwargs): url = self._decode_url(url, "") if url.scheme == or url.scheme == : return HttpConnection(url.geturl(), timeout=timeout, **kwargs) else: if sys.version_info[0] > 2: raise ValueError("T...
Returns a connection object given a string url
374,017
def pause(self, *partitions): if not all([isinstance(p, TopicPartition) for p in partitions]): raise TypeError() for partition in partitions: log.debug("Pausing partition %s", partition) self._subscription.pause(partition)
Suspend fetching from the requested partitions. Future calls to :meth:`~kafka.KafkaConsumer.poll` will not return any records from these partitions until they have been resumed using :meth:`~kafka.KafkaConsumer.resume`. Note: This method does not affect partition subscription. In parti...
374,018
def get_heading_encoding(response): encoding = wpull.protocol.http.util.parse_charset( response.fields.get(, )) if encoding: return wpull.string.normalize_codec_name(encoding) else: return None
Return the document encoding from a HTTP header. Args: response (Response): An instance of :class:`.http.Response`. Returns: ``str``, ``None``: The codec name.
374,019
def save(self): if not self.needs_save(): return defer.succeed(self) args = [] directories = [] for (key, value) in self.unsaved.items(): if key == : self.config[] = value ...
Save any outstanding items. This returns a Deferred which will errback if Tor was unhappy with anything, or callback with this TorConfig object on success.
374,020
def get_bulk_asn_whois(addresses=None, retry_count=3, timeout=120): if not isinstance(addresses, list): raise ValueError( ) try: conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM) conn.settimeout(timeout) log.debug() conn.c...
The function for retrieving ASN information for multiple IP addresses from Cymru via port 43/tcp (WHOIS). Args: addresses (:obj:`list` of :obj:`str`): IP addresses to lookup. retry_count (:obj:`int`): The number of times to retry in case socket errors, timeouts, connection resets, e...
374,021
def forward(self, is_train=False): for texec in self.train_execs: texec.forward(is_train=is_train)
Perform a forward pass on each executor.
374,022
def _process_custom_unitary(self, node): name = node.name if node.arguments is not None: args = self._process_node(node.arguments) else: args = [] bits = [self._process_bit_id(node_element) for node_element in node.bitlist.children] ...
Process a custom unitary node.
374,023
def on(self, analyte=None, filt=None): if isinstance(analyte, str): analyte = [analyte] if isinstance(filt, (int, float)): filt = [filt] elif isinstance(filt, str): filt = self.fuzzmatch(filt, multi=True) if analyte is None: analy...
Turn on specified filter(s) for specified analyte(s). Parameters ---------- analyte : optional, str or array_like Name or list of names of analytes. Defaults to all analytes. filt : optional. int, str or array_like Name/number or iterable names/number...
374,024
def alpha_beta_aligned(returns, factor_returns, risk_free=0.0, period=DAILY, annualization=None, out=None): if out is None: out = np.empty(returns.shape[1:] + (2,), dtype=) b = beta_a...
Calculates annualized alpha and beta. If they are pd.Series, expects returns and factor_returns have already been aligned on their labels. If np.ndarray, these arguments should have the same shape. Parameters ---------- returns : pd.Series or np.ndarray Daily returns of the strategy, ...
374,025
def _insert_compressed( collection_name, docs, check_keys, continue_on_error, opts, ctx): op_insert, max_bson_size = _insert( collection_name, docs, check_keys, continue_on_error, opts) rid, msg = _compress(2002, op_insert, ctx) return rid, msg, max_bson_size
Internal compressed unacknowledged insert message helper.
374,026
def run_preassembly(stmts_in, **kwargs): dump_pkl_unique = kwargs.get() belief_scorer = kwargs.get() use_hierarchies = kwargs[] if in kwargs else \ hierarchies be = BeliefEngine(scorer=belief_scorer) pa = Preassembler(hierarchies, stmts_in) run_preassembly_duplicate(pa, be, save=du...
Run preassembly on a list of statements. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to preassemble. return_toplevel : Optional[bool] If True, only the top-level statements are returned. If False, all statements are returned irrespectiv...
374,027
def add_resource(self, value, name: str = , context_attr: str = None, types: Union[type, Sequence[type]] = ()) -> None: assert check_argument_types() self._check_closed() if isinstance(types, type): types = (types,) elif not types: ty...
Add a resource to this context. This will cause a ``resource_added`` event to be dispatched. :param value: the actual resource value :param name: name of this resource (unique among all its registered types within a single context) :param context_attr: name of the context a...
374,028
def getopt(self, name, argv, opts): while argv and argv[0] and argv[0][0] == : try: argv = opts[argv[0]].parse(name, self, argv) except KeyError: raise OptionError( % argv[0]) except IndexError: raise OptionError( % ar...
getopt(name, argv, opts) Parse X command line options, inserting the recognised options into the resource database. NAME is the application name, and will be prepended to all specifiers. ARGV is the list of command line arguments, typically sys.argv[1:]. OPTS is a map...
374,029
def can_use_autofor(self, node): auto_for = (isinstance(node.target, ast.Name) and node.target.id in self.scope[node] and node.target.id not in self.openmp_deps) auto_for &= not metadata.get(node, OMPDirective) auto_for &= node.target.id not in se...
Check if given for Node can use autoFor syntax. To use auto_for: - iterator should have local scope - yield should not be use - OpenMP pragma should not be use TODO : Yield should block only if it is use in the for loop, not in the whole function.
374,030
def simxGetFloatingParameter(clientID, paramIdentifier, operationMode): paramValue = ct.c_float() return c_GetFloatingParameter(clientID, paramIdentifier, ct.byref(paramValue), operationMode), paramValue.value
Please have a look at the function description/documentation in the V-REP user manual
374,031
def add_connection(self, host): self.hosts.append(host) self.set_connections(self.hosts)
Create a new :class:`~elasticsearch.Connection` instance and add it to the pool. :arg host: kwargs that will be used to create the instance
374,032
def nr_of_antenna(nbl, auto_correlations=False): t = 1 if auto_correlations is False else -1 return int(t + math.sqrt(1 + 8*nbl)) // 2
Compute the number of antenna for the given number of baselines. Can specify whether auto-correlations should be taken into account
374,033
def f(self, m): if len(self.children) == 0: return self._f(m) elif len(self.children) == 1: return self._f(m) and self.children[0].f(m) else: raise Exception( f"{self.__name__} does not support more than one child Matcher" ...
The recursively composed version of filter function f. By default, returns logical **conjunction** of operator and single child operator
374,034
def forward_events_to(self, sink, include_source=False): assert isinstance(sink, Eventful), f self._forwards[sink] = include_source
This forwards signal to sink
374,035
def download_csv(data, filename): assert_is_type(data, H2OFrame) assert_is_type(filename, str) url = h2oconn.make_url("DownloadDataset", 3) + "?frame_id={}&hex_string=false".format(data.frame_id) with open(filename, "wb") as f: f.write(urlopen()(url).read())
Download an H2O data set to a CSV file on the local disk. Warning: Files located on the H2O server may be very large! Make sure you have enough hard drive space to accommodate the entire file. :param data: an H2OFrame object to be downloaded. :param filename: name for the CSV file where the data shoul...
374,036
def md5(text): h = hashlib.md5() h.update(_unicode(text).encode("utf-8")) return h.hexdigest()
Returns the md5 hash of a string.
374,037
def delete_chat_photo(chat_id, **kwargs): params = dict(chat_id=chat_id) return TelegramBotRPCRequest(, params=params, on_result=lambda result: result, **kwargs)
Use this method to delete a chat photo. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) ...
374,038
def crsConvert(crsIn, crsOut): if isinstance(crsIn, osr.SpatialReference): srs = crsIn.Clone() else: srs = osr.SpatialReference() if isinstance(crsIn, int): crsIn = .format(crsIn) if isinstance(crsIn, str): try: srs.S...
convert between different types of spatial references Parameters ---------- crsIn: int, str or :osgeo:class:`osr.SpatialReference` the input CRS crsOut: {'wkt', 'proj4', 'epsg', 'osr', 'opengis' or 'prettyWkt'} the output CRS type Returns ------- int, str or :osgeo:class:`o...
374,039
def acquire(self, tag, blocking=True): logger.debug("Acquiring %s", tag) if not self._semaphore.acquire(blocking): raise NoResourcesAvailable("Cannot acquire tag " % tag)
Acquire the semaphore :param tag: A tag identifying what is acquiring the semaphore. Note that this is not really needed to directly use this class but is needed for API compatibility with the SlidingWindowSemaphore implementation. :param block: If True, block until ...
374,040
def with_user_roles(roles): def wrapper(f): @functools.wraps(f) def wrapped(*args, **kwargs): if current_user.is_authenticated(): if not hasattr(current_user, "role"): raise AttributeError("<> doesncurrent_user'") if current_user.r...
with_user_roles(roles) It allows to check if a user has access to a view by adding the decorator with_user_roles([]) Requires flask-login In your model, you must have a property 'role', which will be invoked to be compared to the roles provided. If current_user doesn't have a role, it will t...
374,041
def read(fname,**kw): Ext remove the edges from domains before concatenation and dons, that is, the grid information. Usually redundant with x,y,z returned. return_array -- If set to truthy, then try to return a numpy array with a dtype. Requires of co...
Reads an lsp output file and returns a raw dump of data, sectioned into quantities either as an dictionary or a typed numpy array. Parameters: ----------- fname -- filename of thing to read Keyword Arguments: ------------------ vprint -- Verbose printer. Used in scripts overri...
374,042
def options(self, **options): self._contexts.append(self._contexts[-1].copy()) self.set_options(**options) try: yield finally: self._contexts.pop(-1)
A context-manager for setting connection options; the original values of the options will be restored when the context-manager exits. For example:: with c.options(gui_mode = False): c.cmd.vol_list()
374,043
def state(name): try: cmd = .format(name) return _machinectl(cmd, ignore_retcode=True)[].split()[-1] except IndexError: return
Return state of container (running or stopped) CLI Example: .. code-block:: bash salt myminion nspawn.state <name>
374,044
def _remove_extraneous_xml_declarations(xml_str): xml_declaration = if xml_str.startswith(): xml_declaration, xml_str = xml_str.split(, maxsplit=1) xml_declaration += xml_str = re.sub(r, , xml_str, flags=re.I) return xml_declaration + xml_str
Sometimes devices return XML with more than one XML declaration in, such as when returning their own XML config files. This removes the extra ones and preserves the first one.
374,045
def SetSize(self, rect): "Called to position/size the edit control within the cell rectangle." self._tc.SetDimensions(rect.x, rect.y, rect.width+2, rect.height+2, wx.SIZE_ALLOW_MINUS_ONE)
Called to position/size the edit control within the cell rectangle.
374,046
def handle_exception(self, exc): if isinstance( exc, (rest_exceptions.NotAuthenticated, rest_exceptions.AuthenticationFailed)) and self.HANDLE_UNAUTHENTICATED: return HttpResponseRedirect(.format( reverse(), self.request.get_full...
Use custom exception handler for errors.
374,047
def token(config, token): if not token: info_out( "To generate a personal API token, go to:\n\n\t" "https://github.com/settings/tokens\n\n" "To read more about it, go to:\n\n\t" "https://help.github.com/articles/creating-an-access" "-token-for...
Store and fetch a GitHub access token
374,048
def install_docs(instance, clear_target): _check_root() def make_docs(): log("Generating HTML documentation") try: build = Popen( [ , ], cwd= ) build.wai...
Builds and installs the complete HFOS documentation.
374,049
def payload_unregister(klass, pid): cmd = [] for x in [klass, pid]: cmd.append(x) subprocess.check_call(cmd)
is used while a hook is running to let Juju know that a payload has been manually stopped. The <class> and <id> provided must match a payload that has been previously registered with juju using payload-register.
374,050
def _norm_default(x): import scipy.linalg if _blas_is_applicable(x.data): nrm2 = scipy.linalg.blas.get_blas_funcs(, dtype=x.dtype) norm = partial(nrm2, n=native(x.size)) else: norm = np.linalg.norm return norm(x.data.ravel())
Default Euclidean norm implementation.
374,051
def get_subfolders(self): headers = self.headers endpoint = + self.id + r = requests.get(endpoint, headers=headers) if check_response(r): return self._json_to_folders(self.account, r.json())
Retrieve all child Folders inside of this Folder. Raises: AuthError: Raised if Outlook returns a 401, generally caused by an invalid or expired access token. Returns: List[:class:`Folder <pyOutlook.core.folder.Folder>`]
374,052
def _on_stackexchange_user(self, future, access_token, response): response[] = access_token future.set_result(response)
Invoked as a callback when self.stackexchange_request returns the response to the request for user data. :param method future: The callback method to pass along :param str access_token: The access token for the user's use :param dict response: The HTTP response already decoded
374,053
def cols_strip(df,col_list, dest = False): if not dest: return _pd.DataFrame({col_name:col_strip(df,col_name) for col_name in col_list}) for col_name in col_list: col_strip(df,col_name,dest)
Performs str.strip() a column of a DataFrame Parameters: df - DataFrame DataFrame to operate on col_list - list of strings names of columns to strip dest - bool, default False Whether to apply the result to the DataFrame or return it. True is apply, False is return.
374,054
def _yum_pkginfo(output): cur = {} keys = itertools.cycle((, , )) values = salt.utils.itertools.split(_strip_headers(output)) osarch = __grains__[] for (key, value) in zip(keys, values): if key == : try: cur[], cur[] = value.rsplit(, 1) except Val...
Parse yum/dnf output (which could contain irregular line breaks if package names are long) retrieving the name, version, etc., and return a list of pkginfo namedtuples.
374,055
def print_log(value_color="", value_noncolor=""): HEADER = ENDC = print(HEADER + value_color + ENDC + str(value_noncolor))
set the colors for text.
374,056
def get_group_filters(self): group_filters = [] field_map = { "feature-type": "feature_type.slug", "tag": "tags.slug", "content-type": "_type" } for group_set in self.query.get("groups", []): for group in group_set: ...
Return es OR filters to include all special coverage group conditions.
374,057
def axes(self): out = self._axes[:] if self._horizontalAxis: out.append(self._horizontalAxis) if self._verticalAxis: out.append(self._verticalAxis) return out
Returns all the axes that have been defined for this chart. :return [<projexui.widgets.xchart.XChartAxis>, ..]
374,058
def _get_placeholders(sql_statement, parameters): placeholders = {} try: for match in REGEX_PATTERN_SQL_PLACEHOLDERS.findall(sql_statement): for (i, placeholder_type) in enumerate(PlaceholderType._values): placeholder_name = mat...
Retrieve the list of placeholders and their type defined in an SQL statement. @param sql_statement: a parameterized statement. @param parameters: the list of parameters used in the SQL statement. @return: a dictionary of placeholders where the key represents the name of ...
374,059
def isIsosceles(self): return (self.a == self.b) or (self.a == self.c) or (self.b == self.c)
True iff two side lengths are equal, boolean.
374,060
def match1(pattern, data, **parse_kwargs): matches = match(pattern, data, **parse_kwargs) return matches[0] if matches else None
Returns first matched value of pattern in data or None if no matches
374,061
def _sanity_check_construct_result_block(ir_blocks): if not isinstance(ir_blocks[-1], ConstructResult): raise AssertionError(u.format(ir_blocks)) for block in ir_blocks[:-1]: if isinstance(block, ConstructResult): raise AssertionError(u u.format(...
Assert that ConstructResult is always the last block, and only the last block.
374,062
def enumerate_chunks (phrase, spacy_nlp): if (len(phrase) > 1): found = False text = " ".join([rl.text for rl in phrase]) doc = spacy_nlp(text.strip(), parse=True) for np in doc.noun_chunks: if np.text != text: found = True yield np.t...
iterate through the noun phrases
374,063
def update(self): data = self._get_data() msg = [] for entry in data: link = self._get_entry_link(entry) stored_entry, is_new = Post.objects.get_or_create(link=link) self._store_post(stored_entry, entry) if is_new is Tru...
This method should be called to update associated Posts It will call content-specific methods: _get_data() to obtain list of entries _store_post() to store obtained entry object _get_data_source_url() to get an URL to identify Posts from this Data Source
374,064
def canonicalize_path(cwd, path): if not os.path.isabs(path): path = os.path.join(cwd, path) return os.path.abspath(path)
Canonicalizes a path relative to a given working directory. That is, the path, if not absolute, is interpreted relative to the working directory, then converted to absolute form. :param cwd: The working directory. :param path: The path to canonicalize. :returns: The absolute path.
374,065
def to_repr(value, ctx): as_string = to_string(value, ctx) if isinstance(value, str) or isinstance(value, datetime.date) or isinstance(value, datetime.time): as_string = as_string.replace(, ) as_string = % as_string return as_string
Converts a value back to its representation form, e.g. x -> "x"
374,066
def simplex_summation_matrix(simplices, weight=None, inverse=False): simplices = np.asarray(simplices) n = np.max(simplices) + 1 (d,m) = simplices.shape rng = range(m) if inverse: if weight is None: f = sps.csr_matrix else: nrng = range(n) ww = sps.csr_ma...
simplex_summation_matrix(mtx) yields a scipy sparse array matrix that, when dotted with a column vector of length m (where m is the number of simplices described in the simplex matrix, mtx), yields a vector of length n (where n is the number of vertices in the simplex mesh); the returned vetor is the ...
374,067
def zplane(self,auto_scale=True,size=2,detect_mult=True,tol=0.001): iir_d.sos_zplane(self.sos,auto_scale,size,tol)
Plot the poles and zeros of the FIR filter in the z-plane
374,068
def set_server_key(self, zmq_socket, server_secret_key_path): load_and_set_key(zmq_socket, server_secret_key_path) zmq_socket.curve_server = True
must call before bind
374,069
def reset_options(self, empty=True): if empty: self.gc = pd.DataFrame(columns=self.clmn) else: self.gc["value"] = self.gc["default"]
Empty ALL options. :param bool empty: When :data:`True`, completelly removes all options; when :data:`False`, sets them back to its original value. This function skips ``locked`` control.
374,070
def get_potential_markables(docgraph): potential_markables = [] for node_id, nattr in dg.select_nodes_by_layer(docgraph, , data=True): if nattr[] == : pp_parent = False for source, target in docgraph.in_edges(node_id): parent_node = docgraph.nod...
returns a list of all NPs and PPs in the given docgraph. Parameters ---------- docgraph : DiscourseDocumentGraph a document graph that (at least) contains syntax trees (imported from Tiger XML files) Returns ------- potential_markables : list of str or int Node IDs of a...
374,071
def checkIfRemoteIsNewer(self, localfile, remote_size, remote_modify): is_remote_newer = False status = os.stat(localfile) LOG.info( "\nLocal file size: %i" "\nLocal Timestamp: %s", status[ST_SIZE], datetime.fromtimestamp(status.st_mtime)) rem...
Overrides checkIfRemoteIsNewer in Source class :param localfile: str file path :param remote_size: str bytes :param remote_modify: str last modify date in the form 20160705042714 :return: boolean True if remote file is newer else False
374,072
def gpg_list_app_keys( blockchain_id, appname, proxy=None, wallet_keys=None, config_dir=None ): raise Exception("BROKEN; depends on list_mutable_data") assert is_valid_appname(appname) config_dir = get_config_dir( config_dir ) client_config_path = os.path.join(config_dir, blockstack_client.CONFI...
List the set of available GPG keys tagged for a given application. Return list of {'keyName': key name, 'contentUrl': URL to key data} Raise on error
374,073
def encode_offset_commit_request(cls, client_id, correlation_id, group, group_generation_id, consumer_id, payloads): grouped_payloads = group_by_topic_and_partition(payloads) message = cls._encode_message_header( ...
Encode some OffsetCommitRequest structs (v1) :param bytes client_id: string :param int correlation_id: int :param str group: the consumer group to which you are committing offsets :param int group_generation_id: int32, generation ID of the group :param str consumer_id: string, I...
374,074
def from_xml_node(xml_node): def gather_enum_values(): l = [] for element in xml_node.iterfind(): l.append(element.text) return l name = xml_node.findtext("name") type = xml_node.tag if type in ("label", "description"): retu...
constructs a CLI.Parameter from an xml node. :param xml_node: :type xml_node: xml.etree.ElementTree.Element :rtype: Executable.Parameter :return:
374,075
def add_filter(self, filter_, frequencies=None, dB=True, analog=False, sample_rate=None, **kwargs): if not analog: if not sample_rate: raise ValueError("Must give sample_rate frequency to display " "digital (analog=False) f...
Add a linear time-invariant filter to this BodePlot Parameters ---------- filter_ : `~scipy.signal.lti`, `tuple` the filter to plot, either as a `~scipy.signal.lti`, or a `tuple` with the following number and meaning of elements - 2: (numerator, denomin...
374,076
def info(name, location=): r\\minion-id if name not in list_tasks(location): return .format(name, location) with salt.utils.winapi.Com(): task_service = win32com.client.Dispatch("Schedule.Service") task_service.Connect() task_folder = task_service.GetFolder(location)...
r''' Get the details about a task in the task scheduler. :param str name: The name of the task for which to return the status :param str location: A string value representing the location of the task. Default is '\\' which is the root for the task scheduler (C:\Windows\System32\tasks). ...
374,077
def fetch_withdrawals(self, limit: int) -> List[Withdrawal]: return self._transactions(self._withdrawals, , limit)
Fetch latest withdrawals, must provide a limit.
374,078
def set_value(self, value, layer=None, source=None): if self._frozen: raise TypeError() if not layer: layer = self._layers[-1] self._values[layer] = (source, value)
Set a value for a particular layer with optional metadata about source. Parameters ---------- value : str Data to store in the node. layer : str Name of the layer to use. If None then the outermost where the value exists will be used. source :...
374,079
def brief_exception_text(exception, secret_values): exception_text = _hide_secret_values(str(exception), secret_values) return .format(type(exception).__name__, exception_text)
Returns the Exception class and the message of the exception as string. :param exception: The exception to format :param secret_values: Values to hide in output
374,080
def json_path_components(path): if isinstance(path, str): path = path.split() return list(path)
Convert JSON path to individual path components. :param path: JSON path, which can be either an iterable of path components or a dot-separated string :return: A list of path components
374,081
def add(self, variant, arch, image): if arch not in productmd.common.RPM_ARCHES: raise ValueError("Arch not found in RPM_ARCHES: %s" % arch) if arch in ["src", "nosrc"]: raise ValueError("Source arch is not allowed. Map source files under binary arches.") if sel...
Assign an :class:`.Image` object to variant and arch. :param variant: compose variant UID :type variant: str :param arch: compose architecture :type arch: str :param image: image :type image: :class:`.Image`
374,082
def remove_adapter(widget_class, flavour=None): for it,tu in enumerate(__def_adapter): if (widget_class == tu[WIDGET] and flavour == tu[FLAVOUR]): del __def_adapter[it] return True return False
Removes the given widget class information from the default set of adapters. If widget_class had been previously added by using add_adapter, the added adapter will be removed, restoring possibly previusly existing adapter(s). Notice that this function will remove only *one* adapter about given wige...
374,083
def createmergerequest(self, project_id, sourcebranch, targetbranch, title, target_project_id=None, assignee_id=None): data = { : sourcebranch, : targetbranch, : title, : assignee_id, : target_project_id } ...
Create a new merge request. :param project_id: ID of the project originating the merge request :param sourcebranch: name of the branch to merge from :param targetbranch: name of the branch to merge to :param title: Title of the merge request :param assignee_id: Assignee user ID ...
374,084
def clear_priority(self): if (self.get_priority_metadata().is_read_only() or self.get_priority_metadata().is_required()): raise errors.NoAccess() self._my_map[] = self._priority_default
Removes the priority. raise: NoAccess - ``Metadata.isRequired()`` is ``true`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.*
374,085
def _render(self, contexts, partials): value = self._lookup(self.value, contexts) if callable(value): value = inner_render(str(value()), contexts, partials) return self._escape(value)
render variable
374,086
def items(self): logger.debug() return [(key, self.get(key)) for key in self.keys()]
Return list of tuples of keys and values in db >>> dc = Dictator() >>> dc['l0'] = [1, 2, 3, 4] >>> dc.items() [('l0', ['1', '2', '3', '4'])] >>> dc.clear() :return: list of (key, value) pairs :rtype: list of tuple
374,087
def parse_file(file): lines = [] for line in file: line = line.rstrip() if line == : lines[-1] += line[1:] else: lines.append(line) yield from parse_item(lines)
Take an open file containing the IANA subtag registry, and yield a dictionary of information for each subtag it describes.
374,088
def is_tuple_end(self, extra_end_rules=None): if self.stream.current.type in (, , ): return True elif extra_end_rules is not None: return self.stream.current.test_any(extra_end_rules) return False
Are we at the end of a tuple?
374,089
def textFileStream(self, directory, process_all=False): deserializer = FileTextStreamDeserializer(self._context) file_stream = FileStream(directory, process_all) self._on_stop_cb.append(file_stream.stop) return DStream(file_stream, self, deserializer)
Monitor a directory and process all text files. File names starting with ``.`` are ignored. :param string directory: a path :param bool process_all: whether to process pre-existing files :rtype: DStream .. warning:: The ``process_all`` parameter does not exist in t...
374,090
def set_glitch_filter(self, user_gpio, steady): res = yield from self._pigpio_aio_command(_PI_CMD_FG, user_gpio, steady) return _u2i(res)
Sets a glitch filter on a GPIO. Level changes on the GPIO are not reported unless the level has been stable for at least [*steady*] microseconds. The level is then reported. Level changes of less than [*steady*] microseconds are ignored. user_gpio:= 0-31 steady:= 0-3...
374,091
def cmd_list(self, argv, help): parser = argparse.ArgumentParser( prog="%s list" % self.progname, description=help, ) parser.add_argument("list", nargs=1, metavar="listname", help="Name of list to show.", ...
Return a list of various things
374,092
def set_default_headers(context): headers = row_table(context) def default_headers_function(): return headers requestsdefaulter.default_headers(default_headers_function)
:type context: behave.runner.Context
374,093
def collate_revs(old, new, key=lambda x: x, merge=lambda old, new: new): missing = object() def maybe_merge(*items): def not_missing(ob): return ob is not missing return functools.reduce(merge, filter(not_missing, items)) new_items = collections.OrderedDict( (key(el), el) for el in new ) old_ite...
Given revision sets old and new, each containing a series of revisions of some set of objects, collate them based on these rules: - all items from each set are yielded in stable order - items in old are yielded first - items in new are yielded last - items that match are yielded in the order in which they appea...
374,094
def _update_history(self): version = self.data[] history = self.vcs.history_file() if not history: logger.warn("No history file found") return history_lines = open(history).read().split() headings = utils.extract_headings_from_history(history_line...
Update the history file
374,095
def add(name, **kwargs): * if not info(name): comp_obj = _get_computer_object() try: new_group = comp_obj.Create(, name) new_group.SetInfo() log.info(, name) except pywintypes.com_error as exc: msg = .format( name, win32api....
Add the specified group Args: name (str): The name of the group to add Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' group.add foo
374,096
def get_metadata(self): if self._metadata is None: self._metadata = ImageMetadata() inspect_to_metadata(self._metadata, self.inspect(refresh=True)) return self._metadata
Provide metadata about this image. :return: ImageMetadata, Image metadata instance
374,097
def LeaseCronJobs(self, cronjob_ids=None, lease_time=None): leased_jobs = [] now = rdfvalue.RDFDatetime.Now() expiration_time = now + lease_time for job in itervalues(self.cronjobs): if cronjob_ids and job.cron_job_id not in cronjob_ids: continue existing_lease = self.cronjob_...
Leases all available cron jobs.
374,098
def tool_click(self, evt): "Event handler tool selection (just add to default handler)" ctrl = self.menu_ctrl_map[evt.GetId()] if self.inspector.selected_obj: parent = self.inspector.selected_obj while parent.drop_target is None and par...
Event handler tool selection (just add to default handler)
374,099
def get_revision(): proc = Process("git log", ["git", "log", "-1"]) try: while True: line = proc.stdout.pop().strip().decode() if not line: continue if line.startswith("commit "): return line[7:] finally: with suppress...
GET THE CURRENT GIT REVISION