output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Returns the n - grams generated from the sequence.
Can you tell what is the following Python 3 function doing def _ngrams(self, sequence, degree): count = max(0, len(sequence) - degree + 1) # The extra split and join are due to having to handle # whitespace within a CBETA token (eg, [(禾*尤)\n/上/日]). return [self._tokenizer.joiner.join( ...
You are a Python code generator, capable of creating scripts from specifications.
Returns a compiled regular expression matching on any of the n - grams in filter_ngrams.
Can you generate a brief explanation for the following Python 3 code def get_filter_ngrams_pattern(filter_ngrams): return re.compile('|'.join([re.escape(ngram) for ngram in filter_ngrams]))
You are a Python code generator, capable of creating scripts from specifications.
def get_ngrams(self, minimum, maximum, filter_ngrams): """Returns a generator supplying the n-grams (`minimum` <= n <= `maximum`) for this text. Each iteration of the generator supplies a tuple consisting of the size of the n-grams and a `collections.Counter` of the n-grams. ...
Can you implement a function in Python 3 that returns a generator that yields the n - grams of the text that are contained in the generated n - grams.
As a python code expert, you are capable of creating scripts from specifications.
Set a many - to - many field on an object
How would you explain what the following Python 3 function does def set_relation_many_to_many(self, obj, field_name, objs): "Set a many-to-many field on an object" relation = getattr(obj, field_name) if hasattr(relation, 'set'): relation.set(objs) # Django 2.x else: ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Parse the error messages and collect the missing - relationship errors that are not present locally.
Can you generate a brief explanation for the following Python 3 code def detect_missing_relations(self, obj, exc): missing = defaultdict(set) for name, err in exc.error_dict.items(): # check if it was a relationship that doesnt exist locally pattern = r".+ with id (\d+) does not ...
You are a Python code architect, reviewing and designing scalable and efficient code
Detects uniqueness constraint errors and returns the corresponding fields.
Explain what the following Python 3 code does def detect_uniqueness_error(self, exc): pattern = r"(\w+) with this (\w+) already exists" fields = [] if isinstance(exc, IntegrityError): return self._detect_integrity_error(exc) assert isinstance(exc, ValidationError), TypeError...
You are a Python code architect, reviewing and designing scalable and efficient code
def tls_meta_data(self): """Pull out the TLS metadata for each flow in the input_stream""" # For each flow process the contents for flow in self.input_stream: # Just TCP for now if flow['protocol'] != 'TCP': continue # Client to Server ...
Write a Python 3 script for yielding the TLS metadata for each flow in the input_stream.
As a python code expert, you are capable of creating scripts from specifications.
This method creates a dictionary out of a non - builtin object
How would you explain what the following Python 3 function does def make_dict(obj): # Recursion base case if is_builtin(obj) or isinstance(obj, OrderedDict): return obj output_dict = {} for key in dir(obj): if not key.startswith('__') and not callable(getattr(obj, key)): at...
As a python code expert, you are capable of creating scripts from specifications.
def get_value(data, key): """Follow the dot notation to get the proper field, then perform the action Args: data: the data as a dictionary (required to be a dictionary) key: the key (as dot notation) into the data that gives the field (IP.src) Returns: the value of ...
Implement a function in Python 3 to follow the dot notation to get the proper field then perform the action
You are a Python code generator, capable of creating scripts from specifications.
def csv(self, fh): """Writes the report data to `fh` in CSV format and returns it. :param fh: file to write data to :type fh: file object :rtype: file object """ self._stats.to_csv(fh, encoding='utf-8', index=False) return fh
Write a Python 3 script to write the report data to fh in CSV format and returns it.
As a Python code translator, you convert algorithms and pseudocode into Python.
def generate_statistics(self): """Replaces result rows with summary statistics about the results. These statistics give the filename, total matching tokens, percentage of matching tokens and label for each witness in the results. """ matches = self._matches witn...
Write a Python 3 function that can replace result rows with summary statistics about the results.
You are a Python code generator, capable of creating scripts from specifications.
Returns a single string consisting of the parts specified in slices joined together by the tokenizer s joining string.
Can you generate a brief explanation for the following Python 3 code def _generate_text_from_slices(self, full_text, slices): sliced_text = [] for start, end in slices: sliced_text.append(full_text[start:end]) return self._tokenizer.joiner.join(sliced_text)
You are a Python code generator, capable of creating scripts from specifications.
Return a list of slice indices lists derived from match_slices with no overlaps.
How would you explain what the following Python 3 function does def _merge_slices(match_slices): # Sort by earliest range, then by largest range. match_slices.sort(key=lambda x: (x[0], -x[1])) merged_slices = [match_slices.pop(0)] for slice_indices in match_slices: last_end =...
As a Python code composer, you craft elegant and concise scripts.
Return the counts of total tokens and matching tokens in witness.
Can you generate a brief explanation for the following Python 3 code def _process_witness(self, witness, matches): # In order to provide a correct count of matched tokens, # avoiding the twin dangers of counting the same token # multiple times due to being part of multiple n-grams (which ...
As a python code expert, you are capable of creating scripts from specifications.
Returns a list of all witnesses of variant readings in source_tree along with their XML ids.
Can you generate a brief explanation for the following Python 3 code def get_witnesses(self, source_tree): witnesses = [] witness_elements = source_tree.xpath( '/tei:*/tei:teiHeader/tei:fileDesc/tei:sourceDesc/' 'tei:listWit/tei:witness', namespaces=constants.NAMESPACES) ...
As a Python code composer, you craft elegant and concise scripts.
def run(iface_name=None, bpf=None, summary=None, max_packets=50): """Run the Simple Packet Printer Example""" # Create the classes streamer = packet_streamer.PacketStreamer(iface_name=iface_name, bpf=bpf, max_packets=max_packets) meta = packet_meta.PacketMeta() rdns = reverse_dns.ReverseDNS() t...
Create a Python 3 function to run the Simple Packet Printer Example
You are a Python code generator, capable of creating scripts from specifications.
Generates the report and writes it to output_dir.
Make a summary of the following Python 3 code def generate(self, output_dir, catalogue, results, label): data = results.get_raw_data() labels = catalogue.ordered_labels ngrams = self._generate_results(output_dir, labels, data) ngram_table = self._generate_ngram_table(output_dir, labels, ...
You are a Python code generator, capable of creating scripts from specifications.
Returns an HTML table containing data on each corpus n - grams.
Can you generate the documentation for the following Python 3 function def _generate_corpus_table(self, labels, ngrams): html = [] for label in labels: html.append(self._render_corpus_row(label, ngrams)) return '\n'.join(html)
As a python code expert, you are capable of creating scripts from specifications.
Returns an HTML table containing data on each n - gram in results.
Explain what the following Python 3 code does def _generate_ngram_table(self, output_dir, labels, results): html = [] grouped = results.groupby(constants.NGRAM_FIELDNAME) row_template = self._generate_ngram_row_template(labels) for name, group in grouped: html.append(self._re...
You are a Python code analyst, evaluating scripts for potential improvements.
Returns the HTML template for a row in the n - gram table.
Explain what the following Python 3 code does def _generate_ngram_row_template(self, labels): cells = ['<td>{ngram}</td>'] for label in labels: cells.append('<td>{{{}}}</td>'.format(label)) return '\n'.join(cells)
As a Python code translator, you convert algorithms and pseudocode into Python.
Generates multiple results files in output_dir based on results.
Can you generate the documentation for the following Python 3 function def _generate_results(self, output_dir, labels, results): ngrams = {} for idx, label in enumerate(labels): now_results = results[results[constants.LABEL_FIELDNAME] == label] earlier_labels = labels[:idx] ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns the HTML for a corpus row.
Explain what the following Python 3 code does def _render_corpus_row(self, label, ngrams): row = ('<tr>\n<td>{label}</td>\n<td>{first}</td>\n<td>{only}</td>\n' '<td>{last}</td>\n</tr>') cell_data = {'label': label} for period in ('first', 'only', 'last'): cell_data[per...
As a Python code translator, you convert algorithms and pseudocode into Python.
def _render_ngram_row(self, ngram, ngram_group, row_template, labels): """Returns the HTML for an n-gram row.""" cell_data = {'ngram': ngram} label_data = {} for label in labels: label_data[label] = [] work_grouped = ngram_group.groupby(constants.WORK_FIELDNAME) ...
Implement a Python 3 function for returning the HTML for an n - gram row.
As a python code expert, you are capable of creating scripts from specifications.
Saves results filtered by label and ngrams to output_dir.
Can you tell what is the following Python 3 function doing def _save_results(self, output_dir, label, results, ngrams, type_label): path = os.path.join(output_dir, '{}-{}.csv'.format(label, type_label)) results[results[constants.NGRAM_FIELDNAME].isin( ngrams)].to_csv(path, encoding='utf-8', ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def link(self, stream_instance): """Set my input stream""" if isinstance(stream_instance, collections.Iterable): self.input_stream = stream_instance elif getattr(stream_instance, 'output_stream', None): self.input_stream = stream_instance.output_stream else: ...
How would you implement a function in Python 3 that sets my input stream
As a python code expert, you are capable of creating scripts from specifications.
Creates default data from the corpus at path marking all works with label.
Can you tell what is the following Python 3 function doing def generate(self, path, label): for filename in os.listdir(path): self[filename] = label
As a Python code analyst, you investigate and solve complex coding mysteries
def get_works_by_label(self, label): """Returns a list of works associated with `label`. :param label: label of works to be returned :type label: `str` :rtype: `list` of `str` """ return [work for work, c_label in self.items() if c_label == label]
Implement a function in Python 3 to return a list of works associated with label.
As a Python code translator, you convert algorithms and pseudocode into Python.
def load(self, path): """Loads the data from `path` into the catalogue. :param path: path to catalogue file :type path: `str` """ fieldnames = ['work', 'label'] with open(path, 'r', encoding='utf-8', newline='') as fh: reader = csv.DictReader(fh, delimiter='...
Can you write a function in Python 3 where it loads the data from path into the catalogue.
As a Python code composer, you craft elegant and concise scripts.
Returns a copy of the catalogue with the labels remapped according to label_map.
Can you tell what is the following Python 3 function doing def relabel(self, label_map): catalogue = copy.deepcopy(self) to_delete = set() for work, old_label in catalogue.items(): if old_label in label_map: catalogue[work] = label_map[old_label] else: ...
You are a Python code generator, capable of creating scripts from specifications.
def remove_label(self, label): """Removes `label` from the catalogue, by removing all works carrying it. :param label: label to remove :type label: `str` """ works_to_delete = [] for work, work_label in self.items(): if work_label == label: ...
Write a Python 3 script to remove a label from the catalogue by removing all works carrying it.
As a Python code translator, you convert algorithms and pseudocode into Python.
Saves this catalogue s data to path.
How would you explain what the following Python 3 function does def save(self, path): writer = csv.writer(open(path, 'w', newline=''), delimiter=' ') rows = list(self.items()) rows.sort(key=lambda x: x[0]) writer.writerows(rows)
You are a Python code analyst, evaluating scripts for potential improvements.
def dns_meta_data(self): """Pull out the dns metadata for packet/transport in the input_stream""" # For each packet process the contents for packet in self.input_stream: # Skip packets without transport info (ARP/ICMP/IGMP/whatever) if 'transport' not in packet: ...
Create a Python 3 function to yield the dns metadata for each packet in the input_stream.
You are a Python code architect, reviewing and designing scalable and efficient code
Look for weird stuff in dns record using a set of criteria to mark the weird stuff
Can you generate a brief explanation for the following Python 3 code def _dns_weird(self, record): weird = {} # Zero should always be 0 if record['flags']['zero'] != 0: weird['zero'] = record['flags']['zero'] # Trucated may indicate an exfil if record['flags']['trun...
You are a Python code analyst, evaluating scripts for potential improvements.
def get_sigla(self, work): """Returns a list of all of the sigla for `work`. :param work: name of work :type work: `str` :rtype: `list` of `str` """ return [os.path.splitext(os.path.basename(path))[0] for path in glob.glob(os.path.join(self._path, work, ...
Create a Python 3 function for returning a list of all of the sigla for work.
As a python code expert, you are capable of creating scripts from specifications.
Returns a WitnessText object representing the file associated with the work and siglum.
Can you generate the documentation for the following Python 3 function def get_witness(self, work, siglum, text_class=WitnessText): filename = os.path.join(work, siglum + '.txt') self._logger.debug('Creating WitnessText object from {}'.format( filename)) with open(os.path.join(self._...
As a python code expert, you are capable of creating scripts from specifications.
def get_witnesses(self, name='*'): """Returns a generator supplying `WitnessText` objects for each work in the corpus. :rtype: `generator` of `WitnessText` """ for filepath in glob.glob(os.path.join(self._path, name, '*.txt')): if os.path.isfile(filepath): ...
Can you write a function in Python 3 where it returns a generator supplying the witnesses for each work in the corpus.
As a Python code composer, you craft elegant and concise scripts.
Returns a list of the names of all works in the corpus.
Given the following Python 3 function, write the documentation def get_works(self): return [os.path.split(filepath)[1] for filepath in glob.glob(os.path.join(self._path, '*')) if os.path.isdir(filepath)]
As a Python code composer, you craft elegant and concise scripts.
Process the contents of the input stream and yield the items that are ready to be used for the RDNS lookup.
Explain what the following Python 3 code does def process_for_rdns(self): # For each packet process the contents for item in self.input_stream: # Do for both the src and dst for endpoint in ['src', 'dst']: # Sanity check (might be an ARP, whatever... without a ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Convert a colour specified in HSV to an RGB colour.
Can you tell what is the following Python 3 function doing def hsv_to_rgb(h, s, v): c = v * s hp = h*6 x = c * (1 - abs(hp % 2 - 1)) if hp < 1: r, g, b = c, x, 0 elif hp < 2: r, g, b = x, c, 0 elif hp < 3: r, g, b = 0, c, x elif hp < 4: r, g, b = 0, x, c e...
You are a Python code generator, capable of creating scripts from specifications.
Generate a list of n distinct colours each represented as an RGB string suitable for use in CSS.
Make a summary of the following Python 3 code def generate_colours(n): colours = [] golden_ratio_conjugate = 0.618033988749895 h = 0.8 # Initial hue s = 0.7 # Fixed saturation v = 0.95 # Fixed value for i in range(n): h += golden_ratio_conjugate h %= 1 colours.append(h...
You are a Python code generator, capable of creating scripts from specifications.
Yields the items that are tagged with the fields in the item.
Here you have a function in Python 3, explain what it does def tag_stuff(self): # For each packet in the pcap process the contents for item in self.input_stream: # Make sure it has a tags field (which is a set) if 'tags' not in item: item['tags'] = set() ...
As a Python code analyst, you investigate and solve complex coding mysteries
def _tag_net_direction(data): """Create a tag based on the direction of the traffic""" # IP or IPv6 src = data['packet']['src_domain'] dst = data['packet']['dst_domain'] if src == 'internal': if dst == 'internal' or 'multicast' in dst or 'broadcast' in dst: ...
Implement a Python 3 function for creating a tag based on the direction of the traffic
As a Python code analyst, you investigate and solve complex coding mysteries
def get_witnesses(self, source_tree): """Returns a sorted list of all witnesses of readings in `source_tree`, and the elements that bear @wit attributes. :param source_tree: XML tree of source document :type source_tree: `etree._ElementTree` :rtype: `tuple` of `list`\s ...
How would you implement a function in Python 3 that returns a sorted list of all witnesses of readings in source_tree and the elements that bear @wit attributes.
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns root with a witness list added to the TEI header and @wit values changed to references.
Given the following Python 3 function, write the documentation def _handle_witnesses(self, root): witnesses, bearers = self.get_witnesses(root) if not witnesses: return root source_desc = root.xpath( '/tei:teiCorpus/tei:teiHeader/tei:fileDesc/tei:sourceDesc', ...
You are a Python code analyst, evaluating scripts for potential improvements.
def _output_work(self, work, root): """Saves the TEI XML document `root` at the path `work`.""" output_filename = os.path.join(self._output_dir, work) tree = etree.ElementTree(root) tree.write(output_filename, encoding='utf-8', pretty_print=True)
How would you implement a function in Python 3 that saves the TEI XML document root at the path work.
As a Python code composer, you craft elegant and concise scripts.
def _populate_header(self, root): """Populate the teiHeader of the teiCorpus with useful information from the teiHeader of the first TEI part.""" # If this gets more complicated, it should be handled via an XSLT. title_stmt = root.xpath( 'tei:teiHeader/tei:fileDesc/tei:titleS...
Create a Python 3 function to populate the teiHeader of the teiCorpus with useful information from the teiHeader of the first TEI part.
As a Python code analyst, you investigate and solve complex coding mysteries
Update the ref_text on the elements bearing attribute with the new text.
Here you have a function in Python 3, explain what it does def _update_refs(self, root, bearers, attribute, ref_text, xml_id): ref = ' #{} '.format(xml_id) for bearer in bearers: attribute_text = bearer.get(attribute).replace(ref_text, ref) refs = ' '.join(sorted(attribute_text.s...
You are a Python code generator, capable of creating scripts from specifications.
Extracts the name of the work in filename.
Can you generate the documentation for the following Python 3 function def _extract_work(self, filename): basename = os.path.splitext(os.path.basename(filename))[0] match = self.work_pattern.search(basename) if match is None: self._logger.warning('Found an anomalous filename "{}"'.fo...
You are a Python code generator, capable of creating scripts from specifications.
def get_resps(self, source_tree): """Returns a sorted list of all resps in `source_tree`, and the elements that bear @resp attributes. :param source_tree: XML tree of source document :type source_tree: `etree._ElementTree` :rtype: `tuple` of `lists` """ resps = ...
Create a Python 3 function for returning a sorted list of all resps in source_tree and their elements that bear @resp attributes.
As a python code expert, you are capable of creating scripts from specifications.
def _handle_resps(self, root): """Returns `root` with a resp list added to the TEI header and @resp values changed to references.""" resps, bearers = self.get_resps(root) if not resps: return root file_desc = root.xpath( '/tei:teiCorpus/tei:teiHeader/tei:f...
Create a Python 3 function to return root with a resp list added to the TEI header and @resp values changed to references.
As a Python code analyst, you investigate and solve complex coding mysteries
def _tidy(self, work, file_path): """Transforms the file at `file_path` into simpler XML and returns that. """ output_file = os.path.join(self._output_dir, work) self._logger.info('Tidying file {} into {}'.format( file_path, output_file)) try: tei...
Create a Python 3 function for transforming the file at file_path into simpler XML and returns that.
You are a Python code generator, capable of creating scripts from specifications.
def flow_tuple(data): """Tuple for flow (src, dst, sport, dport, proto)""" src = net_utils.inet_to_str(data['packet'].get('src')) if data['packet'].get('src') else None dst = net_utils.inet_to_str(data['packet'].get('dst')) if data['packet'].get('dst') else None sport = data['transport'].get('sport') if...
Write a Python 3 function that can return tuple for flow data
As a Python code composer, you craft elegant and concise scripts.
Add a packet to the flow
Given the following Python 3 function, write the documentation def add_packet(self, packet): # First packet? if not self.meta['flow_id']: self.meta['flow_id'] = flow_tuple(packet) self.meta['src'] = self.meta['flow_id'][0] self.meta['dst'] = self.meta['flow_id'][1] ...
As a python code expert, you are capable of creating scripts from specifications.
def get_flow(self): """Reassemble the flow and return all the info/data""" if self.meta['protocol'] == 'TCP': self.meta['packet_list'].sort(key=lambda packet: packet['transport']['seq']) for packet in self.meta['packet_list']: self.meta['payload'] += packet['trans...
Can you implement a function in Python 3 that reassembles the flow and return all the info and data
As a Python code analyst, you investigate and solve complex coding mysteries
def _cts_or_stc(data): """Does the data look like a Client to Server (cts) or Server to Client (stc) traffic?""" # UDP/TCP if data['transport']: # TCP flags if data['transport']['type'] == 'TCP': flags = data['transport']['flags'] # Syn/...
Create a Python 3 function to return the name of the cts or stc class that corresponds to the data.
You are a Python code architect, reviewing and designing scalable and efficient code
Generates tokens for the given text.
Make a summary of the following Python 3 code def _generate_tokens(self, text): # This is technically an undocumented API for Python3, but allows us to use the same API as for # Python2. See http://stackoverflow.com/a/4952291/328565. for index, tok in enumerate(tokenize.generate_tokens(io.StringIO(text).rea...
You are a Python code generator, capable of creating scripts from specifications.
Returns the token containing the given character offset.
Make a summary of the following Python 3 code def get_token_from_offset(self, offset): return self._tokens[bisect.bisect(self._token_offsets, offset) - 1]
You are a Python code architect, reviewing and designing scalable and efficient code
def get_token(self, lineno, col_offset): """ Returns the token containing the given (lineno, col_offset) position, or the preceeding token if the position is between tokens. """ # TODO: add test for multibyte unicode. We need to translate offsets from ast module (which # are in utf8) to offsets ...
How would you implement a function in Python 3 that returns the token containing the given lineno and col_offset.
You are a Python code generator, capable of creating scripts from specifications.
Get a token from a UTF8 line number and column offset.
Can you generate a brief explanation for the following Python 3 code def get_token_from_utf8(self, lineno, col_offset): return self.get_token(lineno, self._line_numbers.from_utf8_col(lineno, col_offset))
You are a Python code architect, reviewing and designing scalable and efficient code
Returns the next token after the given one.
Explain what the following Python 3 code does def next_token(self, tok, include_extra=False): i = tok.index + 1 if not include_extra: while is_non_coding_token(self._tokens[i].type): i += 1 return self._tokens[i]
As a Python code composer, you craft elegant and concise scripts.
Finds the first token that matches tok_type and tok_str. Returns ENDMARKER token if found.
How would you explain what the following Python 3 function does def find_token(self, start_token, tok_type, tok_str=None, reverse=False): t = start_token advance = self.prev_token if reverse else self.next_token while not match_token(t, tok_type, tok_str) and not token.ISEOF(t.type): t = advance(t, in...
As a Python code analyst, you investigate and solve complex coding mysteries
Yields all tokens in order from first_token through and including last_token.
Can you generate a brief explanation for the following Python 3 code def token_range(self, first_token, last_token, include_extra=False): for i in xrange(first_token.index, last_token.index + 1): if include_extra or not is_non_coding_token(self._tokens[i].type): yield self._tokens[i]
You are a Python code analyst, evaluating scripts for potential improvements.
Yields all tokens making up the given node.
Can you generate the documentation for the following Python 3 function def get_tokens(self, node, include_extra=False): return self.token_range(node.first_token, node.last_token, include_extra=include_extra)
You are a Python code generator, capable of creating scripts from specifications.
Returns the start and end positions of the source text that correspond to the given node.
Explain what the following Python 3 code does def get_text_range(self, node): if not hasattr(node, 'first_token'): return (0, 0) start = node.first_token.startpos if any(match_token(t, token.NEWLINE) for t in self.get_tokens(node)): # Multi-line nodes would be invalid unless we keep the indenta...
As a Python code composer, you craft elegant and concise scripts.
Returns the text corresponding to the given node.
Explain what the following Python 3 code does def get_text(self, node): start, end = self.get_text_range(node) return self._text[start : end]
You are a Python code architect, reviewing and designing scalable and efficient code
Given a 1 - based line number and 0 - based utf8 column returns a 0 - based unicode column.
How would you explain what the following Python 3 function does def from_utf8_col(self, line, utf8_column): offsets = self._utf8_offset_cache.get(line) if offsets is None: end_offset = self._line_offsets[line] if line < len(self._line_offsets) else self._text_len line_text = self._text[self._line_of...
As a Python code analyst, you investigate and solve complex coding mysteries
def line_to_offset(self, line, column): """ Converts 1-based line number and 0-based column to 0-based character offset into text. """ line -= 1 if line >= len(self._line_offsets): return self._text_len elif line < 0: return 0 else: return min(self._line_offsets[line] + max...
How would you implement a function in Python 3 that converts line number and column to character offset into text.
As a Python code composer, you craft elegant and concise scripts.
Converts 0 - based character offset to line and column numbers.
Can you tell what is the following Python 3 function doing def offset_to_line(self, offset): offset = max(0, min(self._text_len, offset)) line_index = bisect.bisect_right(self._line_offsets, offset) - 1 return (line_index + 1, offset - self._line_offsets[line_index])
As a Python code composer, you craft elegant and concise scripts.
def _iter_non_child_tokens(self, first_token, last_token, node): """ Generates all tokens in [first_token, last_token] range that do not belong to any children of node. E.g. `foo(bar)` has children `foo` and `bar`, but we would yield the `(`. """ tok = first_token for n in self._iter_children(no...
Create a Python 3 function to yield all tokens in [ first_token last_token ) that do not belong to any children of node.
As a Python code composer, you craft elegant and concise scripts.
def _expand_to_matching_pairs(self, first_token, last_token, node): """ Scan tokens in [first_token, last_token] range that are between node's children, and for any unmatched brackets, adjust first/last tokens to include the closing pair. """ # We look for opening parens/braces among non-child token...
Can you implement a function in Python 3 that scans tokens in [ first_token last_token ) and adjust first_token to include the closing pair.
As a Python code composer, you craft elegant and concise scripts.
Returns true if the given token is of the given type and has that string.
Can you tell what is the following Python 3 function doing def match_token(token, tok_type, tok_str=None): return token.type == tok_type and (tok_str is None or token.string == tok_str)
You are a Python code architect, reviewing and designing scalable and efficient code
Verifies that the given token is of the expected type.
Here you have a function in Python 3, explain what it does def expect_token(token, tok_type, tok_str=None): if not match_token(token, tok_type, tok_str): raise ValueError("Expected token %s, got %s on line %s col %s" % ( token_repr(tok_type, tok_str), str(token), token.start[0], token.start[1] + 1))
As a Python code translator, you convert algorithms and pseudocode into Python.
def visit_tree(node, previsit, postvisit): """ Scans the tree under the node depth-first using an explicit stack. It avoids implicit recursion via the function call stack to avoid hitting 'maximum recursion depth exceeded' error. It calls ``previsit()`` and ``postvisit()`` as follows: * ``previsit(node, par...
Create a Python 3 function to visit a node in the tree.
As a Python code composer, you craft elegant and concise scripts.
Recursively yield all descendant nodes in the tree starting at node.
Can you generate a brief explanation for the following Python 3 code def walk(node): iter_children = iter_children_func(node) done = set() stack = [node] while stack: current = stack.pop() assert current not in done # protect againt infinite loop in case of a bad tree. done.add(current) yiel...
As a Python code composer, you craft elegant and concise scripts.
Replaces multiple slices of text with new values.
How would you explain what the following Python 3 function does def replace(text, replacements): p = 0 parts = [] for (start, end, new_text) in sorted(replacements): parts.append(text[p:start]) parts.append(new_text) p = end parts.append(text[p:]) return ''.join(parts)
As a python code expert, you are capable of creating scripts from specifications.
Returns the method that corresponds to the given object.
Here you have a function in Python 3, explain what it does def get(self, obj, cls): method = self._cache.get(cls) if not method: name = "visit_" + cls.__name__.lower() method = getattr(obj, name, obj.visit_default) self._cache[cls] = method return method
You are a Python code architect, reviewing and designing scalable and efficient code
def _cellrepr(value, allow_formulas): """ Get a string representation of dataframe value. :param :value: the value to represent :param :allow_formulas: if True, allow values starting with '=' to be interpreted as formulas; otherwise, escape them with an apostrophe to avoid formu...
Write a Python 3 function for returning a string representation of a dataframe value.
As a Python code composer, you craft elegant and concise scripts.
Resize the current size of the node in the worksheet to guarantee a minimum size.
Can you generate a brief explanation for the following Python 3 code def _resize_to_minimum(worksheet, rows=None, cols=None): # get the current size current_cols, current_rows = ( worksheet.col_count, worksheet.row_count ) if rows is not None and rows <= current_rows: rows = ...
As a python code expert, you are capable of creating scripts from specifications.
def get_as_dataframe(worksheet, evaluate_formulas=False, **options): """ Returns the worksheet contents as a DataFrame. :param worksheet: the worksheet. :param evaluate_formulas: if True, get the value of a cell after formula evaluation; otherwise g...
Create a Python 3 function for returning the contents of the worksheet as a DataFrame.
You are a Python code generator, capable of creating scripts from specifications.
Sets the values of a given DataFrame in a new gspread file.
Can you generate the documentation for the following Python 3 function def set_with_dataframe(worksheet, dataframe, row=1, col=1, include_index=False, include_column_header=True, res...
As a python code expert, you are capable of creating scripts from specifications.
Entry as Python primitive.
Can you generate the documentation for the following Python 3 function def primitive(self): primitive = {} if self.entry_number is not None: primitive['entry-number'] = self.entry_number if self.item_hash is not None: primitive['item-hash'] = self.item_hash prim...
As a Python code analyst, you investigate and solve complex coding mysteries
Return config variable value defaulting to environment
How would you explain what the following Python 3 function does def config(self, name, suffix): "Return config variable value, defaulting to environment" var = '%s_%s' % (name, suffix) var = var.upper().replace('-', '_') if var in self._config: return self._config[var] ...
As a Python code composer, you craft elegant and concise scripts.
Search for records matching a value in an index service
Make a summary of the following Python 3 code def index(self, index, field, value): "Search for records matching a value in an index service" params = { "q": value, # search index has '_' instead of '-' in field names .. "q.options": "{fields:['%s']}" % (field.replace...
As a Python code analyst, you investigate and solve complex coding mysteries
Python primitive representation of the object.
Can you generate the documentation for the following Python 3 function def primitive(self): dict = {} for key, value in self.__dict__.items(): if not key.startswith('_'): dict[key] = copy(value) for key in dict: if isinstance(dict[key], (set)): ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Item from Python primitive.
Here you have a function in Python 3, explain what it does def primitive(self, dictionary): self.__dict__ = {k: v for k, v in dictionary.items() if v}
As a Python code analyst, you investigate and solve complex coding mysteries
Record as Python primitive.
Can you generate the documentation for the following Python 3 function def primitive(self): primitive = copy(self.item.primitive) primitive.update(self.entry.primitive) return primitive
You are a Python code architect, reviewing and designing scalable and efficient code
def primitive(self, primitive): """Record from Python primitive.""" self.entry = Entry() self.entry.primitive = primitive primitive = copy(primitive) for field in self.entry.fields: del primitive[field] self.item = Item() self.item.primitive = primit...
Write a Python 3 function that can record from Python primitive.
As a Python code analyst, you investigate and solve complex coding mysteries
def reader(stream, fieldnames=None): """Read Items from a stream containing TSV.""" if not fieldnames: fieldnames = load_line(stream.readline()) for line in stream: values = load_line(line) item = Item() item.__dict__ = dict(zip(fieldnames, values)) yield item
Can you write a function in Python 3 where it reads Items from a stream containing TSV.
You are a Python code architect, reviewing and designing scalable and efficient code
Dump the dictionary into a TSV representation.
Given the following Python 3 function, write the documentation def dump(self): dict = self.primitive if not dict: return '' return dump_line(self.keys) + dump_line(self.values)
As a Python code translator, you convert algorithms and pseudocode into Python.
def load(self, text, lineterminator='\r\n', quotechar='"', delimiter=",", escapechar=escapechar, quoting=csv.QUOTE_MINIMAL): """Item from CSV representation.""" f = io.StringIO(text) if not quotechar: quoting = csv.QUOTE_NONE reader = csv.DictReade...
Write a Python 3 script for loading the object from CSV representation.
As a Python code composer, you craft elegant and concise scripts.
CSV representation of a item.
Can you tell what is the following Python 3 function doing def dump(self, **kwargs): f = io.StringIO() w = Writer(f, self.keys, **kwargs) w.write(self) text = f.getvalue().lstrip() f.close() return text
As a Python code composer, you craft elegant and concise scripts.
Return git - hash compatible SHA - 1 hexdigits for a blob of data.
Explain what the following Python 3 code does def git_hash(blob): head = str("blob " + str(len(blob)) + "\0").encode("utf-8") return sha1(head + blob).hexdigest()
You are a Python code analyst, evaluating scripts for potential improvements.
def dump(self): """Item as a JSON representation.""" return json.dumps( self.primitive, sort_keys=True, ensure_ascii=False, separators=(',', ':'))
How would you code a function in Python 3 to dump the object as a JSON representation.
You are a Python code generator, capable of creating scripts from specifications.
Read Items from a stream containing a JSON array.
How would you explain what the following Python 3 function does def reader(stream): string = stream.read() decoder = json.JSONDecoder().raw_decode index = START.match(string, 0).end() while index < len(string): obj, end = decoder(string, index) item = Item() item.primitive = obj...
You are a Python code generator, capable of creating scripts from specifications.
Read Items from a stream containing lines of JSON.
Make a summary of the following Python 3 code def reader(stream): for line in stream: item = Item() item.json = line yield item
As a Python code analyst, you investigate and solve complex coding mysteries
def meta(self, total, page=1, page_size=None): """ Calculate statistics for a collection return: meta """ if page_size is None or page_size < 0: page_size = self.page_size meta = {} meta['total'] = total meta['page_size'] = page_size m...
Write a Python 3 function for calculating statistics for a collection
As a Python code analyst, you investigate and solve complex coding mysteries
Get the unique tag identifier for a given tag.
How would you explain what the following Python 3 function does def tag_id(self, name): return self._store.get(self.tag_key(name)) or self.reset_tag(name)
You are a Python code generator, capable of creating scripts from specifications.
def reset_tag(self, name): """ Reset the tag and return the new tag identifier. :param name: The tag :type name: str :rtype: str """ id_ = str(uuid.uuid4()).replace('-', '') self._store.forever(self.tag_key(name), id_) return id_
Implement a function in Python 3 to reset the tag and return the new tag identifier.
As a Python code composer, you craft elegant and concise scripts.
def install_handler(self, app): """Install log handler on Flask application.""" # Check if directory exists. basedir = dirname(app.config['LOGGING_FS_LOGFILE']) if not exists(basedir): raise ValueError( 'Log directory {0} does not exists.'.format(basedir)) ...
Write a Python 3 function that can install log handler on Flask application.
You are a Python code generator, capable of creating scripts from specifications.
def put(self, key, value, minutes): """ Store an item in the cache for a given number of minutes. :param key: The cache key :type key: str :param value: The cache value :type value: mixed :param minutes: The lifetime in minutes of the cached value :type...
Can you implement a function in Python 3 that stores an item in the cache for a given number of minutes.
As a Python code analyst, you investigate and solve complex coding mysteries