INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Returns a list of Chunk and Chink objects from the given sentence. Chink is a subclass of Chunk used for words that have Word. chunk == None ( e. g. punctuation marks conjunctions ).
def chunked(sentence): """ Returns a list of Chunk and Chink objects from the given sentence. Chink is a subclass of Chunk used for words that have Word.chunk == None (e.g., punctuation marks, conjunctions). """ # For example, to construct a training vector with the head of previous chunks a...
Transforms the output of parse () into a Text object. The token parameter lists the order of tags in each token in the input string.
def tree(string, token=[WORD, POS, CHUNK, PNP, REL, ANCHOR, LEMMA]): """ Transforms the output of parse() into a Text object. The token parameter lists the order of tags in each token in the input string. """ return Text(string, token)
Returns the string with XML - safe special characters.
def xml_encode(string): """ Returns the string with XML-safe special characters. """ string = string.replace("&", "&amp;") string = string.replace("<", "&lt;") string = string.replace(">", "&gt;") string = string.replace("\"","&quot;") string = string.replace(SLASH, "/") return string
Returns the string with special characters decoded.
def xml_decode(string): """ Returns the string with special characters decoded. """ string = string.replace("&amp;", "&") string = string.replace("&lt;", "<") string = string.replace("&gt;", ">") string = string.replace("&quot;","\"") string = string.replace("/", SLASH) return string
Returns the given Sentence object as an XML - string ( plain bytestring UTF - 8 encoded ). The tab delimiter is used as indendation for nested elements. The id can be used as a unique identifier per sentence for chunk id s and anchors. For example: I eat pizza with a fork. = > <sentence token = word part - of - speech ...
def parse_xml(sentence, tab="\t", id=""): """ Returns the given Sentence object as an XML-string (plain bytestring, UTF-8 encoded). The tab delimiter is used as indendation for nested elements. The id can be used as a unique identifier per sentence for chunk id's and anchors. For example: "I...
Returns a slash - formatted string from the given XML representation. The return value is a TokenString ( for MBSP ) or TaggedString ( for Pattern ).
def parse_string(xml): """ Returns a slash-formatted string from the given XML representation. The return value is a TokenString (for MBSP) or TaggedString (for Pattern). """ string = "" # Traverse all the <sentence> elements in the XML. dom = XML(xml) for sentence in dom(XML_SENTENCE): ...
Parses tokens from <word > elements in the given XML <chunk > element. Returns a flat list of tokens in which each token is [ WORD POS CHUNK PNP RELATION ANCHOR LEMMA ]. If a <chunk type = PNP > is encountered traverses all of the chunks in the PNP.
def _parse_tokens(chunk, format=[WORD, POS, CHUNK, PNP, REL, ANCHOR, LEMMA]): """ Parses tokens from <word> elements in the given XML <chunk> element. Returns a flat list of tokens, in which each token is [WORD, POS, CHUNK, PNP, RELATION, ANCHOR, LEMMA]. If a <chunk type="PNP"> is encountered, trave...
Returns a string of the roles and relations parsed from the given <chunk > element. The chunk type ( which is part of the relation string ) can be given as parameter.
def _parse_relation(chunk, type="O"): """ Returns a string of the roles and relations parsed from the given <chunk> element. The chunk type (which is part of the relation string) can be given as parameter. """ r1 = chunk.get(XML_RELATION) r2 = chunk.get(XML_ID, chunk.get(XML_OF)) r1 = [x != ...
Returns a list of token tags parsed from the given <word > element. Tags that are not attributes in a <word > ( e. g. relation ) can be given as parameters.
def _parse_token(word, chunk="O", pnp="O", relation="O", anchor="O", format=[WORD, POS, CHUNK, PNP, REL, ANCHOR, LEMMA]): """ Returns a list of token tags parsed from the given <word> element. Tags that are not attributes in a <word> (e.g., relation) can be given as parameters. """ ...
Returns an NLTK nltk. tree. Tree object from the given Sentence. The NLTK module should be on the search path somewhere.
def nltk_tree(sentence): """ Returns an NLTK nltk.tree.Tree object from the given Sentence. The NLTK module should be on the search path somewhere. """ from nltk import tree def do_pnp(pnp): # Returns the PNPChunk (and the contained Chunk objects) in NLTK bracket format. s = ' '....
Returns a dot - formatted string that can be visualized as a graph in GraphViz.
def graphviz_dot(sentence, font="Arial", colors=BLUE): """ Returns a dot-formatted string that can be visualized as a graph in GraphViz. """ s = 'digraph sentence {\n' s += '\tranksep=0.75;\n' s += '\tnodesep=0.15;\n' s += '\tnode [penwidth=1, fontname="%s", shape=record, margin=0.1, height=0.3...
Returns a string where the tags of tokens in the sentence are organized in outlined columns.
def table(sentence, fill=1, placeholder="-"): """ Returns a string where the tags of tokens in the sentence are organized in outlined columns. """ tags = [WORD, POS, IOB, CHUNK, ROLE, REL, PNP, ANCHOR, LEMMA] tags += [tag for tag in sentence.token if tag not in tags] def format(token, tag): ...
Yields a list of all the token tags as they appeared when the word was parsed. For example: [ was VBD B - VP O VP - 1 A1 be ]
def tags(self): """ Yields a list of all the token tags as they appeared when the word was parsed. For example: ["was", "VBD", "B-VP", "O", "VP-1", "A1", "be"] """ # See also. Sentence.__repr__(). ch, I,O,B = self.chunk, INSIDE+"-", OUTSIDE, BEGIN+"-" tags = [OUTSIDE ...
Returns the next word in the sentence with the given type.
def next(self, type=None): """ Returns the next word in the sentence with the given type. """ i = self.index + 1 s = self.sentence while i < len(s): if type in (s[i].type, None): return s[i] i += 1
Returns the next previous word in the sentence with the given type.
def previous(self, type=None): """ Returns the next previous word in the sentence with the given type. """ i = self.index - 1 s = self.sentence while i > 0: if type in (s[i].type, None): return s[i] i -= 1
Yields the head of the chunk ( usually the last word in the chunk ).
def head(self): """ Yields the head of the chunk (usually, the last word in the chunk). """ if self.type == "NP" and any(w.type.startswith("NNP") for w in self): w = find(lambda w: w.type.startswith("NNP"), reversed(self)) elif self.type == "NP": # "the cat" => "cat" ...
Yields a list of all chunks in the sentence with the same relation id.
def related(self): """ Yields a list of all chunks in the sentence with the same relation id. """ return [ch for ch in self.sentence.chunks if ch != self and intersects(unzip(0, ch.relations), unzip(0, self.relations))]
Yields the anchor tag as parsed from the original token. Chunks that are anchors have a tag with an A prefix ( e. g. A1 ). Chunks that are PNP attachmens ( or chunks inside a PNP ) have P ( e. g. P1 ). Chunks inside a PNP can be both anchor and attachment ( e. g. P1 - A2 ) as in: clawed/ A1 at/ P1 mice/ P1 - A2 in/ P2 ...
def anchor_id(self): """ Yields the anchor tag as parsed from the original token. Chunks that are anchors have a tag with an "A" prefix (e.g., "A1"). Chunks that are PNP attachmens (or chunks inside a PNP) have "P" (e.g., "P1"). Chunks inside a PNP can be both anchor and atta...
For verb phrases ( VP ) yields a list of the nearest adjectives and adverbs.
def modifiers(self): """ For verb phrases (VP), yields a list of the nearest adjectives and adverbs. """ if self._modifiers is None: # Iterate over all the chunks and attach modifiers to their VP-anchor. is_modifier = lambda ch: ch.type in ("ADJP", "ADVP") and ch.relation...
Returns the nearest chunk in the sentence with the given type. This can be used ( for example ) to find adverbs and adjectives related to verbs as in: the cat is ravenous = > is what? = > ravenous.
def nearest(self, type="VP"): """ Returns the nearest chunk in the sentence with the given type. This can be used (for example) to find adverbs and adjectives related to verbs, as in: "the cat is ravenous" => is what? => "ravenous". """ candidate, d = None, len(self.sente...
Returns the next chunk in the sentence with the given type.
def next(self, type=None): """ Returns the next chunk in the sentence with the given type. """ i = self.stop s = self.sentence while i < len(s): if s[i].chunk is not None and type in (s[i].chunk.type, None): return s[i].chunk i += 1
Returns the next previous chunk in the sentence with the given type.
def previous(self, type=None): """ Returns the next previous chunk in the sentence with the given type. """ i = self.start - 1 s = self.sentence while i > 0: if s[i].chunk is not None and type in (s[i].chunk.type, None): return s[i].chunk i...
Appends the next word to the sentence/ chunk/ preposition. For example: Sentence. append ( clawed claw VB VP role = None relation = 1 ) - word: the current word - lemma: the canonical form of the word - type: part - of - speech tag for the word ( NN JJ... ) - chunk: part - of - speech tag for the chunk this word is par...
def append(self, word, lemma=None, type=None, chunk=None, role=None, relation=None, pnp=None, anchor=None, iob=None, custom={}): """ Appends the next word to the sentence / chunk / preposition. For example: Sentence.append("clawed", "claw", "VB", "VP", role=None, relation=1) - word :...
Returns the arguments for Sentence. append () from a tagged token representation. The order in which token tags appear can be specified. The default order is ( separated by slashes ): - word - part - of - speech - ( IOB - ) chunk - ( IOB - ) preposition - chunk ( - relation ) ( - role ) - anchor - lemma. Examples: The/...
def parse_token(self, token, tags=[WORD, POS, CHUNK, PNP, REL, ANCHOR, LEMMA]): """ Returns the arguments for Sentence.append() from a tagged token representation. The order in which token tags appear can be specified. The default order is (separated by slashes): - word, ...
Parses the chunk tag role and relation id from the token relation tag. - VP = > VP [] [] - VP - 1 = > VP [ 1 ] [ None ] - ADJP - PRD = > ADJP [ None ] [ PRD ] - NP - SBJ - 1 = > NP [ 1 ] [ SBJ ] - NP - OBJ - 1 * NP - OBJ - 2 = > NP [ 1 2 ] [ OBJ OBJ ] - NP - SBJ ; NP - OBJ - 1 = > NP [ 1 1 ] [ SBJ OBJ ]
def _parse_relation(self, tag): """ Parses the chunk tag, role and relation id from the token relation tag. - VP => VP, [], [] - VP-1 => VP, [1], [None] - ADJP-PRD => ADJP, [None], [PRD] - NP-SBJ-1 => NP, [1], [SBJ] ...
Adds a new Word to the sentence. Other Sentence. _do_ [ tag ] functions assume a new word has just been appended.
def _do_word(self, word, lemma=None, type=None): """ Adds a new Word to the sentence. Other Sentence._do_[tag] functions assume a new word has just been appended. """ # Improve 3rd person singular "'s" lemma to "be", e.g., as in "he's fine". if lemma == "'s" and type in ("VB"...
Adds a new Chunk to the sentence or adds the last word to the previous chunk. The word is attached to the previous chunk if both type and relation match and if the word s chunk tag does not start with B - ( i. e. iob ! = BEGIN ). Punctuation marks ( or other O chunk tags ) are not chunked.
def _do_chunk(self, type, role=None, relation=None, iob=None): """ Adds a new Chunk to the sentence, or adds the last word to the previous chunk. The word is attached to the previous chunk if both type and relation match, and if the word's chunk tag does not start with "B-" (i.e., iob !=...
Attaches subjects objects and verbs. If the previous chunk is a subject/ object/ verb it is stored in Sentence. relations {}.
def _do_relation(self): """ Attaches subjects, objects and verbs. If the previous chunk is a subject/object/verb, it is stored in Sentence.relations{}. """ if self.chunks: ch = self.chunks[-1] for relation, role in ch.relations: if role == "SBJ...
Attaches prepositional noun phrases. Identifies PNP s from either the PNP tag or the P - attachment tag. This does not determine the PP - anchor it only groups words in a PNP chunk.
def _do_pnp(self, pnp, anchor=None): """ Attaches prepositional noun phrases. Identifies PNP's from either the PNP tag or the P-attachment tag. This does not determine the PP-anchor, it only groups words in a PNP chunk. """ if anchor or pnp and pnp.endswith("PNP"): ...
Collects preposition anchors and attachments in a dictionary. Once the dictionary has an entry for both the anchor and the attachment they are linked.
def _do_anchor(self, anchor): """ Collects preposition anchors and attachments in a dictionary. Once the dictionary has an entry for both the anchor and the attachment, they are linked. """ if anchor: for x in anchor.split("-"): A, P = None, None ...
Attach conjunctions. CC - words like and and or between two chunks indicate a conjunction.
def _do_conjunction(self, _and=("and", "e", "en", "et", "und", "y")): """ Attach conjunctions. CC-words like "and" and "or" between two chunks indicate a conjunction. """ w = self.words if len(w) > 2 and w[-2].type == "CC" and w[-2].chunk is None: cc = w[-2].stri...
Returns a tag for the word at the given index. The tag can be WORD LEMMA POS CHUNK PNP RELATION ROLE ANCHOR or a custom word tag.
def get(self, index, tag=LEMMA): """ Returns a tag for the word at the given index. The tag can be WORD, LEMMA, POS, CHUNK, PNP, RELATION, ROLE, ANCHOR or a custom word tag. """ if tag == WORD: return self.words[index] if tag == LEMMA: return self.word...
Iterates over the tags in the entire Sentence For example Sentence. loop ( POS LEMMA ) yields tuples of the part - of - speech tags and lemmata. Possible tags: WORD LEMMA POS CHUNK PNP RELATION ROLE ANCHOR or a custom word tag. Any order or combination of tags can be supplied.
def loop(self, *tags): """ Iterates over the tags in the entire Sentence, For example, Sentence.loop(POS, LEMMA) yields tuples of the part-of-speech tags and lemmata. Possible tags: WORD, LEMMA, POS, CHUNK, PNP, RELATION, ROLE, ANCHOR or a custom word tag. Any order or combi...
Returns the indices of tokens in the sentence where the given token tag equals the string. The string can contain a wildcard * at the end ( this way NN * will match NN and NNS ). The tag can be WORD LEMMA POS CHUNK PNP RELATION ROLE ANCHOR or a custom word tag. For example: Sentence. indexof ( VP tag = CHUNK ) returns ...
def indexof(self, value, tag=WORD): """ Returns the indices of tokens in the sentence where the given token tag equals the string. The string can contain a wildcard "*" at the end (this way "NN*" will match "NN" and "NNS"). The tag can be WORD, LEMMA, POS, CHUNK, PNP, RELATION, ROLE, ANC...
Returns a portion of the sentence from word start index to word stop index. The returned slice is a subclass of Sentence and a deep copy.
def slice(self, start, stop): """ Returns a portion of the sentence from word start index to word stop index. The returned slice is a subclass of Sentence and a deep copy. """ s = Slice(token=self.token, language=self.language) for i, word in enumerate(self.words[start:stop])...
Returns an in - order list of mixed Chunk and Word objects. With pnp = True also contains PNPChunk objects whenever possible.
def constituents(self, pnp=False): """ Returns an in-order list of mixed Chunk and Word objects. With pnp=True, also contains PNPChunk objects whenever possible. """ a = [] for word in self.words: if pnp and word.pnp is not None: if len(a) == 0 or ...
Returns a new Text from the given XML string.
def from_xml(cls, xml): """ Returns a new Text from the given XML string. """ s = parse_string(xml) return Sentence(s.split("\n")[0], token=s.tags, language=s.language)
Yields the sentence as an XML - formatted string ( plain bytestring UTF - 8 encoded ). All the sentences in the XML are wrapped in a <text > element.
def xml(self): """ Yields the sentence as an XML-formatted string (plain bytestring, UTF-8 encoded). All the sentences in the XML are wrapped in a <text> element. """ xml = [] xml.append('<?xml version="1.0" encoding="%s"?>' % XML_ENCODING.get(self.encoding, self.encoding)) ...
Extract credits from AUTHORS. rst
def get_credits(): """Extract credits from `AUTHORS.rst`""" credits = read(os.path.join(_HERE, "AUTHORS.rst")).split("\n") from_index = credits.index("Active Contributors") credits = "\n".join(credits[from_index + 2:]) return credits
Converts rst to ** markdown_github ** using: program: pandoc
def rst2markdown_github(path_to_rst, path_to_md, pandoc="pandoc"): """ Converts ``rst`` to **markdown_github**, using :program:`pandoc` **Input** * ``FILE.rst`` **Output** * ``FILE.md`` """ _proc = subprocess.Popen([pandoc, "-f", "rst", "-t", "m...
Extract HELP information from <program > - h | -- help message
def console_help2rst(cwd, help_cmd, path_to_rst, rst_title, format_as_code=False): """ Extract HELP information from ``<program> -h | --help`` message **Input** * ``$ <program> -h | --help`` * ``$ cd <cwd> && make help`` **Output** * ``docs/src/console_he...
Update documentation ( ready for publishing new release )
def update_docs(readme=True, makefiles=True): """Update documentation (ready for publishing new release) Usually called by ``make docs`` :param bool make_doc: generate DOC page from Makefile help messages """ if readme: _pandoc = get_external_executable("pandoc") rst2markdown_gith...
Returns root mean square value of f ( x params )
def rms(self, x, params=()): """ Returns root mean square value of f(x, params) """ internal_x, internal_params = self.pre_process(np.asarray(x), np.asarray(params)) if internal_params.ndim > 1: raise NotImplementedError("Paramet...
Solve system for a set of parameters in which one is varied
def solve_series(self, x0, params, varied_data, varied_idx, internal_x0=None, solver=None, propagate=True, **kwargs): """ Solve system for a set of parameters in which one is varied Parameters ---------- x0 : array_like Guess (subject to ``self.post_proc...
Plots the results from: meth: solve_series.
def plot_series(self, xres, varied_data, varied_idx, **kwargs): """ Plots the results from :meth:`solve_series`. Parameters ---------- xres : array Of shape ``(varied_data.size, self.nx)``. varied_data : array See :meth:`solve_series`. varied_idx ...
Analogous to: meth: plot_series but will plot residuals.
def plot_series_residuals(self, xres, varied_data, varied_idx, params, **kwargs): """ Analogous to :meth:`plot_series` but will plot residuals. """ nf = len(self.f_cb(*self.pre_process(xres[0], params))) xerr = np.empty((xres.shape[0], nf)) new_params = np.array(params) for idx,...
Analogous to: meth: plot_series but for internal residuals from last run.
def plot_series_residuals_internal(self, varied_data, varied_idx, **kwargs): """ Analogous to :meth:`plot_series` but for internal residuals from last run. """ nf = len(self.f_cb(*self.pre_process( self.internal_xout[0], self.internal_params_out[0]))) xerr = np.empty((self.internal_x...
Solve and plot for a series of a varied parameter.
def solve_and_plot_series(self, x0, params, varied_data, varied_idx, solver=None, plot_kwargs=None, plot_residuals_kwargs=None, **kwargs): """ Solve and plot for a series of a varied parameter. Convenience method, see :meth:`solve_series`, :meth:`plot_series` & :me...
Used internally for transformation of variables.
def pre_process(self, x0, params=()): """ Used internally for transformation of variables. """ # Should be used by all methods matching "solve_*" if self.x_by_name and isinstance(x0, dict): x0 = [x0[k] for k in self.names] if self.par_by_name and isinstance(params, dict): ...
Used internally for transformation of variables.
def post_process(self, xout, params_out): """ Used internally for transformation of variables. """ # Should be used by all methods matching "solve_*" for post_processor in self.post_processors: xout, params_out = post_processor(xout, params_out) return xout, params_out
Solve with user specified solver choice.
def solve(self, x0, params=(), internal_x0=None, solver=None, attached_solver=None, **kwargs): """ Solve with user specified ``solver`` choice. Parameters ---------- x0: 1D array of floats Guess (subject to ``self.post_processors``) params: 1D array_like of floats ...
Uses scipy. optimize. root
def _solve_scipy(self, intern_x0, tol=1e-8, method=None, **kwargs): """ Uses ``scipy.optimize.root`` See: http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.root.html Parameters ---------- intern_x0: array_like initial guess tol: float ...
Solve the problem ( systems of equations )
def solve(self, x0, params=(), internal_x0=None, solver=None, conditional_maxiter=20, initial_conditions=None, **kwargs): """ Solve the problem (systems of equations) Parameters ---------- x0 : array Guess. params : array See :meth:`NeqSys.s...
Constructs a pyneqsys. symbolic. SymbolicSys instance and returns from its solve method.
def solve(guess_a, guess_b, power, solver='scipy'): """ Constructs a pyneqsys.symbolic.SymbolicSys instance and returns from its ``solve`` method. """ # The problem is 2 dimensional so we need 2 symbols x = sp.symbols('x:2', real=True) # There is a user specified parameter ``p`` in this problem: p =...
Example demonstrating how to solve a system of non - linear equations defined as SymPy expressions.
def main(guess_a=1., guess_b=0., power=3, savetxt='None', verbose=False): """ Example demonstrating how to solve a system of non-linear equations defined as SymPy expressions. The example shows how a non-linear problem can be given a command-line interface which may be preferred by end-users who are no...
Plot the values of the solution vector vs the varied parameter.
def plot_series(xres, varied_data, indices=None, info=None, fail_vline=None, plot_kwargs_cb=None, ls=('-', '--', ':', '-.'), c=('k', 'r', 'g', 'b', 'c', 'm', 'y'), labels=None, ax=None, names=None, latex_names=None): """ Plot the values of the solution...
Places a legend box outside a matplotlib Axes instance.
def mpl_outside_legend(ax, **kwargs): """ Places a legend box outside a matplotlib Axes instance. """ box = ax.get_position() ax.set_position([box.x0, box.y0, box.width * 0.75, box.height]) # Put a legend to the right of the current axis ax.legend(loc='upper left', bbox_to_anchor=(1, 1), **kwargs)
Transform a linear system to reduced row - echelon form
def linear_rref(A, b, Matrix=None, S=None): """ Transform a linear system to reduced row-echelon form Transforms both the matrix and right-hand side of a linear system of equations to reduced row echelon form Parameters ---------- A : Matrix-like Iterable of rows. b : iterable ...
Returns Ax - b
def linear_exprs(A, x, b=None, rref=False, Matrix=None): """ Returns Ax - b Parameters ---------- A : matrix_like of numbers Of shape (len(b), len(x)). x : iterable of symbols b : array_like of numbers (default: None) When ``None``, assume zeros of length ``len(x)``. Matrix ...
Generate a SymbolicSys instance from a callback.
def from_callback(cls, cb, nx=None, nparams=None, **kwargs): """ Generate a SymbolicSys instance from a callback. Parameters ---------- cb : callable Should have the signature ``cb(x, p, backend) -> list of exprs``. nx : int Number of unknowns, when not g...
Return the jacobian of the expressions
def get_jac(self): """ Return the jacobian of the expressions """ if self._jac is True: if self.band is None: f = self.be.Matrix(self.nf, 1, self.exprs) _x = self.be.Matrix(self.nx, 1, self.x) return f.jacobian(_x) else: ...
Generate a TransformedSys instance from a callback
def from_callback(cls, cb, transf_cbs, nx, nparams=0, pre_adj=None, **kwargs): """ Generate a TransformedSys instance from a callback Parameters ---------- cb : callable Should have the signature ``cb(x, p, backend) -> list of exprs``. The c...
Write binary header data to a file handle.
def write(self, handle): '''Write binary header data to a file handle. This method writes exactly 512 bytes to the beginning of the given file handle. Parameters ---------- handle : file handle The given handle will be reset to 0 using `seek` and then 512 by...
Read and parse binary header data from a file handle.
def read(self, handle): '''Read and parse binary header data from a file handle. This method reads exactly 512 bytes from the beginning of the given file handle. Parameters ---------- handle : file handle The given handle will be reset to 0 using `seek` and ...
Return the number of bytes needed to store this parameter.
def binary_size(self): '''Return the number of bytes needed to store this parameter.''' return ( 1 + # group_id 2 + # next offset marker 1 + len(self.name.encode('utf-8')) + # size of name and name bytes 1 + # data size 1 + len(self.dimensions)...
Write binary data for this parameter to a file handle.
def write(self, group_id, handle): '''Write binary data for this parameter to a file handle. Parameters ---------- group_id : int The numerical ID of the group that holds this parameter. handle : file handle An open, writable, binary file handle. ...
Read binary data for this parameter from a file handle.
def read(self, handle): '''Read binary data for this parameter from a file handle. This reads exactly enough data from the current position in the file to initialize the parameter. ''' self.bytes_per_element, = struct.unpack('b', handle.read(1)) dims, = struct.unpack('B'...
Unpack the raw bytes of this param using the given data format.
def _as_array(self, fmt): '''Unpack the raw bytes of this param using the given data format.''' assert self.dimensions, \ '{}: cannot get value as {} array!'.format(self.name, fmt) elems = array.array(fmt) elems.fromstring(self.bytes) return np.array(elems).reshape(se...
Get the param as an array of raw byte strings.
def bytes_array(self): '''Get the param as an array of raw byte strings.''' assert len(self.dimensions) == 2, \ '{}: cannot get value as bytes array!'.format(self.name) l, n = self.dimensions return [self.bytes[i*l:(i+1)*l] for i in range(n)]
Get the param as a array of unicode strings.
def string_array(self): '''Get the param as a array of unicode strings.''' assert len(self.dimensions) == 2, \ '{}: cannot get value as string array!'.format(self.name) l, n = self.dimensions return [self.bytes[i*l:(i+1)*l].decode('utf-8') for i in range(n)]
Add a parameter to this group.
def add_param(self, name, **kwargs): '''Add a parameter to this group. Parameters ---------- name : str Name of the parameter to add to this group. The name will automatically be case-normalized. Additional keyword arguments will be passed to the `Param`...
Return the number of bytes to store this group and its parameters.
def binary_size(self): '''Return the number of bytes to store this group and its parameters.''' return ( 1 + # group_id 1 + len(self.name.encode('utf-8')) + # size of name and name bytes 2 + # next offset marker 1 + len(self.desc.encode('utf-8')) + # size ...
Write this parameter group with parameters to a file handle.
def write(self, group_id, handle): '''Write this parameter group, with parameters, to a file handle. Parameters ---------- group_id : int The numerical ID of the group. handle : file handle An open, writable, binary file handle. ''' name =...
Ensure that the metadata in our file is self - consistent.
def check_metadata(self): '''Ensure that the metadata in our file is self-consistent.''' assert self.header.point_count == self.point_used, ( 'inconsistent point count! {} header != {} POINT:USED'.format( self.header.point_count, self.point_used, )...
Add a new parameter group.
def add_group(self, group_id, name, desc): '''Add a new parameter group. Parameters ---------- group_id : int The numeric ID for a group to check or create. name : str, optional If a group is created, assign this name to the group. desc : str, opt...
Get a group or parameter.
def get(self, group, default=None): '''Get a group or parameter. Parameters ---------- group : str If this string contains a period (.), then the part before the period will be used to retrieve a group, and the part after the period will be used to re...
Compute the size ( in 512B blocks ) of the parameter section.
def parameter_blocks(self): '''Compute the size (in 512B blocks) of the parameter section.''' bytes = 4. + sum(g.binary_size() for g in self.groups.values()) return int(np.ceil(bytes / 512))
Iterate over the data frames from our C3D file handle.
def read_frames(self, copy=True): '''Iterate over the data frames from our C3D file handle. Parameters ---------- copy : bool If False, the reader returns a reference to the same data buffers for every frame. The default is True, which causes the reader to ...
Pad the file with 0s to the end of the next block boundary.
def _pad_block(self, handle): '''Pad the file with 0s to the end of the next block boundary.''' extra = handle.tell() % 512 if extra: handle.write(b'\x00' * (512 - extra))
Write metadata to a file handle.
def _write_metadata(self, handle): '''Write metadata to a file handle. Parameters ---------- handle : file Write metadata and C3D motion frames to the given file handle. The writer does not close the handle. ''' self.check_metadata() # he...
Write our frame data to the given file handle.
def _write_frames(self, handle): '''Write our frame data to the given file handle. Parameters ---------- handle : file Write metadata and C3D motion frames to the given file handle. The writer does not close the handle. ''' assert handle.tell() ==...
Write metadata and point + analog frames to a file handle.
def write(self, handle): '''Write metadata and point + analog frames to a file handle. Parameters ---------- handle : file Write metadata and C3D motion frames to the given file handle. The writer does not close the handle. ''' if not self._frames...
Given a time range aggregates bytes per prefix.
def aggregate_per_prefix(self, start_time, end_time, limit=0, net_masks='', exclude_net_masks=False, filter_proto=None): """ Given a time range aggregates bytes per prefix. Args: start_time: A string representing the starting time of the time range end_time: A string...
Given a time range aggregates bytes per ASNs.
def aggregate_per_as(self, start_time, end_time): """ Given a time range aggregates bytes per ASNs. Args: start_time: A string representing the starting time of the time range end_time: A string representing the ending time of the time range Returns: ...
Replace vector images with fake ones.
def _workaround_no_vector_images(project): """Replace vector images with fake ones.""" RED = (255, 0, 0) PLACEHOLDER = kurt.Image.new((32, 32), RED) for scriptable in [project.stage] + project.sprites: for costume in scriptable.costumes: if costume.image.format == "SVG": ...
Make Stage - specific variables global ( move them to Project ).
def _workaround_no_stage_specific_variables(project): """Make Stage-specific variables global (move them to Project).""" for (name, var) in project.stage.variables.items(): yield "variable %s" % name for (name, _list) in project.stage.lists.items(): yield "list %s" % name project.variabl...
Register a new: class: KurtPlugin.
def register(cls, plugin): """Register a new :class:`KurtPlugin`. Once registered, the plugin can be used by :class:`Project`, when: * :attr:`Project.load` sees a file with the right extension * :attr:`Project.convert` is called with the format as a parameter """ cls....
Returns the first format plugin whose attributes match kwargs.
def get_plugin(cls, name=None, **kwargs): """Returns the first format plugin whose attributes match kwargs. For example:: get_plugin(extension="scratch14") Will return the :class:`KurtPlugin` whose :attr:`extension <KurtPlugin.extension>` attribute is ``"scratch14"``. ...
Return the block with the given: attr: command.
def block_by_command(cls, command): """Return the block with the given :attr:`command`. Returns None if the block is not found. """ for block in cls.blocks: if block.has_command(command): return block
Return a list of blocks matching the given: attr: text.
def blocks_by_text(cls, text): """Return a list of blocks matching the given :attr:`text`. Capitalisation and spaces are ignored. """ text = kurt.BlockType._strip_text(text) matches = [] for block in cls.blocks: for pbt in block.conversions: ...
Clean up the given list of scripts in - place so none of the scripts overlap.
def clean_up(scripts): """Clean up the given list of scripts in-place so none of the scripts overlap. """ scripts_with_pos = [s for s in scripts if s.pos] scripts_with_pos.sort(key=lambda s: (s.pos[1], s.pos[0])) scripts = scripts_with_pos + [s for s in scripts if not s.pos] y = 20 for...
Return a list of classes in a module that have a classID attribute.
def obj_classes_from_module(module): """Return a list of classes in a module that have a 'classID' attribute.""" for name in dir(module): if not name.startswith('_'): cls = getattr(module, name) if getattr(cls, 'classID', None): yield (name, cls)
Return root object from ref - containing obj table entries
def decode_network(objects): """Return root object from ref-containing obj table entries""" def resolve_ref(obj, objects=objects): if isinstance(obj, Ref): # first entry is 1 return objects[obj.index - 1] else: return obj # Reading the ObjTable backwards ...
Yield ref - containing obj table entries from object network
def encode_network(root): """Yield ref-containing obj table entries from object network""" orig_objects = [] objects = [] def get_ref(value, objects=objects): """Returns the index of the given object in the object table, adding it if needed. """ value = PythonicAdapter(...
Yield ref - containing obj table entries from object network
def encode_network(root): """Yield ref-containing obj table entries from object network""" def fix_values(obj): if isinstance(obj, Container): obj.update((k, get_ref(v)) for (k, v) in obj.items() if k != 'class_name') fixed_obj = obj ...
Return root of obj table. Converts user - class objects
def decode_obj_table(table_entries, plugin): """Return root of obj table. Converts user-class objects""" entries = [] for entry in table_entries: if isinstance(entry, Container): assert not hasattr(entry, '__recursion_lock__') user_obj_def = plugin.user_objects[entry.classID]...
Return list of obj table entries. Converts user - class objects
def encode_obj_table(root, plugin): """Return list of obj table entries. Converts user-class objects""" entries = encode_network(root) table_entries = [] for entry in entries: if isinstance(entry, Container): assert not hasattr(entry, '__recursion_lock__') user_obj_def =...
Encodes a class to a lower - level object using the class own to_construct function. If no such function is defined returns the object unchanged.
def _encode(self, obj, context): """Encodes a class to a lower-level object using the class' own to_construct function. If no such function is defined, returns the object unchanged. """ func = getattr(obj, 'to_construct', None) if callable(func): return func(c...
Initialises a new Python class from a construct using the mapping passed to the adapter.
def _decode(self, obj, context): """Initialises a new Python class from a construct using the mapping passed to the adapter. """ cls = self._get_class(obj.classID) return cls.from_construct(obj, context)
Write file contents string into archive.
def write_file(self, name, contents): """Write file contents string into archive.""" # TODO: find a way to make ZipFile accept a file object. zi = zipfile.ZipInfo(name) zi.date_time = time.localtime(time.time())[:6] zi.compress_type = zipfile.ZIP_DEFLATED zi.external_attr...