text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def print_dot(docgraph):
""" converts a document graph into a dot file and returns it as a string. If this function call is prepended by %dotstr, it will display... |
stripped_graph = preprocess_for_pydot(docgraph)
return nx.drawing.nx_pydot.to_pydot(stripped_graph).to_string() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def relabel_nodes(G, mapping, copy=True):
"""Relabel the nodes of the graph G. Parameters G : graph A NetworkX graph mapping : dictionary A dictionary with the o... |
# you can pass a function f(old_label)->new_label
# but we'll just make a dictionary here regardless
if not hasattr(mapping, "__getitem__"):
m = dict((n, mapping(n)) for n in G)
else:
m = mapping
if copy:
return _relabel_copy(G, m)
else:
return _relabel_inplace(G... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_node_labels_to_integers(G, first_label=0, ordering="default", label_attribute=None):
"""Return a copy of the graph G with the nodes relabeled with in... |
N = G.number_of_nodes() + first_label
if ordering == "default":
mapping = dict(zip(G.nodes(), range(first_label, N)))
elif ordering == "sorted":
nlist = G.nodes()
nlist.sort()
mapping = dict(zip(nlist, range(first_label, N)))
elif ordering == "increasing degree":
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write(self, output_filepath):
""" serialize the ExmaraldaFile instance and write it to a file. Parameters output_filepath : str relative or absolute path to ... |
with open(output_filepath, 'w') as out_file:
out_file.write(self.__str__()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __create_document_header(self):
""" Look, mum! XML generation without string concatenation!1!! This creates an empty, but functional header for an Exmaralda ... |
E = self.E
root = E('basic-transcription')
head = E('head')
meta = E('meta-information')
project = E('project-name')
tname = E('transcription-name')
ref_file = E('referenced-file', url="")
ud = E('ud-meta-information')
comment = E('comment')
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __add_document_structure(self, docgraph, remove_redundant_layers=True):
"""return an Exmaralda XML etree representation a docgraph""" |
E = self.E
root = self.__create_document_header()
body = E('basic-body')
timeline = E('common-timeline')
# for n tokens we need to create n+1 timeline indices
for i in xrange(len(docgraph.tokens)+1):
idx = str(i)
# example: <tli id="T0" time="0"... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __add_tokenization(self, tree):
"""adds a node for each token ID in the document""" |
for token_id in self.get_token_ids(tree):
self.add_node(token_id, layers={self.ns})
self.tokens.append(token_id) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_token_annotation_tier(self, tier):
""" returns True, iff all events in the given tier annotate exactly one token. """ |
for i, event in enumerate(tier.iter('event')):
if self.indexdelta(event.attrib['end'], event.attrib['start']) != 1:
return False
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __add_token_annotation_tier(self, tier):
""" adds a tier to the document graph, in which each event annotates exactly one token. """ |
for i, event in enumerate(tier.iter('event')):
anno_key = '{0}:{1}'.format(self.ns, tier.attrib['category'])
anno_val = event.text if event.text else ''
self.node[event.attrib['start']][anno_key] = anno_val |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __add_span_tier(self, tier):
""" adds a tier to the document graph in which each event annotates a span of one or more tokens. """ |
tier_id = tier.attrib['id']
# add the tier's root node with an inbound edge from the document root
self.add_node(
tier_id, layers={self.ns, self.ns+':tier'},
attr_dict={self.ns+':category': tier.attrib['category'],
self.ns+':type': tier.attrib['typ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_token_ids(tree):
""" returns a list of all token IDs occuring the the given exmaralda file, sorted by their time stamp in ascending order. """ |
def tok2time(token_element):
'''
extracts the time (float) of a <tli> element
(i.e. the absolute position of a token in the document)
'''
return float(token_element.attrib['time'])
timeline = tree.find('//common-timeline')
return (tok... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_token_mapping(docgraph_with_old_names, docgraph_with_new_names, verbose=False):
""" given two document graphs which annotate the same text and which u... |
def kwic_string(docgraph, keyword_index):
tokens = [tok for (tokid, tok) in list(docgraph.get_tokens())]
before, keyword, after = get_kwic(tokens, keyword_index)
return "{0} (Index: {1}): {2} [[{3}]] {4}\n".format(
docgraph.name, keyword_index, ' '.join(before), keyword,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_kwic(tokens, index, context_window=5):
""" keyword in context Parameters tokens : list of str a text represented as a list of tokens index : int the inde... |
text_length = len(tokens)
start_before = max(0, index-context_window)
end_before = max(0, index)
before = tokens[start_before:end_before]
start_after = min(text_length, index+1)
end_after = min(text_length, index+context_window+1)
after = tokens[start_after:end_after]
return before, tok... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_span_offsets(docgraph, node_id):
""" returns the character start and end position of the span of text that the given node spans or dominates. Returns ---... |
try:
span = get_span(docgraph, node_id)
# workaround for issue #138
# TODO: when #138 is fixed, just take the first onset / last offset
onsets, offsets = zip(*[docgraph.get_offsets(tok_node)
for tok_node in span])
return (min(onsets), max(offs... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_span(docgraph, node_id, debug=False):
""" returns all the tokens that are dominated or in a span relation with the given node. If debug is set to True, y... |
if debug is True and is_directed_acyclic_graph(docgraph) is False:
warnings.warn(
("Can't reliably extract span '{0}' from cyclical graph'{1}'."
"Maximum recursion depth may be exceeded.").format(node_id,
docgraph))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def istoken(docgraph, node_id, namespace=None):
"""returns true, iff the given node ID belongs to a token node. Parameters node_id : str the node to be checked n... |
if namespace is None:
namespace = docgraph.ns
return namespace+':token' in docgraph.node[node_id] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_continuous(docgraph, dominating_node):
"""return True, if the tokens dominated by the given node are all adjacent""" |
first_onset, last_offset = get_span_offsets(docgraph, dominating_node)
span_range = xrange(first_onset, last_offset+1)
token_offsets = (docgraph.get_offsets(tok)
for tok in get_span(docgraph, dominating_node))
char_positions = set(itertools.chain.from_iterable(xrange(on, off+1)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def select_edges(docgraph, conditions, data):
"""yields all edges that meet the conditions given as eval strings""" |
for (src_id, target_id, edge_attribs) in docgraph.edges(data=True):
# if all conditions are fulfilled
# we need to add edge_attribs to the namespace eval is working in
if all((eval(cond, {'edge_attribs': edge_attribs})
for cond in conditions)):
if data:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_offsets(self, offset_ns=None):
""" adds the onset and offset to each token in the document graph, i.e. the character position where each token starts and... |
if offset_ns is None:
offset_ns = self.ns
onset = 0
offset = 0
for token_id, token_str in self.get_tokens():
offset = onset + len(token_str)
self.node[token_id]['{0}:{1}'.format(offset_ns, 'onset')] = onset
self.node[token_id]['{0}:{1}'.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_node(self, n, layers=None, attr_dict=None, **attr):
"""Add a single node n and update node attributes. Parameters n : node A node can be any hashable Pyt... |
if not layers:
layers = {self.ns}
assert isinstance(layers, set), \
"'layers' parameter must be given as a set of strings."
assert all((isinstance(layer, str) for layer in layers)), \
"All elements of the 'layers' set must be strings."
# add layers to... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_nodes_from(self, nodes, **attr):
"""Add multiple nodes. Parameters nodes : iterable container A container of nodes (list, dict, set, etc.). OR A containe... |
additional_attribs = attr # will be added to each node
for n in nodes:
try: # check, if n is a node_id or a (node_id, attrib dict) tuple
newnode = n not in self.succ # is node in the graph, yet?
except TypeError: # n is a (node_id, attribute dict) tuple
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_layer(self, element, layer):
""" add a layer to an existing node or edge Parameters element : str, int, (str/int, str/int) the ID of a node or edge (sour... |
assert isinstance(layer, str), "Layers must be strings!"
if isinstance(element, tuple): # edge repr. by (source, target)
assert len(element) == 2
assert all(isinstance(node, (str, int)) for node in element)
source_id, target_id = element
# this class is b... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_token(self, token_node_id, token_attrib='token'):
""" given a token node ID, returns the token unicode string. Parameters token_node_id : str the ID of t... |
return self.node[token_node_id][self.ns+':'+token_attrib] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def merge_rootnodes(self, other_docgraph):
""" Copy all the metadata from the root node of the other graph into this one. Then, move all edges belonging to the o... |
# copy metadata from other graph, cf. #136
if 'metadata' in other_docgraph.node[other_docgraph.root]:
other_meta = other_docgraph.node[other_docgraph.root]['metadata']
self.node[self.root]['metadata'].update(other_meta)
assert not other_docgraph.in_edges(other_docgraph.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def paula_etree_to_string(tree, dtd_filename):
"""convert a PAULA etree into an XML string.""" |
return etree.tostring(
tree, pretty_print=True, xml_declaration=True,
encoding="UTF-8", standalone='no',
doctype='<!DOCTYPE paula SYSTEM "{0}">'.format(dtd_filename)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gen_paula_etree(paula_id):
""" creates an element tree representation of an empty PAULA XML file. """ |
E = ElementMaker(nsmap=NSMAP)
tree = E('paula', version='1.1')
tree.append(E('header', paula_id=paula_id))
return E, tree |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_paula(docgraph, output_root_dir, human_readable=False):
""" converts a DiscourseDocumentGraph into a set of PAULA XML files representing the same docum... |
paula_document = PaulaDocument(docgraph, human_readable=human_readable)
error_msg = ("Please specify an output directory.\nPaula documents consist"
" of multiple files, so we can't just pipe them to STDOUT.")
assert isinstance(output_root_dir, str), error_msg
document_dir = os.path.joi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __make_xpointer_compatible(self):
""" ensure that all node and IDs in the document graph are valid xpointer IDs. this will relabel all node IDs in place in t... |
node_id_map = {node: ensure_xpointer_compatibility(node)
for node in self.dg.nodes_iter()}
old_token_ids = self.dg.tokens
# replace document graph with node relabeled version
self.dg = relabel_nodes(self.dg, node_id_map, copy=True)
self.dg.tokens = [node... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_etree(cls, etree_element):
""" creates a ``SaltLabel`` from an etree element representing a label element in a SaltXMI file. A label element in SaltXMI ... |
return cls(name=etree_element.attrib['name'],
value=etree_element.attrib['valueString'],
xsi_type=get_xsi_type(etree_element),
namespace=etree_element.attrib.get('namespace'),
hexvalue=etree_element.attrib['value']) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_brackets(docgraph, output_file, layer='mmax'):
""" converts a document graph into a plain text file with brackets. Parameters layer : str or None The l... |
bracketed_str = gen_bracketed_output(docgraph, layer=layer)
assert isinstance(output_file, (str, file))
if isinstance(output_file, str):
path_to_file = os.path.dirname(output_file)
if not os.path.isdir(path_to_file):
create_dir(path_to_file)
with codecs.open(output_file,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def node2geoff(node_name, properties, encoder):
"""converts a NetworkX node into a Geoff string. Parameters node_name : str or int the ID of a NetworkX node prop... |
if properties:
return '({0} {1})'.format(node_name,
encoder.encode(properties))
else:
return '({0})'.format(node_name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def edge2geoff(from_node, to_node, properties, edge_relationship_name, encoder):
"""converts a NetworkX edge into a Geoff string. Parameters from_node : str or i... |
edge_string = None
if properties:
args = [from_node, edge_relationship_name,
encoder.encode(properties), to_node]
edge_string = '({0})-[:{1} {2}]->({3})'.format(*args)
else:
args = [from_node, edge_relationship_name, to_node]
edge_string = '({0})-[:{1}]->({2}... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_edu_text(text_subtree):
"""return the text of the given EDU subtree""" |
assert text_subtree.label() == SubtreeType.text
return u' '.join(word.decode('utf-8') for word in text_subtree.leaves()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _add_edus_to_tree(parented_tree, edus):
"""replace EDU indices with the text of the EDUs in a parented tree. Parameters parented_tree : nltk.ParentedTree a p... |
for i, child in enumerate(parented_tree):
if isinstance(child, nltk.Tree):
_add_edus_to_tree(child, edus)
else:
edu_index = int(child)
edu_tokens = edus[edu_index]
parented_tree[i] = u" ".join(edu_tokens) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def execute(self, controller_id, command, *args, **kwargs):
""" Execute a single command, and sets sleep times properly. - controller_id = index of controller, z... |
controller_instance = self.controllers[controller_id]
controller_instance.last_command_at = self.last_command_at
ret_val = getattr(controller_instance, command)(*args, **kwargs)
self.last_command_at = controller_instance.last_command_at
return ret_val |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_group_type(self, group, bulb_type):
""" Set bulb type for specified group. Group must be int between 1 and 4. Type must be "rgbw" or "white". Alternative... |
if bulb_type not in ("rgbw", "white"):
raise AttributeError("Bulb type must be either rgbw or white")
self.group[group] = bulb_type
self.has_white = "white" in self.group.values()
self.has_rgbw = "rgbw" in self.group.values() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_brightness_level(cls, percent):
""" Convert percents to bulbs internal range. percent should be integer from 0 to 100. Return value is 2 (minimum brightn... |
# Clamp to appropriate range.
percent = min(100, max(0, percent))
# Map 0-100 to 2-27
value = int(2 + ((float(percent) / 100) * 25))
return percent, value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_brightness(self, percent, group=None):
""" Set brightness. Percent is int between 0 (minimum brightness) and 100 (maximum brightness), or float between 0... |
# If input is float, assume it is percent value from 0 to 1.
if isinstance(percent, float):
if percent > 1:
percent = int(percent)
else:
percent = int(percent * 100)
percent, value = self.get_brightness_level(percent)
self.on(group... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def batch_run(self, *commands):
""" Run batch of commands in sequence. Input is positional arguments with (function pointer, *args) tuples. This method is useful... |
original_retries = self.repeat_commands
self.repeat_commands = 1
for _ in range(original_retries):
for command in commands:
cmd = command[0]
args = command[1:]
cmd(*args)
self.repeat_commands = original_retries |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send(self, msg_dict):
"""Send a message through the websocket client and wait for the answer if the message being sent contains an id attribute.""" |
message = ejson.dumps(msg_dict)
super(DDPSocket, self).send(message)
self._debug_log('<<<{}'.format(message)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _debug_log(self, msg):
"""Debug log messages if debug=True""" |
if not self.debug:
return
sys.stderr.write('{}\n'.format(msg)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _init_socket(self):
"""Initialize the ddp socket""" |
# destroy the connection if it already exists
if self.ddpsocket:
self.ddpsocket.remove_all_listeners('received_message')
self.ddpsocket.remove_all_listeners('closed')
self.ddpsocket.remove_all_listeners('opened')
self.ddpsocket.close_connection()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _recover_network_failure(self):
"""Recover from a network failure""" |
if self.auto_reconnect and not self._is_closing:
connected = False
while not connected:
log_msg = "* ATTEMPTING RECONNECT"
if self._retry_new_version:
log_msg = "* RETRYING DIFFERENT DDP VERSION"
self.ddpsocket._debug_l... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def opened(self):
"""Send the connect message to the server.""" |
# give up if there are no more ddp versions to try
if self._ddp_version_index == len(DDP_VERSIONS):
self.ddpsocket._debug_log('* DDP VERSION MISMATCH')
self.emit('version_mismatch', DDP_VERSIONS)
return
# use server recommended version if we support it
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def closed(self, code, reason=None):
"""Called when the connection is closed""" |
self.emit('socket_closed', code, reason)
self._recover_network_failure() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def call(self, method, params, callback=None):
"""Call a method on the server Arguments: method - the remote server method params - an array of commands to send ... |
cur_id = self._next_id()
if callback:
self._callbacks[cur_id] = callback
self.send({'msg': 'method', 'id': cur_id, 'method': method, 'params': params}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_edus(merge_file_str):
"""Extract EDUs from DPLPs .merge output files. Returns ------- edus : dict from EDU IDs (int) to words (list(str)) """ |
lines = merge_file_str.splitlines()
edus = defaultdict(list)
for line in lines:
if line.strip(): # ignore empty lines
token = line.split('\t')[2]
edu_id = int(line.split('\t')[9])
edus[edu_id].append(token)
return edus |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dplptree2dgparentedtree(self):
"""Convert the tree from DPLP's format into a conventional binary tree, which can be easily converted into output formats like... |
def transform(dplp_tree):
"""Transform a DPLP parse tree into a more conventional parse tree."""
if isinstance(dplp_tree, basestring) or not hasattr(dplp_tree, 'label'):
return dplp_tree
assert len(dplp_tree) == 2, "We can only handle binary trees."
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_terminals_and_nonterminals(sentence_graph):
""" Given a TigerSentenceGraph, returns a sorted list of terminal node IDs, as well as a sorted list of nont... |
terminals = set()
nonterminals = set()
for node_id in sentence_graph.nodes_iter():
if sentence_graph.out_degree(node_id) > 0:
# all nonterminals (incl. root)
nonterminals.add(node_id)
else: # terminals
terminals.add(node_id)
return sorted(list(termin... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_unconnected_nodes(sentence_graph):
""" Takes a TigerSentenceGraph and returns a list of node IDs of unconnected nodes. A node is unconnected, if it doesn... |
return [node for node in sentence_graph.nodes_iter()
if sentence_graph.degree(node) == 0 and
sentence_graph.number_of_nodes() > 1] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_subordinate_clauses(tiger_docgraph):
""" given a document graph of a TIGER syntax tree, return all node IDs of nodes representing subordinate clause cons... |
subord_clause_rels = \
dg.select_edges_by_attribute(
tiger_docgraph, attribute='tiger:label',
value=['MO', 'RC', 'SB'])
subord_clause_nodes = []
for src_id, target_id in subord_clause_rels:
src_cat = tiger_docgraph.node[src_id].get('tiger:cat')
if src_cat ==... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _add_token_to_document(self, token_string, token_attrs=None):
"""add a token node to this document graph""" |
token_feat = {self.ns+':token': token_string}
if token_attrs:
token_attrs.update(token_feat)
else:
token_attrs = token_feat
token_id = 'token_{}'.format(self.token_count)
self.add_node(token_id, layers={self.ns, self.ns+':token'},
at... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _add_dominance_relation(self, source, target):
"""add a dominance relation to this docgraph""" |
# TODO: fix #39, so we don't need to add nodes by hand
self.add_node(target, layers={self.ns, self.ns+':unit'})
self.add_edge(source, target,
layers={self.ns, self.ns+':discourse'},
edge_type=EdgeTypes.dominance_relation) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _add_spanning_relation(self, source, target):
"""add a spanning relation to this docgraph""" |
self.add_edge(source, target, layers={self.ns, self.ns+':unit'},
edge_type=EdgeTypes.spanning_relation) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate(data):
""" Query data and result data must have keys who's values are strings. """ |
if not isinstance(data, dict):
error('Data must be a dictionary.')
for value in data.values():
if not isinstance(value, basestring):
error('Values must be strings.') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def terraform_external_data(function):
""" Query data is received on stdin as a JSON object. Result data must be returned on stdout as a JSON object. The wrapped... |
@wraps(function)
def wrapper(*args, **kwargs):
query = json.loads(sys.stdin.read())
validate(query)
try:
result = function(query, *args, **kwargs)
except Exception as e:
# Terraform wants one-line errors so we catch all exceptions and trim down to just th... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def n_wrap(tree, debug=False, root_id=None):
"""Ensure the given tree has a nucleus as its root. If the root of the tree is a nucleus, return it. If the root of ... |
root_label = tree.label()
expected_n_root = debug_root_label('N', debug=debug, root_id=tree.root_id)
expected_s_root = debug_root_label('S', debug=debug, root_id=tree.root_id)
if root_label == expected_n_root:
return tree
elif root_label == expected_s_root:
tree.set_label(expected... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_relations(dgtree, relations=None):
"""Extracts relations from a DGParentedTree. Given a DGParentedTree, returns a (relation name, relation type) dict... |
if hasattr(dgtree, 'reltypes'):
# dgtree is an RSTTree or a DisTree that contains a DGParentedTree
return dgtree.reltypes
if relations is None:
relations = {}
if is_leaf(dgtree):
return relations
root_label = dgtree.label()
if root_label == '':
assert dgtr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def elem_wrap(self, tree, debug=False, root_id=None):
"""takes a DGParentedTree and puts a nucleus or satellite on top, depending on the nuclearity of the root e... |
if root_id is None:
root_id = tree.root_id
elem = self.elem_dict[root_id]
if elem['nuclearity'] == 'nucleus':
return n_wrap(tree, debug=debug, root_id=root_id)
else:
return s_wrap(tree, debug=debug, root_id=root_id) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def release():
"Cut a new release"
version = run('python setup.py --version').stdout.strip()
assert version, 'No version found in setup.py?'
print('### Releasing new version: {0}'.format(version))
run('git tag {0}'.format(version))
run('git push --tags')
run('python setup.py sdist bdist_wh... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def bgwrite(fileObj, data, closeWhenFinished=False, chainAfter=None, ioPrio=4):
'''
bgwrite - Start a background writing process
@param fileObj <stream> - A stream backed by an fd
@param data <str/bytes/list> - The data to write. If a list is given, each successive element will ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def run(self):
'''
run - Starts the thread. bgwrite and bgwrite_chunk automatically start the thread.
'''
# If we are chaining after another process, wait for it to complete.
# We use a flag here instead of joining the thread for various reasons
chainAfter = self.c... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def print_sorted_counter(counter, tab=1):
"""print all elements of a counter in descending order""" |
for key, count in sorted(counter.items(), key=itemgetter(1), reverse=True):
print "{0}{1} - {2}".format('\t'*tab, key, count) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def print_most_common(counter, number=5, tab=1):
"""print the most common elements of a counter""" |
for key, count in counter.most_common(number):
print "{0}{1} - {2}".format('\t'*tab, key, count) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def info(docgraph):
"""print node and edge statistics of a document graph""" |
print networkx.info(docgraph), '\n'
node_statistics(docgraph)
print
edge_statistics(docgraph) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _sum_cycles_from_tokens(self, tokens: List[str]) -> int: """Sum the total number of cycles over a list of tokens.""" |
return sum((int(self._nonnumber_pattern.sub('', t)) for t in tokens)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def template_cycles(self) -> int: """The number of cycles dedicated to template.""" |
return sum((int(re.sub(r'\D', '', op)) for op in self.template_tokens)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def skip_cycles(self) -> int: """The number of cycles dedicated to skips.""" |
return sum((int(re.sub(r'\D', '', op)) for op in self.skip_tokens)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def umi_cycles(self) -> int: """The number of cycles dedicated to UMI.""" |
return sum((int(re.sub(r'\D', '', op)) for op in self.umi_tokens)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def total_cycles(self) -> int: """The number of total number of cycles in the structure.""" |
return sum((int(re.sub(r'\D', '', op)) for op in self.tokens)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def experimental_design(self) -> Any: """Return a markdown summary of the samples on this sample sheet. This property supports displaying rendered markdown only w... |
if not self.samples:
raise ValueError('No samples in sample sheet')
markdown = tabulate(
[[getattr(s, h, '') for h in DESIGN_HEADER] for s in self.samples],
headers=DESIGN_HEADER,
tablefmt='pipe',
)
return maybe_render_markdown(markdown) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _repr_tty_(self) -> str: """Return a summary of this sample sheet in a TTY compatible codec.""" |
header_description = ['Sample_ID', 'Description']
header_samples = [
'Sample_ID',
'Sample_Name',
'Library_ID',
'index',
'index2',
]
header = SingleTable([], 'Header')
setting = SingleTable([], 'Settings')
sampl... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_prep_value(self, value):
"""Converts timezone instances to strings for db storage.""" |
# pylint: disable=newstyle
value = super(TimeZoneField, self).get_prep_value(value)
if isinstance(value, tzinfo):
return value.zone
return value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_python(self, value):
"""Returns a datetime.tzinfo instance for the value.""" |
# pylint: disable=newstyle
value = super(TimeZoneField, self).to_python(value)
if not value:
return value
try:
return pytz.timezone(str(value))
except pytz.UnknownTimeZoneError:
raise ValidationError(
message=self.error_messa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def formfield(self, **kwargs):
"""Returns a custom form field for the TimeZoneField.""" |
defaults = {'form_class': forms.TimeZoneField}
defaults.update(**kwargs)
return super(TimeZoneField, self).formfield(**defaults) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check(self, **kwargs):
# pragma: no cover """Calls the TimeZoneField's custom checks.""" |
errors = super(TimeZoneField, self).check(**kwargs)
errors.extend(self._check_timezone_max_length_attribute())
errors.extend(self._check_choices_attribute())
return errors |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _check_timezone_max_length_attribute(self):
# pragma: no cover """ Checks that the `max_length` attribute covers all possible pytz timezone lengths. """ |
# Retrieve the maximum possible length for the time zone string
possible_max_length = max(map(len, pytz.all_timezones))
# Make sure that the max_length attribute will handle the longest time
# zone string
if self.max_length < possible_max_length: # pragma: no cover
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _check_choices_attribute(self):
# pragma: no cover """Checks to make sure that choices contains valid timezone choices.""" |
if self.choices:
warning_params = {
'msg': (
"'choices' contains an invalid time zone value '{value}' "
"which was not found as a supported time zone by pytz "
"{version}."
),
'hint': "Value... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_python(self, value):
"""Convert the value to the appropriate timezone.""" |
# pylint: disable=newstyle
value = super(LinkedTZDateTimeField, self).to_python(value)
if not value:
return value
return value.astimezone(self.timezone) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pre_save(self, model_instance, add):
""" Converts the value being saved based on `populate_from` and `time_override` """ |
# pylint: disable=newstyle
# Retrieve the currently entered datetime
value = super(
LinkedTZDateTimeField,
self
).pre_save(
model_instance=model_instance,
add=add
)
# Convert the value to the correct time/timezone
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deconstruct(self):
# pragma: no cover """Add our custom keyword arguments for migrations.""" |
# pylint: disable=newstyle
name, path, args, kwargs = super(
LinkedTZDateTimeField,
self
).deconstruct()
# Only include kwarg if it's not the default
if self.populate_from is not None:
# Since populate_from requires a model instance and Djang... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_populate_from(self, model_instance):
""" Retrieves the timezone or None from the `populate_from` attribute. """ |
if hasattr(self.populate_from, '__call__'):
tz = self.populate_from(model_instance)
else:
from_attr = getattr(model_instance, self.populate_from)
tz = callable(from_attr) and from_attr() or from_attr
try:
tz = pytz.timezone(str(tz))
exce... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_time_override(self):
""" Retrieves the datetime.time or None from the `time_override` attribute. """ |
if callable(self.time_override):
time_override = self.time_override()
else:
time_override = self.time_override
if not isinstance(time_override, datetime_time):
raise ValueError(
'Invalid type. Must be a datetime.time instance.'
)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _convert_value(self, value, model_instance, add):
""" Converts the value to the appropriate timezone and time as declared by the `time_override` and `populat... |
if not value:
return value
# Retrieve the default timezone as the default
tz = get_default_timezone()
# If populate_from exists, override the default timezone
if self.populate_from is not None:
tz = self._get_populate_from(model_instance)
if i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_multinuc(relname, nucleii):
"""Creates a rst.sty Latex string representation of a multi-nuclear RST relation.""" |
nuc_strings = []
for nucleus in nucleii:
nuc_strings.append( MULTINUC_ELEMENT_TEMPLATE.substitute(nucleus=nucleus) )
nucleii_string = "\n\t" + "\n\t".join(nuc_strings)
return MULTINUC_TEMPLATE.substitute(relation=relname, nucleus_segments=nucleii_string) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_multisat(nucsat_tuples):
"""Creates a rst.sty Latex string representation of a multi-satellite RST subtree (i.e. a set of nucleus-satellite relations th... |
nucsat_tuples = [tup for tup in nucsat_tuples] # unpack the iterable, so we can check its length
assert len(nucsat_tuples) > 1, \
"A multisat relation bundle must contain more than one relation"
result = "\dirrel\n\t"
first_relation, remaining_relations = nucsat_tuples[0], nucsat_tuples[1:]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def indent(text, amount, ch=' '):
"""Indents a string by the given amount of characters.""" |
padding = amount * ch
return ''.join(padding+line for line in text.splitlines(True)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def document_ids(self):
"""returns a list of document IDs used in the PCC""" |
matches = [PCC_DOCID_RE.match(os.path.basename(fname))
for fname in pcc.tokenization]
return sorted(match.groups()[0] for match in matches) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_document(self, doc_id):
""" given a document ID, returns a merged document graph containng all available annotation layers. """ |
layer_graphs = []
for layer_name in self.layers:
layer_files, read_function = self.layers[layer_name]
for layer_file in layer_files:
if fnmatch.fnmatch(layer_file, '*{}.*'.format(doc_id)):
layer_graphs.append(read_function(layer_file))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_files_by_layer(self, layer_name, file_pattern='*'):
""" returns a list of all files with the given filename pattern in the given PCC annotation layer """ |
layer_path = os.path.join(self.path, layer_name)
return list(dg.find_files(layer_path, file_pattern)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def maybe_render_markdown(string: str) -> Any: """Render a string as Markdown only if in an IPython interpreter.""" |
if is_ipython_interpreter(): # pragma: no cover
from IPython.display import Markdown # type: ignore # noqa: E501
return Markdown(string)
else:
return string |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generic_converter_cli(docgraph_class, file_descriptor=''):
""" generic command line interface for importers. Will convert the file specified on the command l... |
parser = argparse.ArgumentParser()
parser.add_argument('input_file',
help='{} file to be converted'.format(file_descriptor))
parser.add_argument('output_file', nargs='?', default=sys.stdout)
args = parser.parse_args(sys.argv[1:])
assert os.path.isfile(args.input_file), \
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dump_sensor_memory(self, cb_compress=False, custom_compress=False, custom_compress_file=None, auto_collect_result=False):
"""Customized function for dumping ... |
print("~ dumping contents of memory on {}".format(self.sensor.computer_name))
local_file = remote_file = "{}.memdmp".format(self.sensor.computer_name)
if not self.lr_session:
self.go_live()
try:
if cb_compress and auto_collect_result:
logging.inf... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dump_process_memory(self, pid, working_dir="c:\\windows\\carbonblack\\", path_to_procdump=None):
"""Use sysinternals procdump to dump process memory on a spe... |
self.go_live()
print("~ dumping memory where pid={} for {}".format(pid, self.sensor.computer_name))
# need to make sure procdump.exe is on the sensor
procdump_host_path = None
dir_output = self.lr_session.list_directory(working_dir)
for dir_item in dir_output:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_relationtypes(urml_xml_tree):
""" extracts the allowed RST relation names and relation types from an URML XML file. Parameters urml_xml_tree : lxml.e... |
return {rel.attrib['name']: rel.attrib['type']
for rel in urml_xml_tree.iterfind('//header/reltypes/rel')
if 'type' in rel.attrib} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def filters(self):
"""List of filters available for the dataset.""" |
if self._filters is None:
self._filters, self._attributes = self._fetch_configuration()
return self._filters |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def default_attributes(self):
"""List of default attributes for the dataset.""" |
if self._default_attributes is None:
self._default_attributes = {
name: attr
for name, attr in self.attributes.items()
if attr.default is True
}
return self._default_attributes |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_attributes(self):
"""Lists available attributes in a readable DataFrame format. Returns: pd.DataFrame: Frame listing available attributes. """ |
def _row_gen(attributes):
for attr in attributes.values():
yield (attr.name, attr.display_name, attr.description)
return pd.DataFrame.from_records(
_row_gen(self.attributes),
columns=['name', 'display_name', 'description']) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_filters(self):
"""Lists available filters in a readable DataFrame format. Returns: pd.DataFrame: Frame listing available filters. """ |
def _row_gen(attributes):
for attr in attributes.values():
yield (attr.name, attr.type, attr.description)
return pd.DataFrame.from_records(
_row_gen(self.filters), columns=['name', 'type', 'description']) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def query(self, attributes=None, filters=None, only_unique=True, use_attr_names=False, dtypes = None ):
"""Queries the dataset to retrieve the contained data. Ar... |
# Example query from Ensembl biomart:
#
# <?xml version="1.0" encoding="UTF-8"?>
# <!DOCTYPE Query>
# <Query virtualSchemaName = "default" formatter = "TSV" header = "0"
# uniqueRows = "0" count = "" datasetConfigVersion = "0.6" >
# <Dataset name = "hsapiens... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.