docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Add a value to knowledge graph by giving a jsonpath Args: field_name: str jsonpath: str Returns:
def _add_doc_value(self, field_name: str, jsonpath: str) -> None: path = self.origin_doc.etk.parse_json_path(jsonpath) matches = path.find(self.origin_doc.value) all_valid = True invalid = [] for a_match in matches: # If the value is the empty string, we trea...
572,141
Get a list of all the values of a field. Args: field_name: Returns: the list of values (not the keys)
def get_values(self, field_name: str) -> List[object]: result = list() if self.validate_field(field_name): for value_key in self._kg.get(field_name): result.append(value_key["value"]) return result
572,143
Initialize the extractor, storing the rule information and construct spacy rules Args: nlp: tokenizer: Tokenizer extractor_name: str Returns:
def __init__(self, nlp, tokenizer, extractor_name: str) -> None: Extractor.__init__(self, input_type=InputType.TEXT, category="build_in_extractor", name=extractor_name) ...
572,170
Check if the email provider should be filtered Args: tokens: Returns: Bool
def _check_domain(tokens) -> bool: idx = None for e in tokens: if e.text == "@": idx = e.i break if not idx or tokens[idx+1].text in FILTER_PROVIDER: return False else: return True
572,172
Deal with corner case that there is "email" string in text and no space around it Args: doc: List[Token] Returns: Bool
def _get_non_space_email(self, doc) -> List: result_lst = [] for e in doc: if "mail:" in e.text.lower(): idx = e.text.lower().index("mail:") + 5 value = e.text[idx:] tmp_doc = self._nlp(value) tmp_email_matches = self._...
572,173
Tokenize the given text, returning a list of tokens. Type token: class spacy.tokens.Token Args: text (string): Returns: [tokens]
def tokenize(self, text: str, customize=True, disable=[]) -> List[Token]: if not self.keep_multi_space: text = re.sub(' +', ' ', text) # disable spacy parsing, tagging etc as it takes a long time if the text is short tokens = self.nlp(text, disable=disable) ...
572,175
Tokenize the given text, returning a spacy doc. Used for spacy rule extractor Args: text (string): Returns: Doc
def tokenize_to_spacy_doc(self, text: str) -> Doc: if not self.keep_multi_space: text = re.sub(' +', ' ', text) doc = self.nlp(text, disable=['parser']) for a_token in doc: self.custom_token(a_token) return doc
572,176
Given a list of tokens, reconstruct the original text with as much fidelity as possible. Args: [tokens]: Returns: a string.
def reconstruct_text(tokens: List[Token]) -> str: return "".join([x.text_with_ws for x in tokens])
572,179
Run ``{scp} {localfile} {remote}:{remotefile}`` Parameters: localfile (str): relative or absolute path to a local file remote (str): Host on which to put the file remotefile (str): remote path where to put the file. May start with '~' to indicate the home directory. scp ...
def upload_file(localfile, remote, remotefile, scp='scp'): sp.check_output( [scp, localfile, remote+':'+remotefile], stderr=sp.STDOUT)
572,478
Returns a sequence of Tokens. Args: source: string of C++ source code. Yields: Token that represents the next token in the source.
def get_tokens(source): if not source.endswith('\n'): source += '\n' # Cache various valid character sets for speed. valid_identifier_first_chars = VALID_IDENTIFIER_FIRST_CHARS valid_identifier_chars = VALID_IDENTIFIER_CHARS hex_digits = HEX_DIGITS int_or_float_digits = INT_OR_FLOA...
573,087
Utility method that returns an ASTBuilder from source code. Args: source: 'C++ source code' filename: 'file1' Returns: ASTBuilder
def builder_from_source(source, filename, system_includes, nonsystem_includes, quiet=False): return ASTBuilder(tokenize.get_tokens(source), filename, system_includes, nonsystem_includes, quiet=quiet)
573,090
Helper for lookup_symbol that only looks up variables in a namespace. Args: symbol: Symbol namespace: pointer into self.namespaces
def _lookup_namespace(self, symbol, namespace): for namespace_part in symbol.parts: namespace = namespace.get(namespace_part) if namespace is None: break if not isinstance(namespace, dict): return namespace raise Error('%s not ...
573,151
Helper for lookup_symbol that only looks up global variables. Args: symbol: Symbol
def _lookup_global(self, symbol): assert symbol.parts namespace = self.namespaces if len(symbol.parts) == 1: # If there is only one part, look in globals. namespace = self.namespaces[None] try: # Try to do a normal, global namespace lookup. ...
573,152
Helper for lookup_symbol that looks for symbols in all namespaces. Args: symbol: Symbol
def _lookup_in_all_namespaces(self, symbol): namespace = self.namespaces # Create a stack of namespaces. namespace_stack = [] for current in symbol.namespace_stack: namespace = namespace.get(current) if namespace is None or not isinstance(namespace, dict)...
573,153
Returns AST node and module for symbol if found. Args: name: 'name of the symbol to lookup' namespace_stack: None or ['namespaces', 'in', 'current', 'scope'] Returns: (ast.Node, module (ie, any object stored with symbol)) if found Raises: Error if the s...
def lookup_symbol(self, name, namespace_stack): # TODO(nnorwitz): a convenient API for this depends on the # representation of the name. e.g., does symbol_name contain # ::, is symbol_name a list of colon separated names, how are # names prefixed with :: handled. These have diff...
573,154
Adds symbol_name defined in namespace_stack to the symbol table. Args: symbol_name: 'name of the symbol to lookup' namespace_stack: None or ['namespaces', 'symbol', 'defined', 'in'] node: ast.Node that defines this symbol module: module (any object) this symbol is define...
def add_symbol(self, symbol_name, namespace_stack, node, module): # TODO(nnorwitz): verify symbol_name doesn't contain :: ? if namespace_stack: # Handle non-global symbols (ie, in some namespace). last_namespace = self.namespaces for namespace in namespace_st...
573,156
Returns the prefix of names from name_seq that are known namespaces. Args: name_seq: ['names', 'of', 'possible', 'namespace', 'to', 'find'] Returns: ['names', 'that', 'are', 'namespaces', 'possibly', 'empty', 'list']
def get_namespace(self, name_seq): namespaces = self.namespaces result = [] for name in name_seq: namespaces = namespaces.get(name) if not namespaces: break result.append(name) return result
573,157
Send a remote command to a service. Used Args: target: The service that the command gets set to remote_command: The command to do remotely. source: the binary source of the zmq_socket. Packed to send to the
def do_REMOTE(self, target: str, remote_command: str, source: list, *args, **kwargs) -> None: if target == self.messaging._service_name: info = 'target for remote command is the bot itself! Returning t...
573,568
Perform identification of a service to a binary representation. Args: service_name: human readable name for service source: zmq representation for the socket source
def do_IDENT(self, service_name: str, source: list, *args, **kwargs) -> None: self.logger.info(' IDENT %s as %s', service_name, source) self.messaging._address_map[service_name] = source
573,571
Run the internal control loop. Args: blocking (bool): Defaults to `True`. If set to `False`, will intialize a thread to run the control loop. Raises: RuntimeError: If called and not using the internal control loop via `self._run_control_loop`, set ...
def run(self, blocking: bool=True): if not self._run_control_loop: err = ("`run` called, but not using the internal control loop. Use" " `start` instead") raise RuntimeError(err) self._setup() self._heartbeat_reciever.start() if bloc...
573,647
Validates the extension version matches the requested version. Args: min_version: Minimum version passed as a query param when establishing the connection. Returns: An ExtensionVersionResult indicating validation status. If there is a problem, the error_reason field will be non-empty.
def _validate_min_version(min_version): if min_version is not None: try: parsed_min_version = version.StrictVersion(min_version) except ValueError: return ExtensionVersionResult( error_reason=ExtensionValidationError.UNPARSEABLE_REQUESTED_VERSION, requested_extension_version...
574,203
Initializes a DelaunayTri from points. Args: points ([[float]]): All the points as a sequence of sequences. e.g., [[-0.5, -0.5], [-0.5, 0.5], [0.5, -0.5], [0.5, 0.5]] joggle (bool): Use qhull option to joggle inputs until simplical result is obtained inst...
def __init__(self, points, joggle=False): self.points = points dim = [len(i) for i in self.points] if max(dim) != min(dim): raise ValueError("Input points must all have the same dimension!") self.dim = dim[0] if joggle: options = "i QJ" el...
574,561
Initializes a Simplex from vertex coordinates. Args: coords ([[float]]): Coords of the vertices of the simplex. E.g., [[1, 2, 3], [2, 4, 5], [6, 7, 8], [8, 9, 10].
def __init__(self, coords): self._coords = np.array(coords) self.simplex_dim, self.space_dim = self._coords.shape self.origin = self._coords[-1] if self.simplex_dim == self.space_dim + 1: # precompute attributes for calculating bary_coords self.T = self._...
574,565
Initializes a Halfspace. Args: normal: vector normal to hyperplane offset: offset of hyperplane from origin
def __init__(self, normal, offset): self.normal = normal self.offset = offset
574,571
Returns a Halfspace defined by a list of vectors parallel to the bounding hyperplane. Args: basis: basis for the hyperplane (array with vector rows) origin: point on the hyperplane point: point not on the hyperplane internal: whether point is inside the h...
def from_hyperplane(basis, origin, point, internal = True): basis = np.array(basis) assert basis.shape[0] + 1 == basis.shape[1] big_basis = np.zeros((basis.shape[1], basis.shape[1])) big_basis[:basis.shape[0],:basis.shape[1]] = basis u, s, vh = np.linalg.svd(big_basis)...
574,572
Initializes a VoronoiTess from points. Args: points ([[float]]): All the points as a sequence of sequences. e.g., [[-0.5, -0.5], [-0.5, 0.5], [0.5, -0.5], [0.5, 0.5]] add_bounding_box (bool): If True, a hypercube corresponding to the extremes of each coor...
def __init__(self, points, add_bounding_box=False): self.points = list(points) dim = [len(i) for i in self.points] if max(dim) != min(dim): raise ValueError("Input points must all have the same dimension!") self.dim = dim[0] if add_bounding_box: c...
574,578
Find files that does not exist, are not in the repo or are directories. Args: filenames: list of filenames to check repository_root: the absolute path of the repository's root. Returns: A list of errors.
def find_invalid_filenames(filenames, repository_root): errors = [] for filename in filenames: if not os.path.abspath(filename).startswith(repository_root): errors.append((filename, 'Error: File %s does not belong to ' 'repository %s' % (filename, repository_r...
574,980
Formats the data returned by the linters. Given a dictionary with the fields: line, column, severity, message_id, message, will generate a message like: 'line {line}, col {column}: {severity}: [{message_id}]: {message}' Any of the fields may nbe absent. Args: comment_data: dictionary with ...
def format_comment(comment_data): format_pieces = [] # Line and column information if 'line' in comment_data: format_pieces.append('line {line}') if 'column' in comment_data: if format_pieces: format_pieces.append(', ') format_pieces.append('col {column}') if...
574,982
Returns a list of files that has been modified since the last commit. Args: root: the root of the repository, it has to be an absolute path. tracked_only: exclude untracked files when True. commit: SHA1 of the commit. If None, it will get the modified files in the working copy. Retur...
def modified_files(root, tracked_only=False, commit=None): assert os.path.isabs(root), "Root has to be absolute, got: %s" % root command = ['hg', 'status'] if commit: command.append('--change=%s' % commit) # Convert to unicode and split status_lines = subprocess.check_output(command)....
574,987
Filters out the lines not matching the pattern. Args: lines: list[string]: lines to filter. pattern: string: regular expression to filter out lines. Returns: list[string]: the list of filtered lines.
def filter_lines(lines, filter_regex, groups=None): pattern = re.compile(filter_regex) for line in lines: match = pattern.search(line) if match: if groups is None: yield line elif len(groups) == 1: yield match.group(groups[0]) ...
574,998
Returns the output from the cache if still valid. It checks that the cache file is defined and that its modification time is after the modification time of the original file. Args: name: string: name of the linter. filename: string: path of the filename for which we are retrieving the ...
def get_output_from_cache(name, filename): cache_filename = _get_cache_filename(name, filename) if (os.path.exists(cache_filename) and os.path.getmtime(filename) < os.path.getmtime(cache_filename)): with io.open(cache_filename) as f: return f.read() return None
575,002
Saves output in the cache location. Args: name: string: name of the linter. filename: string: path of the filename for which we are saving the output. output: string: full output (not yet filetered) of the lint command.
def save_output_in_cache(name, filename, output): cache_filename = _get_cache_filename(name, filename) with _open_for_write(cache_filename) as f: f.write(output)
575,003
Get the most popular artists on Last.fm by country. Parameters: country (Required) : A country name, as defined by the ISO 3166-1 country names standard. limit (Optional) : The number of results to fetch per page. Defaults to 50.
def get_geo_top_artists(self, country, limit=None, cacheable=True): params = {"country": country} if limit: params["limit"] = limit doc = _Request(self, "geo.getTopArtists", params).execute(cacheable) return _extract_top_artists(doc, self)
575,022
Get the most popular tracks on Last.fm last week by country. Parameters: country (Required) : A country name, as defined by the ISO 3166-1 country names standard location (Optional) : A metro name, to fetch the charts for (must be within the country specified) lim...
def get_geo_top_tracks(self, country, location=None, limit=None, cacheable=True): params = {"country": country} if location: params["location"] = location if limit: params["limit"] = limit doc = _Request(self, "geo.getTopTracks", params).execute(cacheab...
575,023
Check a task. Args: draco_query: a list of facts Returns: whether the task is valid
def is_valid(draco_query: List[str], debug=False) -> bool: _, stdout = run_clingo( draco_query, files=["define.lp", "hard.lp", "hard-integrity.lp"], silence_warnings=True, debug=debug, ) return json.loads(stdout)["Result"] != "UNSATISFIABLE"
575,376
Reads the given JSON file and generates the ASP definition. Args: file: the json data file Returns: the asp definition.
def read_data_to_asp(file: str) -> List[str]: if file.endswith(".json"): with open(file) as f: data = json.load(f) return schema2asp(data2schema(data)) elif file.endswith(".csv"): df = pd.read_csv(file) df = df.where((pd.notnull(df)), None) data = lis...
575,377
Applies the linear differential operator to y Parameters: ----------- y ndarray The array to differentiate Returns: -------- An ndarray with the derivative. It has the same shape as y.
def __call__(self, u, **kwargs): for kwarg in kwargs: if kwarg == "acc": self.set_accuracy(kwargs[kwarg]) else: raise Exception("Unknown kwarg.") if self.acc is None: self.acc = 2 if self.child is not None: ...
576,011
Invoke an HTTP GET request on a url Args: url (string): URL endpoint to request params (dict): Dictionary of url parameters Returns: dict: JSON response as a dictionary
def get(url, params={}): request_url = url if len(params): request_url = "{}?{}".format(url, urlencode(params)) try: req = Request(request_url, headers={'User-Agent': 'Mozilla/5.0'}) response = json.loads(urlopen(req).read().decode("utf-8")) ...
576,835
Get a resource by its id Args: id (string): Resource id Returns: object: Instance of the resource type
def find(self, id): url = "{}/{}/{}".format(__endpoint__, self.type.RESOURCE, id) response = RestClient.get(url)[self.type.RESOURCE[:-1]] return self.type(response)
576,836
Get a list of resources Args: url (string): URL to invoke type (class): Class type resource (string): The REST Resource Returns: list of object: List of resource instances
def find_many(self, url, type, resource): return [type(item) for item in RestClient.get(url)[resource]]
576,837
Find data points on the convex hull of a supplied data set Args: sample: data points as column vectors n x d n - number samples d - data dimension (should be two) Returns: a k x d matrix containint the convex hull data points
def quickhull(sample): link = lambda a, b: np.concatenate((a, b[1:])) edge = lambda a, b: np.concatenate(([a], [b])) def dome(sample, base): h, t = base dists = np.dot(sample - h, np.dot(((0, -1), (1, 0)), (t - h))) outer = np.repeat(sample, dists > 0, axis=0) if len(...
577,101
Ordinal linear discriminant analysis Arguments: ---------- sigma : float Regularization parameter
def __init__(self, sigma=1e-4): self.sigma = sigma self.scatter_ordinal_ = None self.scatter_within_ = None
577,169
Load a ground-truth segmentation, and align times to the nearest detected beats. Arguments: beat_times -- array song -- path to the audio file Returns: segment_beats -- array beat-aligned segment boundaries segment_times -- array true segment times ...
def align_segmentation(beat_times, song): try: segment_times, segment_labels = msaf.io.read_references(song) except: return None, None, None segment_times = np.asarray(segment_times) # Map to intervals segment_intervals = msaf.utils.times_to_intervals(segment_times) # Map ...
577,205
Start background process for get_datas and async task for notifying all subscribed observers Args: macs (list): MAC addresses bt_device (string): Bluetooth device id
def __init__(self, macs=[], bt_device=''): self._run_flag = RunFlag() self._subjects = [] m = Manager() q = m.Queue() # Use Manager dict to share data between processes self._shared_data = m.dict() self._shared_data['run_flag'] = True # Start ...
577,422
Get lates data for sensors in the MAC's list. Args: macs (array): MAC addresses search_duratio_sec (int): Search duration in seconds. Default 5 bt_device (string): Bluetooth device id Returns: dict: MAC and state of found sensors
def get_data_for_sensors(macs=[], search_duratio_sec=5, bt_device=''): log.info('Get latest data for sensors. Stop with Ctrl+C.') log.info('Stops automatically in %ss', search_duratio_sec) log.info('MACs: %s', macs) datas = dict() for new_data in RuuviTagSensor._get_r...
577,435
Get data for all ruuvitag sensors or sensors in the MAC's list. Args: callback (func): callback funcion to be called when new data is received macs (list): MAC addresses run_flag (object): RunFlag object. Function executes while run_flag.running bt_device (string...
def get_datas(callback, macs=[], run_flag=RunFlag(), bt_device=''): log.info('Get latest data for sensors. Stop with Ctrl+C.') log.info('MACs: %s', macs) for new_data in RuuviTagSensor._get_ruuvitag_datas(macs, None, run_flag, bt_device): callback(new_data)
577,436
Get data from BluetoothCommunication and handle data encoding. Args: macs (list): MAC addresses. Default empty list search_duratio_sec (int): Search duration in seconds. Default None run_flag (object): RunFlag object. Function executes while run_flag.running. Default new Run...
def _get_ruuvitag_datas(macs=[], search_duratio_sec=None, run_flag=RunFlag(), bt_device=''): mac_blacklist = [] start_time = time.time() data_iter = ble.get_datas(mac_blacklist, bt_device) for ble_data in data_iter: # Check duration if search_duratio_se...
577,437
Hang up the connection. Arguments: message -- Quit message.
def disconnect(self, message=""): try: del self.connected except AttributeError: return self.quit(message) self.transport.close() self._handle_event(Event("disconnect", self.server, "", [message]))
577,513
Set mode on the channel. Arguments: mode -- The mode (a single-character string). value -- Value
def set_mode(self, mode, value=None): if mode in self.user_modes: self.mode_users[mode][value] = 1 else: self.modes[mode] = value
577,574
Clear mode on the channel. Arguments: mode -- The mode (a single-character string). value -- Value
def clear_mode(self, mode, value=None): try: if mode in self.user_modes: del self.mode_users[mode][value] else: del self.modes[mode] except KeyError: pass
577,575
Send a CAP command according to `the spec <http://ircv3.atheme.org/specification/capability-negotiation-3.1>`_. Arguments: subcommand -- LS, LIST, REQ, ACK, CLEAR, END args -- capabilities, if required for given subcommand Example: .cap('LS') ....
def cap(self, subcommand, *args): cap_subcommands = set('LS LIST REQ ACK NAK CLEAR END'.split()) client_subcommands = set(cap_subcommands) - {'NAK'} assert subcommand in client_subcommands, "invalid subcommand" def _multi_parameter(args): if len(args) >...
577,595
Hang up the connection. Arguments: message -- Quit message.
def disconnect(self, message=""): try: del self.connected except AttributeError: return self.quit(message) try: self.socket.shutdown(socket.SHUT_WR) self.socket.close() except socket.error: pass del se...
577,597
Called when there is more data to read on connection sockets. Arguments: sockets -- A list of socket objects. See documentation for Reactor.__init__.
def process_data(self, sockets): with self.mutex: log.log(logging.DEBUG - 2, "process_data()") for sock, conn in itertools.product(sockets, self.connections): if sock == conn.socket: conn.process_data()
577,609
Process data from connections once. Arguments: timeout -- How long the select() call should wait if no data is available. This method should be called periodically to check and process incoming data, if there are any. If that seems boring, look at t...
def process_once(self, timeout=0): log.log(logging.DEBUG - 2, "process_once()") sockets = self.sockets if sockets: in_, out, err = select.select(sockets, [], [], timeout) self.process_data(in_) else: time.sleep(timeout) self.process_ti...
577,611
Run an infinite loop, processing data from connections. This method repeatedly calls process_once. Arguments: timeout -- Parameter to pass to process_once.
def process_forever(self, timeout=0.2): # This loop should specifically *not* be mutex-locked. # Otherwise no other thread would ever be able to change # the shared state of a Reactor object running this function. log.debug("process_forever(timeout=%s)", timeout) one = f...
577,612
Removes a global handler function. Arguments: event -- Event type (a string). handler -- Callback function. Returns 1 on success, otherwise 0.
def remove_global_handler(self, event, handler): with self.mutex: if event not in self.handlers: return 0 for h in self.handlers[event]: if handler == h.callback: self.handlers[event].remove(h) return 1
577,615
Creates and returns a DCCConnection object. Arguments: dcctype -- "chat" for DCC CHAT connections or "raw" for DCC SEND (or other DCC types). If "chat", incoming data will be split in newline-separated chunks. If "raw", incoming ...
def dcc(self, dcctype="chat"): with self.mutex: conn = DCCConnection(self, dcctype) self.connections.append(conn) return conn
577,616
Connect/reconnect to a DCC peer. Arguments: address -- Host/IP address of the peer. port -- The port number to connect to. Returns the DCCConnection object.
def connect(self, address, port): self.peeraddress = socket.gethostbyname(address) self.peerport = port self.buffer = buffer.LineBuffer() self.handlers = {} self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: self.socket.connect((self...
577,620
Hang up the connection and close the object. Arguments: message -- Quit message.
def disconnect(self, message=""): try: del self.connected except AttributeError: return try: self.socket.shutdown(socket.SHUT_WR) self.socket.close() except socket.error: pass del self.socket self.react...
577,622
Connect to a DCC peer. Arguments: address -- IP address of the peer. port -- Port to connect to. Returns a DCCConnection instance.
def dcc_connect(self, address, port, dcctype="chat"): warnings.warn("Use self.dcc(type).connect()", DeprecationWarning) return self.dcc(dcctype).connect(address, port)
577,629
Initialize an Event. Arguments: type -- A string describing the event. source -- The originator of the event (a nick mask or a server). target -- The target of the event (a nick or a channel). arguments -- Any event-specific arguments.
def __init__(self, type, source, target, arguments=None, tags=None): self.type = type self.source = source self.target = target if arguments is None: arguments = [] self.arguments = arguments if tags is None: tags = [] self.tags = ...
577,631
Dequote a message according to CTCP specifications. The function returns a list where each element can be either a string (normal message) or a tuple of one or two strings (tagged messages). If a tuple has only one element (ie is a singleton), that element is the tag; otherwise the tuple has two eleme...
def dequote(message): # Perform the substitution message = low_level_regexp.sub(_low_level_replace, message) if DELIMITER not in message: return [message] # Split it into parts. chunks = message.split(DELIMITER) return list(_gen_messages(chunks))
577,636
Convert number to percentage string. Parameters: ----------- :param v: numerical value to be converted :param precision: int decimal places to round to
def as_percent(precision=2, **kwargs): if not isinstance(precision, Integral): raise TypeError("Precision must be an integer.") return _surpress_formatting_errors( _format_numer(".{}%".format(precision)) )
578,793
Convert value to unit. Parameters: ----------- :param v: numerical value :param unit: string of unit :param precision: int decimal places to round to :param location: 'prefix' or 'suffix' representing where the currency symbol falls relative to the value
def as_unit(unit, precision=2, location='suffix'): if not isinstance(precision, Integral): raise TypeError("Precision must be an integer.") if location == 'prefix': formatter = partial(_format_numer, prefix=unit) elif location == 'suffix': formatter = partial(_format_numer, suf...
578,794
Generates a RelaxNG Schema for FoLiA. Optionally saves it to file. Args: filename (str): Save the schema to the following filename Returns: lxml.ElementTree: The schema
def relaxng(filename=None): E = ElementMaker(namespace="http://relaxng.org/ns/structure/1.0",nsmap={None:'http://relaxng.org/ns/structure/1.0' , 'folia': NSFOLIA, 'xml' : "http://www.w3.org/XML/1998/namespace"}) grammar = E.grammar( E.start( E.element( #FoLiA E.attribute(name='id',ns="http:...
579,086
Run text validation on this element. Checks whether any text redundancy is consistent and whether offsets are valid. Parameters: warnonly (bool): Warn only (True) or raise exceptions (False). If set to None then this value will be determined based on the document's FoLiA version (Warn only before F...
def textvalidation(self, warnonly=None): if warnonly is None and self.doc and self.doc.version: warnonly = (checkversion(self.doc.version, '1.5.0') < 0) #warn only for documents older than FoLiA v1.5 valid = True for cls in self.doc.textclasses: if self.hastext(...
579,095
Make a deep copy of this element and all its children. Parameters: newdoc (:class:`Document`): The document the copy should be associated with. idsuffix (str or bool): If set to a string, the ID of the copy will be append with this (prevents duplicate IDs when making copies for the same...
def copy(self, newdoc=None, idsuffix=""): if idsuffix is True: idsuffix = ".copy." + "%08x" % random.getrandbits(32) #random 32-bit hash for each copy, same one will be reused for all children c = deepcopy(self) if idsuffix: c.addidsuffix(idsuffix) c.setparents() ...
579,103
Set the text for this element. Arguments: text (str): The text cls (str): The class of the text, defaults to ``current`` (leave this unless you know what you are doing). There may be only one text content element of each class associated with the element.
def settext(self, text, cls='current'): self.replace(TextContent, value=text, cls=cls)
579,110
Associate a document with this element. Arguments: doc (:class:`Document`): A document Each element must be associated with a FoLiA document.
def setdocument(self, doc): assert isinstance(doc, Document) if not self.doc: self.doc = doc if self.id: if self.id in doc: raise DuplicateIDError(self.id) else: self.doc.index[id] = self f...
579,111
Generator yielding all ancestors of this element, effectively back-tracing its path to the root element. A tuple of multiple classes may be specified. Arguments: *Class: The class or classes (:class:`AbstractElement` or subclasses). Not instances! Yields: elements (instances de...
def ancestors(self, Class=None): e = self while e: if e.parent: e = e.parent if not Class or isinstance(e,Class): yield e elif isinstance(Class, tuple): for C in Class: if...
579,122
Find the most immediate ancestor of the specified type, multiple classes may be specified. Arguments: *Classes: The possible classes (:class:`AbstractElement` or subclasses) to select from. Not instances! Example:: paragraph = word.ancestor(folia.Paragraph)
def ancestor(self, *Classes): for e in self.ancestors(tuple(Classes)): return e raise NoSuchAnnotation
579,123
Internal class method used for turning an XML element into an instance of the Class. Args: * ``node`` - XML Element * ``doc`` - Document Returns: An instance of the current Class.
def parsexml(Class, node, doc, **kwargs): #pylint: disable=bad-classmethod-argument assert issubclass(Class, AbstractElement) if doc.preparsexmlcallback: result = doc.preparsexmlcallback(node) if not result: return None if isinstance(result,...
579,140
Returns a generator of Word elements found (recursively) under this element. Arguments: * ``index``: If set to an integer, will retrieve and return the n'th element (starting at 0) instead of returning the list of all
def words(self, index = None): if index is None: return self.select(Word,None,True,default_ignore_structure) else: if index < 0: index = self.count(Word,None,True,default_ignore_structure) + index for i, e in enumerate(self.select(Word,None,Tr...
579,159
Returns a generator of Paragraph elements found (recursively) under this element. Arguments: index (int or None): If set to an integer, will retrieve and return the n'th element (starting at 0) instead of returning the generator of all
def paragraphs(self, index = None): if index is None: return self.select(Paragraph,None,True,default_ignore_structure) else: if index < 0: index = self.count(Paragraph,None,True,default_ignore_structure) + index for i,e in enumerate(self.selec...
579,160
Returns a generator of Sentence elements found (recursively) under this element Arguments: index (int or None): If set to an integer, will retrieve and return the n'th element (starting at 0) instead of returning a generator of all
def sentences(self, index = None): if index is None: return self.select(Sentence,None,True,default_ignore_structure) else: if index < 0: index = self.count(Sentence,None,True,default_ignore_structure) + index for i,e in enumerate(self.select(S...
579,161
Sets the span of the span element anew, erases all data inside. Arguments: *args: Instances of :class:`Word`, :class:`Morpheme` or :class:`Phoneme`
def setspan(self, *args): self.data = [] for child in args: self.append(child)
579,211
Returns a list of word references, these can be Words but also Morphemes or Phonemes. Arguments: index (int or None): If set to an integer, will retrieve and return the n'th element (starting at 0) instead of returning the list of all
def wrefs(self, index = None, recurse=True): targets =[] self._helper_wrefs(targets, recurse) if index is None: return targets else: return targets[index]
579,216
Generator over alternatives, either all or only of a specific annotation type, and possibly restrained also by set. Arguments: * ``Class`` - The Class you want to retrieve (e.g. PosAnnotation). Or set to None to select all alternatives regardless of what type they are. * ``set`` - The...
def alternatives(self, Class=None, set=None): for e in self.select(AlternativeLayers,None, True, ['Original','Suggestion']): #pylint: disable=too-many-nested-blocks if Class is None: yield e elif len(e) >= 1: #child elements? for e2 in e: ...
579,223
Save the document to file. Arguments: * filename (str): The filename to save to. If not set (``None``, default), saves to the same file as loaded from.
def save(self, filename=None): if not filename: filename = self.filename if not filename: raise Exception("No filename specified") if filename[-4:].lower() == '.bz2': f = bz2.BZ2File(filename,'wb') f.write(self.xmlstring().encode('utf-8'))...
579,299
Perform any pending validations Parameters: warnonly (bool): Warn only (True) or raise exceptions (False). If set to None then this value will be determined based on the document's FoLiA version (Warn only before FoLiA v1.5) Returns: bool
def pendingvalidation(self, warnonly=None): if self.debug: print("[PyNLPl FoLiA DEBUG] Processing pending validations (if any)",file=stderr) if warnonly is None and self and self.version: warnonly = (checkversion(self.version, '1.5.0') < 0) #warn only for documents older than FoLiA...
579,322
Run the Cell code using the IPython globals and locals Args: cell (str): Python code to be executed
def run_cell(self, cell): globals = self.ipy_shell.user_global_ns locals = self.ipy_shell.user_ns globals.update({ "__ipy_scope__": None, }) try: with redirect_stdout(self.stdout): self.run(cell, globals, locals) except: ...
579,597
Return a new dict with specified keys excluded from the origional dict Args: d (dict): origional dict exclude (list): The keys that are excluded
def filter_dict(d, exclude): ret = {} for key, value in d.items(): if key not in exclude: ret.update({key: value}) return ret
579,623
Redirect the stdout Args: new_stdout (io.StringIO): New stdout to use instead
def redirect_stdout(new_stdout): old_stdout, sys.stdout = sys.stdout, new_stdout try: yield None finally: sys.stdout = old_stdout
579,624
Return a string representation of the Python object Args: obj: The Python object options: Format options
def format(obj, options): formatters = { float_types: lambda x: '{:.{}g}'.format(x, options.digits), } for _types, fmtr in formatters.items(): if isinstance(obj, _types): return fmtr(obj) try: if six.PY2 and isinstance(obj, six.string_types): return s...
579,625
Get type information for a Python object Args: obj: The Python object Returns: tuple: (object type "catagory", object type name)
def get_type_info(obj): if isinstance(obj, primitive_types): return ('primitive', type(obj).__name__) if isinstance(obj, sequence_types): return ('sequence', type(obj).__name__) if isinstance(obj, array_types): return ('array', type(obj).__name__) if isinstance(obj, key_valu...
579,626
Wipe the entire context. Args: Context is a dictionary or dictionary-like. Does not require any specific keys in context.
def run_step(context): logger.debug("started") context.clear() logger.info(f"Context wiped. New context size: {len(context)}") logger.debug("done")
579,753
Look for the pipeline in the various places it could be. First checks the cwd. Then checks pypyr/pipelines dir. Args: pipeline_name: string. Name of pipeline to find working_directory: string. Path in which to look for pipeline_name.yaml Returns: Absolute path to the pipeline_name...
def get_pipeline_path(pipeline_name, working_directory): logger.debug("starting") # look for name.yaml in the pipelines/ sub-directory logger.debug(f"current directory is {working_directory}") # looking for {cwd}/pipelines/[pipeline_name].yaml pipeline_path = os.path.abspath(os.path.join( ...
579,759
Initialize the class. No duh, huh?. You can happily expect the initializer to initialize all member attributes. Args: step: a string or a dict. This is the actual step as it exists in the pipeline yaml - which is to say it can just be a string fo...
def __init__(self, step): logger.debug("starting") # defaults for decorators self.description = None self.foreach_items = None self.in_parameters = None self.retry_decorator = None self.run_me = True self.skip_me = False self.swallow_me =...
579,763
Run step once for each item in foreach_items. On each iteration, the invoked step can use context['i'] to get the current iterator value. Args: context: (pypyr.context.Context) The pypyr context. This arg will mutate.
def foreach_loop(self, context): logger.debug("starting") # Loop decorators only evaluated once, not for every step repeat # execution. foreach = context.get_formatted_iterable(self.foreach_items) foreach_length = len(foreach) logger.info(f"foreach decorator w...
579,764
Evaluate the step decorators to decide whether to run step or not. Use pypyr.dsl.Step.run_step if you intend on executing the step the same way pypyr does. Args: context: (pypyr.context.Context) The pypyr context. This arg will mutate.
def run_conditional_decorators(self, context): logger.debug("starting") # The decorator attributes might contain formatting expressions that # change whether they evaluate True or False, thus apply formatting at # last possible instant. run_me = context.get_formatted_as...
579,766
Run the foreach sequence or the conditional evaluation. Args: context: (pypyr.context.Context) The pypyr context. This arg will mutate.
def run_foreach_or_conditional(self, context): logger.debug("starting") # friendly reminder [] list obj (i.e empty) evals False if self.foreach_items: self.foreach_loop(context) else: # since no looping required, don't pollute output with looping info ...
579,767
Run a single pipeline step. Args: context: (pypyr.context.Context) The pypyr context. This arg will mutate.
def run_step(self, context): logger.debug("starting") # the in params should be added to context before step execution. self.set_step_input_context(context) if self.while_decorator: self.while_decorator.while_loop(context, ...
579,768
Initialize the class. No duh, huh. You can happily expect the initializer to initialize all member attributes. Args: retry_definition: dict. This is the actual retry definition as it exists in the pipeline yaml.
def __init__(self, retry_definition): logger.debug("starting") if isinstance(retry_definition, dict): # max: optional. defaults None. self.max = retry_definition.get('max', None) # sleep: optional. defaults 0. self.sleep = retry_definition.get('...
579,770
Run step inside a retry loop. Args: context: (pypyr.context.Context) The pypyr context. This arg will mutate - after method execution will contain the new updated context. step_method: (method/function) This is the method/function that ...
def retry_loop(self, context, step_method): logger.debug("starting") context['retryCounter'] = 0 sleep = context.get_formatted_as_type(self.sleep, out_type=float) if self.max: max = context.get_formatted_as_type(self.max, out_type=int) logger.info(f"re...
579,772
Initialize the class. No duh, huh. You can happily expect the initializer to initialize all member attributes. Args: while_definition: dict. This is the actual while definition as it exists in the pipeline yaml.
def __init__(self, while_definition): logger.debug("starting") if isinstance(while_definition, dict): # errorOnMax: optional. defaults False self.error_on_max = while_definition.get('errorOnMax', False) # max: optional. defaults None. self.max =...
579,773
Run step inside a while loop. Args: context: (pypyr.context.Context) The pypyr context. This arg will mutate - after method execution will contain the new updated context. step_method: (method/function) This is the method/function that ...
def while_loop(self, context, step_method): logger.debug("starting") context['whileCounter'] = 0 if self.stop is None and self.max is None: # the ctor already does this check, but guess theoretically # consumer could have messed with the props since ctor ...
579,775
Run a command. Runs a program or executable. If is_shell is True, executes the command through the shell. Args: is_shell: bool. defaults False. Set to true to execute cmd through the default shell.
def run_step(self, is_shell): assert is_shell is not None, ("is_shell param must exist for CmdStep.") # why? If shell is True, it is recommended to pass args as a string # rather than as a sequence. if is_shell: args = self.cmd_text else: args = ...
579,804
Run the run_step(context) method of each step in steps. Args: steps: list. Sequence of Steps to execute context: pypyr.context.Context. The pypyr context. Will mutate.
def run_pipeline_steps(steps, context): logger.debug("starting") assert isinstance( context, dict), "context must be a dictionary, even if empty {}." if steps is None: logger.debug("No steps found to execute.") else: step_count = 0 for step in steps: st...
579,810
Create all parent directories of path if they don't exist. Args: path. Path-like object. Create parent dirs to this path. Return: None.
def ensure_dir(path): os.makedirs(os.path.abspath(os.path.dirname(path)), exist_ok=True)
579,812
Return True if path1 is the same file as path2. The reason for this dance is that samefile throws if either file doesn't exist. Args: path1: str or path-like. path2: str or path-like. Returns: bool. True if the same file, False if not.
def is_same_file(path1, path2): return ( path1 and path2 and os.path.isfile(path1) and os.path.isfile(path2) and os.path.samefile(path1, path2))
579,814