output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Classifies the given token in context of the given previous and next tags. | How would you explain what the following Python 3 function does
def classify(self, token, previous=None, next=None, **kwargs):
return self._classifier.classify(self._v(token, previous, next), **kwargs) | As a Python code composer, you craft elegant and concise scripts. |
def apply(self, token, previous=(None, None), next=(None, None)):
""" Returns a (token, tag)-tuple for the given token,
in context of the given previous and next (token, tag)-tuples.
"""
return [token[0], self._classifier.classify(self._v(token[0], previous, next))] | Can you write a function in Python 3 where it
returns a tuple of the given token and tag in context of the given previous and next. | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns a training vector for the given word tag - tuple and its context. | Can you tell what is the following Python 3 function doing
def _v(self, token, previous=None, next=None):
def f(v, s1, s2):
if s2:
v[s1 + " " + s2] = 1
p, n = previous, next
p = ("", "") if not p else (p[0] or "", p[1] or "")
n = ("", "") if not n else (n[0] ... | As a Python code composer, you craft elegant and concise scripts. |
def apply(self, token, previous=(None, None), next=(None, None)):
""" Applies lexical rules to the given token, which is a [word, tag] list.
"""
w = token[0]
for r in self:
if r[1] in self._cmd: # Rule = ly hassuf 2 RB x
f, x, pos, cmd = bool(0), r[0], r[-2], ... | Create a Python 3 function for
applying lexical rules to the given token. | You are a Python code analyst, evaluating scripts for potential improvements. |
def insert(self, i, tag, affix, cmd="hassuf", tagged=None):
""" Inserts a new rule that assigns the given tag to words with the given affix,
e.g., Morphology.append("RB", "-ly").
"""
if affix.startswith("-") and affix.endswith("-"):
affix, cmd = affix[+1:-1], "char"
... | Create a Python 3 function to
insert a new rule that assigns the given tag to words with the given affix. | You are a Python code analyst, evaluating scripts for potential improvements. |
def apply(self, tokens):
""" Applies contextual rules to the given list of tokens,
where each token is a [word, tag] list.
"""
o = [("STAART", "STAART")] * 3 # Empty delimiters for look ahead/back.
t = o + tokens + o
for i, token in enumerate(t):
for r in ... | How would you code a function in Python 3 to
apply contextual rules to the given list of tokens. | You are a Python code generator, capable of creating scripts from specifications. |
Inserts a new rule that updates words with tag1 to tag2 given constraints x and y. | Given the following Python 3 function, write the documentation
def insert(self, i, tag1, tag2, cmd="prevtag", x=None, y=None):
if " < " in tag1 and not x and not y:
tag1, x = tag1.split(" < "); cmd="prevtag"
if " > " in tag1 and not x and not y:
x, tag1 = tag1.split(" > "); cmd="... | As a python code expert, you are capable of creating scripts from specifications. |
def apply(self, tokens):
""" Applies the named entity recognizer to the given list of tokens,
where each token is a [word, tag] list.
"""
# Note: we could also scan for patterns, e.g.,
# "my|his|her name is|was *" => NNP-PERS.
i = 0
while i < len(tokens):
... | Can you create a Python 3 function that
applies the named entity recognizer to the given list of tokens. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def append(self, entity, name="pers"):
""" Appends a named entity to the lexicon,
e.g., Entities.append("Hooloovoo", "PERS")
"""
e = map(lambda s: s.lower(), entity.split(" ") + [name])
self.setdefault(e[0], []).append(e) | Write a Python 3 function that can
append a named entity to the lexicon. | You are a Python code analyst, evaluating scripts for potential improvements. |
def find_keywords(self, string, **kwargs):
""" Returns a sorted list of keywords in the given string.
"""
return find_keywords(string,
parser = self,
top = kwargs.pop("top", 10),
frequency = kwargs.pop("frequency", {}), **kwargs
... | Write a Python 3 script to
return a sorted list of keywords in the given string. | As a python code expert, you are capable of creating scripts from specifications. |
Returns a list of sentences from the given string. | Can you generate the documentation for the following Python 3 function
def find_tokens(self, string, **kwargs):
# "The cat purs." => ["The cat purs ."]
return find_tokens(string,
punctuation = kwargs.get( "punctuation", PUNCTUATION),
abbreviations = kwargs.get("abbreviatio... | As a Python code analyst, you investigate and solve complex coding mysteries |
def find_tags(self, tokens, **kwargs):
""" Annotates the given list of tokens with part-of-speech tags.
Returns a list of tokens, where each token is now a [word, tag]-list.
"""
# ["The", "cat", "purs"] => [["The", "DT"], ["cat", "NN"], ["purs", "VB"]]
return find_tags(tokens... | How would you code a function in Python 3 to
annotate the given list of tokens with part - of - speech tags. | As a Python code composer, you craft elegant and concise scripts. |
def find_chunks(self, tokens, **kwargs):
""" Annotates the given list of tokens with chunk tags.
Several tags can be added, for example chunk + preposition tags.
"""
# [["The", "DT"], ["cat", "NN"], ["purs", "VB"]] =>
# [["The", "DT", "B-NP"], ["cat", "NN", "I-NP"], ["purs", ... | Create a Python 3 function for
annotating the given list of tokens with chunk tags. Several tags can be added for example chunk + preposition tags. | You are a Python code architect, reviewing and designing scalable and efficient code |
Takes a string and returns a tagged Unicode string. | How would you explain what the following Python 3 function does
def parse(self, s, tokenize=True, tags=True, chunks=True, relations=False, lemmata=False, encoding="utf-8", **kwargs):
# Tokenizer.
if tokenize is True:
s = self.find_tokens(s, **kwargs)
if isinstance(s, (list, tuple)):
... | As a Python code composer, you craft elegant and concise scripts. |
Returns a list of sentences where each sentence is a list of tokens where each token is a list of word + tags. | Make a summary of the following Python 3 code
def split(self, sep=TOKENS):
if sep != TOKENS:
return unicode.split(self, sep)
if len(self) == 0:
return []
return [[[x.replace("&slash;", "/") for x in token.split("/")]
for token in sentence.split(" ")]
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Yields a list of tenses for this language excluding negations. | Make a summary of the following Python 3 code
def TENSES(self):
a = set(TENSES[id] for id in self._format)
a = a.union(set(TENSES[id] for id in self._default.keys()))
a = a.union(set(TENSES[id] for id in self._default.values()))
a = sorted(x[:-2] for x in a if x[-2] is False) # Exclude n... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def lemma(self, verb, parse=True):
""" Returns the infinitive form of the given verb, or None.
"""
if dict.__len__(self) == 0:
self.load()
if verb.lower() in self._inverse:
return self._inverse[verb.lower()]
if verb in self._inverse:
return sel... | Write a Python 3 function that can
return the infinitive form of the given verb or None if no such verb exists. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns a list of all possible inflections of the given verb. | Can you generate a brief explanation for the following Python 3 code
def lexeme(self, verb, parse=True):
a = []
b = self.lemma(verb, parse=parse)
if b in self:
a = [x for x in self[b] if x != ""]
elif parse is True: # rule-based
a = self.find_lexeme(b)
u =... | You are a Python code architect, reviewing and designing scalable and efficient code |
def conjugate(self, verb, *args, **kwargs):
""" Inflects the verb and returns the given tense (or None).
For example: be
- Verbs.conjugate("is", INFINITVE) => be
- Verbs.conjugate("be", PRESENT, 1, SINGULAR) => I am
- Verbs.conjugate("be", PRESENT, 1, PLURAL) => w... | Write a Python 3 script to
inflect the verb and returns the given tense. | You are a Python code architect, reviewing and designing scalable and efficient code |
def tenses(self, verb, parse=True):
""" Returns a list of possible tenses for the given inflected verb.
"""
verb = verb.lower()
a = set()
b = self.lemma(verb, parse=parse)
v = []
if b in self:
v = self[b]
elif parse is True: # rule-based
... | Implement a function in Python 3 to
return a list of possible tenses for the given verb. | As a python code expert, you are capable of creating scripts from specifications. |
Loads the Sentiment. xml file with sentiment annotations. | How would you explain what the following Python 3 function does
def load(self, path=None):
# <word form="great" wordnet_id="a-01123879" pos="JJ" polarity="1.0" subjectivity="1.0" intensity="1.0" />
# <word form="damnmit" polarity="-0.75" subjectivity="1.0" label="profanity" />
if not path:
... | As a Python code composer, you craft elegant and concise scripts. |
def synset(self, id, pos=ADJECTIVE):
""" Returns a (polarity, subjectivity)-tuple for the given synset id.
For example, the adjective "horrible" has id 193480 in WordNet:
Sentiment.synset(193480, pos="JJ") => (-0.6, 1.0, 1.0).
"""
id = str(id).zfill(8)
if not id.s... | How would you code a function in Python 3 to
return a tuple of polarity subjectivity - tuple for the given synset id. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns a list of tuples for the given list of words. | Can you tell what is the following Python 3 function doing
def assessments(self, words=[], negation=True):
a = []
m = None # Preceding modifier (i.e., adverb or adjective).
n = None # Preceding negation (e.g., "not beautiful").
for w, pos in words:
# Only assess known words, ... | As a python code expert, you are capable of creating scripts from specifications. |
Annotates the given word with polarity subjectivity and intensity scores. | Can you tell what is the following Python 3 function doing
def annotate(self, word, pos=None, polarity=0.0, subjectivity=0.0, intensity=1.0, label=None):
w = self.setdefault(word, {})
w[pos] = w[None] = (polarity, subjectivity, intensity)
if label:
self.labeler[word] = label | As a Python code composer, you craft elegant and concise scripts. |
Counts the words in the given string and saves the probabilities at the given path. | Can you tell what is the following Python 3 function doing
def train(self, s, path="spelling.txt"):
model = {}
for w in re.findall("[a-z]+", s.lower()):
model[w] = w in model and model[w] + 1 or 1
model = ("%s %s" % (k, v) for k, v in sorted(model.items()))
model = "\n".join(... | You are a Python code generator, capable of creating scripts from specifications. |
def _edit1(self, w):
""" Returns a set of words with edit distance 1 from the given word.
"""
# Of all spelling errors, 80% is covered by edit distance 1.
# Edit distance 1 = one character deleted, swapped, replaced or inserted.
split = [(w[:i], w[i:]) for i in range(len(w) + 1)]... | Write a Python 3 script to
return a set of words with edit distance 1 from the given word. | As a Python code analyst, you investigate and solve complex coding mysteries |
def _edit2(self, w):
""" Returns a set of words with edit distance 2 from the given word
"""
# Of all spelling errors, 99% is covered by edit distance 2.
# Only keep candidates that are actually known words (20% speedup).
return set(e2 for e1 in self._edit1(w) for e2 in self._edi... | Write a Python 3 function that can
return a set of words with edit distance 2 from the given word. | You are a Python code architect, reviewing and designing scalable and efficient code |
Return a list of ( word confidence ) spelling corrections for the given word. | Can you generate the documentation for the following Python 3 function
def suggest(self, w):
if len(self) == 0:
self.load()
if len(w) == 1:
return [(w, 1.0)] # I
if w in PUNCTUATION:
return [(w, 1.0)] # .?!
if w.replace(".", "").isdigit():
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def zip(*args, **kwargs):
""" Returns a list of tuples, where the i-th tuple contains the i-th element
from each of the argument sequences or iterables (or default if too short).
"""
args = [list(iterable) for iterable in args]
n = max(map(len, args))
v = kwargs.get("default", None)
ret... | Can you implement a function in Python 3 that
returns a list of tuples where the i - th tuple contains the i - th element from each of the argument sequences or iterables. | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns a list of Chunk and Chink objects from the given sentence. | Explain what the following Python 3 code does
def chunked(sentence):
# For example, to construct a training vector with the head of previous chunks as a feature.
# Doing this with Sentence.chunks would discard the punctuation marks and conjunctions
# (Sentence.chunks only yields Chunk objects), which amy be... | You are a Python code architect, reviewing and designing scalable and efficient code |
Transforms the output of parse into a Text object. | Given the following Python 3 function, write the documentation
def tree(string, token=[WORD, POS, CHUNK, PNP, REL, ANCHOR, LEMMA]):
return Text(string, token) | You are a Python code analyst, evaluating scripts for potential improvements. |
def xml_encode(string):
""" Returns the string with XML-safe special characters.
"""
string = string.replace("&", "&")
string = string.replace("<", "<")
string = string.replace(">", ">")
string = string.replace("\"",""")
string = string.replace(SLASH, "/")
return string | How would you code a function in Python 3 to
return the string with XML - safe special characters. | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns the string with special characters decoded. | How would you explain what the following Python 3 function does
def xml_decode(string):
string = string.replace("&", "&")
string = string.replace("<", "<")
string = string.replace(">", ">")
string = string.replace(""","\"")
string = string.replace("/", SLASH)
return string | You are a Python code architect, reviewing and designing scalable and efficient code |
Parses the given sentence as an XML - string. | Can you tell what is the following Python 3 function doing
def parse_xml(sentence, tab="\t", id=""):
uid = lambda *parts: "".join([str(id), _UID_SEPARATOR ]+[str(x) for x in parts]).lstrip(_UID_SEPARATOR)
push = lambda indent: indent+tab # push() increases the indentation.
pop = lambda indent: ind... | You are a Python code generator, capable of creating scripts from specifications. |
Parses the given XML representation into a TokenString or TaggedString. | How would you explain what the following Python 3 function does
def parse_string(xml):
string = ""
# Traverse all the <sentence> elements in the XML.
dom = XML(xml)
for sentence in dom(XML_SENTENCE):
_anchors.clear() # Populated by calling _parse_tokens().
_attachments.clear() # Popu... | You are a Python code generator, capable of creating scripts from specifications. |
Parses a list of tokens from the given XML chunk element. | Make a summary of the following Python 3 code
def _parse_tokens(chunk, format=[WORD, POS, CHUNK, PNP, REL, ANCHOR, LEMMA]):
tokens = []
# Only process <chunk> and <chink> elements,
# text nodes in between return an empty list.
if not (chunk.tag == XML_CHUNK or chunk.tag == XML_CHINK):
return []... | As a Python code analyst, you investigate and solve complex coding mysteries |
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 != ... | Can you implement a function in Python 3 that
parses the relation string from the given chunk element. | As a python code expert, you are capable of creating scripts from specifications. |
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.
"""
... | How would you implement a function in Python 3 that
parses a word element into a list of token tags. | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns an NLTK nltk. tree. Tree object from the given Sentence. | Can you tell what is the following Python 3 function doing
def nltk_tree(sentence):
from nltk import tree
def do_pnp(pnp):
# Returns the PNPChunk (and the contained Chunk objects) in NLTK bracket format.
s = ' '.join([do_chunk(ch) for ch in pnp.chunks])
return '(PNP %s)' % s
def... | You are a Python code generator, capable of creating scripts from specifications. |
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... | Write a Python 3 function for
returning a DOT - formatted string that can be visualized as a graph in GraphViz. | As a Python code composer, you craft elegant and concise scripts. |
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):
... | Write a Python 3 script to
return a string where the tags of tokens in the sentence are organized in outlined columns. | You are a Python code generator, capable of creating scripts from specifications. |
Yields a list of all the token tags as they appeared when the word was parsed. | How would you explain what the following Python 3 function does
def tags(self):
# See also. Sentence.__repr__().
ch, I,O,B = self.chunk, INSIDE+"-", OUTSIDE, BEGIN+"-"
tags = [OUTSIDE for i in range(len(self.sentence.token))]
for i, tag in enumerate(self.sentence.token): # Default: [WORD... | As a Python code translator, you convert algorithms and pseudocode into Python. |
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 | Write a Python 3 script for
returning the next word in the sentence with the given type. | As a python code expert, you are capable of creating scripts from specifications. |
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 | Can you create a Python 3 function that
returns the previous word in the sentence with the given type. | You are a Python code generator, capable of creating scripts from specifications. |
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"
... | Write a Python 3 script for
yielding the first entry in the list. | As a Python code composer, you craft elegant and concise scripts. |
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))] | Can you implement a function in Python 3 that
yields a list of all chunks in the sentence with the same relation id. | You are a Python code analyst, evaluating scripts for potential improvements. |
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... | Implement a function in Python 3 to
yield the anchor tag as parsed from the original token. | You are a Python code analyst, evaluating scripts for potential improvements. |
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... | Can you implement a function in Python 3 that
returns a list of all the modifiers that are part of the VP. | As a python code expert, you are capable of creating scripts from specifications. |
Returns the nearest chunk in the sentence with the given type. | Given the following Python 3 function, write the documentation
def nearest(self, type="VP"):
candidate, d = None, len(self.sentence.chunks)
if isinstance(self, PNPChunk):
i = self.sentence.chunks.index(self.chunks[0])
else:
i = self.sentence.chunks.index(self)
for... | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns the next chunk in the sentence with the given type. | Given the following Python 3 function, write the documentation
def next(self, type=None):
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 | You are a Python code architect, reviewing and designing scalable and efficient code |
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... | Can you create a Python 3 function that
returns the previous chunk in the sentence with the given type. | As a Python code composer, you craft elegant and concise scripts. |
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 :... | Implement a function in Python 3 to
append a new word to the internal list of words. | You are a Python code architect, reviewing and designing scalable and efficient code |
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,
... | Write a Python 3 function for
parsing a tagged token representation into a list of arguments. | As a python code expert, you are capable of creating scripts from specifications. |
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]
... | Implement a Python 3 function for
parsing the token relation tag and returns the chunk relation role and relation id. | As a Python code composer, you craft elegant and concise scripts. |
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"... | Implement a Python 3 function for
adding a new Word to the sentence. | As a Python code analyst, you investigate and solve complex coding mysteries |
Add a new Chunk to the sentence or adds the last word to the previous chunk. | Can you generate a brief explanation for the following Python 3 code
def _do_chunk(self, type, role=None, relation=None, iob=None):
if (type is None or type == OUTSIDE) and \
(role is None or role == OUTSIDE) and (relation is None or relation == OUTSIDE):
return
if iob != BEGIN \
... | You are a Python code generator, capable of creating scripts from specifications. |
Attaches subjects objects and verbs to the last chunk of the list of related resources. | Explain what the following Python 3 code does
def _do_relation(self):
if self.chunks:
ch = self.chunks[-1]
for relation, role in ch.relations:
if role == "SBJ" or role == "OBJ":
self.relations[role][relation] = ch
if ch.type in ("VP",):
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
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"):
... | Implement a Python 3 function for
attaching 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. | You are a Python code generator, capable of creating scripts from specifications. |
Collects anchors and attachments in a dictionary. | Explain what the following Python 3 code does
def _do_anchor(self, anchor):
if anchor:
for x in anchor.split("-"):
A, P = None, None
if x.startswith("A") and len(self.chunks) > 0: # anchor
A, P = x, x.replace("A","P")
self._anch... | As a python code expert, you are capable of creating scripts from specifications. |
Add a conjunction to the list of possible conjunctions. | How would you explain what the following Python 3 function does
def _do_conjunction(self, _and=("and", "e", "en", "et", "und", "y")):
w = self.words
if len(w) > 2 and w[-2].type == "CC" and w[-2].chunk is None:
cc = w[-2].string.lower() in _and and AND or OR
ch1 = w[-3].chunk
... | As a python code expert, you are capable of creating scripts from specifications. |
Returns a tag for the word at the given index. | How would you explain what the following Python 3 function does
def get(self, index, tag=LEMMA):
if tag == WORD:
return self.words[index]
if tag == LEMMA:
return self.words[index].lemma
if tag == POS:
return self.words[index].type
if tag == CHUNK:
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
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... | Can you implement a function in Python 3 that
yields the words in the Sentence and lemmata. | You are a Python code generator, capable of creating scripts from specifications. |
Returns the indices of the words in the sentence where the given token tag equals the string. | Explain what the following Python 3 code does
def indexof(self, value, tag=WORD):
match = lambda a, b: a.endswith("*") and b.startswith(a[:-1]) or a==b
indices = []
for i in range(len(self.words)):
if match(value, unicode(self.get(i, tag))):
indices.append(i)
... | As a python code expert, you are capable of creating scripts from specifications. |
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])... | How would you code a function in Python 3 to
return a portion of the sentence from word start index to word stop index. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns an in - order list of mixed Chunk and Word objects. With pnp = True also contains PNPChunk objects whenever possible. | Can you generate a brief explanation for the following Python 3 code
def constituents(self, pnp=False):
a = []
for word in self.words:
if pnp and word.pnp is not None:
if len(a) == 0 or a[-1] != word.pnp:
a.append(word.pnp)
elif word.chunk is n... | As a Python code composer, you craft elegant and concise scripts. |
Returns a new Sentence from the given XML string. | Explain what the following Python 3 code does
def from_xml(cls, xml):
s = parse_string(xml)
return Sentence(s.split("\n")[0], token=s.tags, language=s.language) | You are a Python code architect, reviewing and designing scalable and efficient code |
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))
... | Can you write a function in Python 3 where it
yields the sentence as an XML - formatted string. | You are a Python code generator, capable of creating scripts from specifications. |
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 | Create a Python 3 function to
extract credits from AUTHORS. rst | As a Python code translator, you convert algorithms and pseudocode into Python. |
Converts README. rst to markdown_github. | Here you have a function in Python 3, explain what it does
def rst2markdown_github(path_to_rst, path_to_md, pandoc="pandoc"):
_proc = subprocess.Popen([pandoc, "-f", "rst",
"-t", "markdown_github",
#"-o", path_to_md,
path_to_r... | As a Python code translator, you convert algorithms and pseudocode into Python. |
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... | How would you implement a function in Python 3 that
extracts HELP information from ``<program> -h | --help`` message **Input** * ``$ <program> -h | --help`` * ``$ cd <cwd> && make help`` **Output** * ``docs/src/console_help_xy.rst`` | As a Python code translator, you convert algorithms and pseudocode into Python. |
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... | Implement a function in Python 3 to
update the documentation for the current project. | You are a Python code architect, reviewing and designing scalable and efficient code |
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... | Can you create a Python 3 function that
returns root mean square value of f | As a Python code composer, you craft elegant and concise scripts. |
Solve system for a set of parameters in which one is varied. | Can you generate the documentation for the following Python 3 function
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
----------... | You are a Python code generator, capable of creating scripts from specifications. |
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 ... | Implement a function in Python 3 to
plot the results from the solve_series method. | You are a Python code generator, capable of creating scripts from specifications. |
Analogous to plot_series but will plot residuals. | Here you have a function in Python 3, explain what it does
def plot_series_residuals(self, xres, varied_data, varied_idx, params, **kwargs):
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, row in enumera... | You are a Python code generator, capable of creating scripts from specifications. |
Analogous to plot_series but for internal residuals from last run. | How would you explain what the following Python 3 function does
def plot_series_residuals_internal(self, varied_data, varied_idx, **kwargs):
nf = len(self.f_cb(*self.pre_process(
self.internal_xout[0], self.internal_params_out[0])))
xerr = np.empty((self.internal_xout.shape[0], nf))
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Solve and plot for a varied parameter. | Here you have a function in Python 3, explain what it does
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, ... | As a Python code analyst, you investigate and solve complex coding mysteries |
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):
... | How would you code a function in Python 3 to
use internally for transformation of variables. | You are a Python code analyst, evaluating scripts for potential improvements. |
Used internally for transformation of variables. | Can you tell what is the following Python 3 function doing
def post_process(self, xout, params_out):
# 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 | As a python code expert, you are capable of creating scripts from specifications. |
Solve with user specified solver choice. | Explain what the following Python 3 code does
def solve(self, x0, params=(), internal_x0=None, solver=None, attached_solver=None, **kwargs):
if not isinstance(solver, (tuple, list)):
solver = [solver]
if not isinstance(attached_solver, (tuple, list)):
attached_solver = [attached_... | As a Python code composer, you craft elegant and concise scripts. |
Solve the current state of a set of unsatisfied iCal objects using scipy. optimize. root. | Can you generate the documentation for the following Python 3 function
def _solve_scipy(self, intern_x0, tol=1e-8, method=None, **kwargs):
from scipy.optimize import root
if method is None:
if self.nf > self.nx:
method = 'lm'
elif self.nf == self.nx:
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Solve the problem for a set of conditions. | Make a summary of the following Python 3 code
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.
... | As a Python code analyst, you investigate and solve complex coding mysteries |
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 =... | Write a Python 3 function for
solving a system using a user - specified solver. | As a Python code analyst, you investigate and solve complex coding mysteries |
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... | Can you write a function in Python 3 where it
plots the values of the varied parameter vector vs the varied parameter vector. | You are a Python code architect, reviewing and designing scalable and efficient code |
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) | Implement a function in Python 3 to
place a legend box outside a matplotlib Axes instance. | You are a Python code architect, reviewing and designing scalable and efficient code |
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
... | Implement a Python 3 function for
transforming a linear system to reduced row - echelon form. | You are a Python code analyst, evaluating scripts for potential improvements. |
Linear expression of A. | Can you tell what is the following Python 3 function doing
def linear_exprs(A, x, b=None, rref=False, Matrix=None):
if b is None:
b = [0]*len(x)
if rref:
rA, rb = linear_rref(A, b, Matrix)
if Matrix is None:
from sympy import Matrix
return [lhs - rhs for lhs, rhs in z... | You are a Python code analyst, evaluating scripts for potential improvements. |
Generate a new instance of a SymbolicSys instance from a callback function. | Can you tell what is the following Python 3 function doing
def from_callback(cls, cb, nx=None, nparams=None, **kwargs):
if kwargs.get('x_by_name', False):
if 'names' not in kwargs:
raise ValueError("Need ``names`` in kwargs.")
if nx is None:
nx = len(kwarg... | You are a Python code generator, capable of creating scripts from specifications. |
Returns the jacobian of the expressions | Can you generate the documentation for the following Python 3 function
def get_jac(self):
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)
e... | You are a Python code generator, capable of creating scripts from specifications. |
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... | Can you create a Python 3 function that
generates a TransformedSys instance from a callback. | As a Python code translator, you convert algorithms and pseudocode into Python. |
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... | Implement a function in Python 3 to
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 bytes will be written to describe the parameters in this... | As a Python code analyst, you investigate and solve complex coding mysteries |
Read and parse binary header data from a file handle. | Make a summary of the following Python 3 code
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 giv... | You are a Python code generator, capable of creating scripts from specifications. |
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)... | Can you write a function in Python 3 where it
returns the number of bytes needed to store this parameter. | As a Python code analyst, you investigate and solve complex coding mysteries |
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.
... | How would you implement a function in Python 3 that
writes binary data for this parameter to a file handle. | As a python code expert, you are capable of creating scripts from specifications. |
Read binary data for this parameter from a file handle. | Explain what the following Python 3 code does
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', han... | You are a Python code architect, reviewing and designing scalable and efficient code |
Unpack the raw bytes of this param using the given data format. | Make a summary of the following Python 3 code
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.by... | You are a Python code architect, reviewing and designing scalable and efficient code |
Get the param as an array of raw byte strings. | How would you explain what the following Python 3 function does
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... | You are a Python code analyst, evaluating scripts for potential improvements. |
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)] | How would you implement a function in Python 3 that
gets the param as a list of unicode strings. | As a python code expert, you are capable of creating scripts from specifications. |
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`... | Can you implement a function in Python 3 that
adds a parameter to this group. | You are a Python code architect, reviewing and designing scalable and efficient code |
Return the number of bytes to store this group and its parameters. | Here you have a function in Python 3, explain what it does
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 mark... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.