Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Predict the next line for this snippet: <|code_start|> # seq_crumbs is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with seq_crumbs. If not, see <http://www.gnu.org/licenses/>. # pylint: disable=R0201 # pylint: disable=R0904 # pylint: disable=W0402 # pylint: disable=C0111 FASTQ_NO_DUPS1 = '''@CUESXEL822 1:Y:18:ATCACG TAATACACCCAGTCTCAATTCCATCCTGGGAACTAAGT + AEGDFG5GGEGGF;EGD=D@>GCCGFFGGGCECFE:D@ @CUESXEL822 2:Y:18:ATCACG TCATTACGTAGCTCCGGCTCCGCCATGTCTGTTCCTTC + CG?BEGGGGFGGGGGGGGGGGGGGGGBGGGA<EE=515 @CUESXEL824 1:Y:18:ATCACG GATTGAAGCTCCAAACCGCCATGTTCACCACCGCAAGC + HHGEHD8EEHHHDGHHHHHHHHHCEHHHHDHHHHEHHH <|code_end|> with the help of current file imports: import unittest import os from subprocess import check_output from tempfile import NamedTemporaryFile from StringIO import StringIO from crumbs.seq.seq import SeqWrapper, SeqItem from crumbs.utils.tags import SEQITEM from crumbs.seq.bulk_filters import (filter_duplicates, _read_pairs, _seqitem_pairs_equal) from crumbs.utils.bin_utils import BIN_DIR from crumbs.utils.test_utils import TEST_DATA_DIR from crumbs.exceptions import UndecidedFastqVersionError from crumbs.utils.file_utils import flush_fhand and context from other files: # Path: crumbs/seq/seq.py # class SeqItem(_SeqItem): # def __new__(cls, name, lines, annotations=None): # def get_title(seq): # def get_description(seq): # def get_name(seq): # def get_file_format(seq): # def _break(): # def _is_fastq_plus_line(line, seq_name): # def _get_seqitem_quals(seq): # def get_str_seq(seq): # def get_length(seq): # def _get_seqitem_qualities(seqwrap): # def get_int_qualities(seq): # def _int_quals_to_str_quals(int_quals, out_format): # def get_str_qualities(seq, out_format=None): # def get_annotations(seq): # def _copy_seqrecord(seqrec, seq=None, name=None, id_=None): # def _copy_seqitem(seqwrapper, seq=None, name=None): # def copy_seq(seqwrapper, seq=None, name=None): # def _slice_seqitem(seqwrap, start, stop): # def slice_seq(seq, start=None, stop=None): # def assing_kind_to_seqs(kind, seqs, file_format): # SANGER_QUALS = {chr(i): i - 33 for i in range(33, 127)} # ILLUMINA_QUALS = {chr(i): i - 64 for i in range(64, 127)} # SANGER_STRS = {i - 33: chr(i) for i in range(33, 127)} # ILLUMINA_STRS = {i - 64: chr(i) for i in range(64, 127)} # # Path: crumbs/utils/tags.py # SEQITEM = 'seqitem' # # Path: crumbs/seq/bulk_filters.py # def filter_duplicates(in_fhands, out_fhand, paired_reads, use_length=None, # n_seqs_packet=None, tempdir=None): # if not in_fhands: # raise ValueError('At least one input fhand is required') # pairs = _read_pairs(in_fhands, paired_reads) # get_pair_key = _PairKeyGetter(use_length=use_length) # if n_seqs_packet is None: # unique_pairs = unique_unordered(pairs, key=get_pair_key) # else: # sorted_pairs = sorted_items(pairs, key=get_pair_key, tempdir=tempdir, # max_items_in_memory=n_seqs_packet) # unique_pairs = unique(sorted_pairs, key=get_pair_key) # for pair in unique_pairs: # write_seqs(pair, out_fhand) # # def _read_pairs(in_fhands, paired_reads): # seqs = read_seqs(in_fhands, prefered_seq_classes=[SEQITEM]) # if paired_reads: # pairs = group_pairs_by_name(seqs) # else: # pairs = group_pairs(seqs, n_seqs_in_pair=1) # return pairs # # def _seqitem_pairs_equal(pair1, pair2): # if len(pair1) != len(pair2): # return False # else: # for read1, read2 in zip(pair1, pair2): # if not get_str_seq(read1) == get_str_seq(read2): # return False # return True # # Path: crumbs/utils/bin_utils.py # BIN_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', # 'bin')) # # Path: crumbs/utils/test_utils.py # TEST_DATA_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', # '..', 'test', 'test_data')) # # Path: crumbs/exceptions.py # class UndecidedFastqVersionError(Exception): # 'The file is Fastq, but the version is difficult to guess' # pass # # Path: crumbs/utils/file_utils.py # def flush_fhand(fhand): # try: # fhand.flush() # except IOError, error: # # The pipe could be already closed # if 'Broken pipe' not in str(error): # raise , which may contain function names, class names, or code. Output only the next line.
@CUESXEL824 2:Y:18:ATCACG
Given the following code snippet before the placeholder: <|code_start|> # the query name and definition definition = bio_result.query if self.use_query_def_as_accession: items = definition.split(' ', 1) name = items[0] if len(items) > 1: definition = items[1] else: definition = None else: name = bio_result.query_id definition = definition if definition is None: definition = "<unknown description>" # length of query sequence length = bio_result.query_letters # now we can create the query sequence query = {'name': name, 'description': definition, 'length': length} # now we go for the hits (matches) matches = [] for alignment in bio_result.alignments: # the subject sequence if self.use_subject_def_as_accession: items = alignment.hit_def.split(' ', 1) name = items[0] if len(items) > 1: definition = items[1] else: definition = None <|code_end|> , predict the next line using imports from the current file: import itertools import copy import os from math import log10 from crumbs.utils.optional_modules import NCBIXML from crumbs.utils.tags import SUBJECT, QUERY, ELONGATED from crumbs.utils.segments_utils import merge_overlaping_segments and context including class names, function names, and sometimes code from other files: # Path: crumbs/utils/optional_modules.py # NCBIXML = create_fake_class(MSG + BIO) # # Path: crumbs/utils/tags.py # SUBJECT = 'subject' # # QUERY = 'query' # # ELONGATED = 'elongated' # # Path: crumbs/utils/segments_utils.py # def merge_overlaping_segments(segments, merge_segments_closer=1): # '''Given a list of segments it returns the overlapped segments. # # segments 1 ------- -----> ----------- # segments 2 ------ # returns ----------- ------ ----------- # merge_segments_closer is an integer. Segments closer than the given # number of residues will be merged. # ''' # # # we collect all start and ends # limits = [] # for segment in segments: # start = segment[0] # end = segment[1] # if start > end: # a reversed item # start, end = end, start # limit_1 = (START, start) # limit_2 = (END, end) # limits.append(limit_1) # limits.append(limit_2) # # # sort by secondary key: start before end # limits.sort(key=itemgetter(0)) # # sort by location (primary key) # limits.sort(key=itemgetter(1)) # # # merge the ends and start that differ in only one base # filtered_limits = [] # previous_limit = None # for limit in limits: # if previous_limit is None: # previous_limit = limit # continue # if (previous_limit[0] == END and limit[0] == START and # previous_limit[1] >= limit[1] - merge_segments_closer): # # These limits cancelled each other # previous_limit = None # continue # filtered_limits.append(previous_limit) # previous_limit = limit # else: # filtered_limits.append(limit) # limits = filtered_limits # # # now we create the merged hsps # starts = 0 # segments = [] # for limit in limits: # if limit[0] == START: # starts += 1 # if starts == 1: # segment_start = limit[1] # elif limit[0] == END: # starts -= 1 # if starts == 0: # segment = (segment_start, limit[1]) # segments.append(segment) # return segments . Output only the next line.
else:
Given snippet: <|code_start|> similarity = None try: identity = hsp.identities * 100.0 / float(hsp_length) except TypeError: identity = None match_parts.append({'subject_start': subject_start, 'subject_end': subject_end, 'subject_strand': subject_strand, 'query_start': query_start, 'query_end': query_end, 'query_strand': query_strand, 'scores': {'similarity': similarity, 'expect': expect, 'identity': identity} }) # It takes the first loc and the last loc of the hsp to # determine hit start and end if match_start is None or query_start < match_start: match_start = query_start if match_end is None or query_end > match_end: match_end = query_end if (match_subject_start is None or subject_start < match_subject_start): match_subject_start = subject_start if (match_subject_end is None or subject_end > match_subject_end): match_subject_end = subject_end matches.append({ 'subject': subject, 'start': match_start, <|code_end|> , continue by predicting the next line. Consider current file imports: import itertools import copy import os from math import log10 from crumbs.utils.optional_modules import NCBIXML from crumbs.utils.tags import SUBJECT, QUERY, ELONGATED from crumbs.utils.segments_utils import merge_overlaping_segments and context: # Path: crumbs/utils/optional_modules.py # NCBIXML = create_fake_class(MSG + BIO) # # Path: crumbs/utils/tags.py # SUBJECT = 'subject' # # QUERY = 'query' # # ELONGATED = 'elongated' # # Path: crumbs/utils/segments_utils.py # def merge_overlaping_segments(segments, merge_segments_closer=1): # '''Given a list of segments it returns the overlapped segments. # # segments 1 ------- -----> ----------- # segments 2 ------ # returns ----------- ------ ----------- # merge_segments_closer is an integer. Segments closer than the given # number of residues will be merged. # ''' # # # we collect all start and ends # limits = [] # for segment in segments: # start = segment[0] # end = segment[1] # if start > end: # a reversed item # start, end = end, start # limit_1 = (START, start) # limit_2 = (END, end) # limits.append(limit_1) # limits.append(limit_2) # # # sort by secondary key: start before end # limits.sort(key=itemgetter(0)) # # sort by location (primary key) # limits.sort(key=itemgetter(1)) # # # merge the ends and start that differ in only one base # filtered_limits = [] # previous_limit = None # for limit in limits: # if previous_limit is None: # previous_limit = limit # continue # if (previous_limit[0] == END and limit[0] == START and # previous_limit[1] >= limit[1] - merge_segments_closer): # # These limits cancelled each other # previous_limit = None # continue # filtered_limits.append(previous_limit) # previous_limit = limit # else: # filtered_limits.append(limit) # limits = filtered_limits # # # now we create the merged hsps # starts = 0 # segments = [] # for limit in limits: # if limit[0] == START: # starts += 1 # if starts == 1: # segment_start = limit[1] # elif limit[0] == END: # starts -= 1 # if starts == 0: # segment = (segment_start, limit[1]) # segments.append(segment) # return segments which might include code, classes, or functions. Output only the next line.
'end': match_end,
Using the snippet: <|code_start|> try: identity = hsp.identities * 100.0 / float(hsp_length) except TypeError: identity = None match_parts.append({'subject_start': subject_start, 'subject_end': subject_end, 'subject_strand': subject_strand, 'query_start': query_start, 'query_end': query_end, 'query_strand': query_strand, 'scores': {'similarity': similarity, 'expect': expect, 'identity': identity} }) # It takes the first loc and the last loc of the hsp to # determine hit start and end if match_start is None or query_start < match_start: match_start = query_start if match_end is None or query_end > match_end: match_end = query_end if (match_subject_start is None or subject_start < match_subject_start): match_subject_start = subject_start if (match_subject_end is None or subject_end > match_subject_end): match_subject_end = subject_end matches.append({ 'subject': subject, 'start': match_start, 'end': match_end, <|code_end|> , determine the next line of code. You have imports: import itertools import copy import os from math import log10 from crumbs.utils.optional_modules import NCBIXML from crumbs.utils.tags import SUBJECT, QUERY, ELONGATED from crumbs.utils.segments_utils import merge_overlaping_segments and context (class names, function names, or code) available: # Path: crumbs/utils/optional_modules.py # NCBIXML = create_fake_class(MSG + BIO) # # Path: crumbs/utils/tags.py # SUBJECT = 'subject' # # QUERY = 'query' # # ELONGATED = 'elongated' # # Path: crumbs/utils/segments_utils.py # def merge_overlaping_segments(segments, merge_segments_closer=1): # '''Given a list of segments it returns the overlapped segments. # # segments 1 ------- -----> ----------- # segments 2 ------ # returns ----------- ------ ----------- # merge_segments_closer is an integer. Segments closer than the given # number of residues will be merged. # ''' # # # we collect all start and ends # limits = [] # for segment in segments: # start = segment[0] # end = segment[1] # if start > end: # a reversed item # start, end = end, start # limit_1 = (START, start) # limit_2 = (END, end) # limits.append(limit_1) # limits.append(limit_2) # # # sort by secondary key: start before end # limits.sort(key=itemgetter(0)) # # sort by location (primary key) # limits.sort(key=itemgetter(1)) # # # merge the ends and start that differ in only one base # filtered_limits = [] # previous_limit = None # for limit in limits: # if previous_limit is None: # previous_limit = limit # continue # if (previous_limit[0] == END and limit[0] == START and # previous_limit[1] >= limit[1] - merge_segments_closer): # # These limits cancelled each other # previous_limit = None # continue # filtered_limits.append(previous_limit) # previous_limit = limit # else: # filtered_limits.append(limit) # limits = filtered_limits # # # now we create the merged hsps # starts = 0 # segments = [] # for limit in limits: # if limit[0] == START: # starts += 1 # if starts == 1: # segment_start = limit[1] # elif limit[0] == END: # starts -= 1 # if starts == 0: # segment = (segment_start, limit[1]) # segments.append(segment) # return segments . Output only the next line.
'subject_start': match_subject_start,
Predict the next line for this snippet: <|code_start|> subject_strand = _strand_transform(subject_strand) score = int(score) similarity = float(similarity) # For each line , It creates a match part dict match_part = {} match_part['query_start'] = query_start match_part['query_end'] = query_end match_part['query_strand'] = query_strand match_part['subject_start'] = subject_start match_part['subject_end'] = subject_end match_part['subject_strand'] = subject_strand match_part['scores'] = {'score': score, 'similarity': similarity} # Check if the match is already added to the struct. A match is # defined by a list of part matches between a query and a subject match_num = _match_num_if_exists_in_struc(subject_name, struct_dict) if match_num is not None: match = struct_dict['matches'][match_num] if match['start'] > query_start: match['start'] = query_start if match['end'] < query_end: match['end'] = query_end if match['scores']['score'] < score: match['scores']['score'] = score match['match_parts'].append(match_part) else: match = {} match['subject'] = {'name': subject_name, 'length': int(subject_length)} <|code_end|> with the help of current file imports: import itertools import copy import os from math import log10 from crumbs.utils.optional_modules import NCBIXML from crumbs.utils.tags import SUBJECT, QUERY, ELONGATED from crumbs.utils.segments_utils import merge_overlaping_segments and context from other files: # Path: crumbs/utils/optional_modules.py # NCBIXML = create_fake_class(MSG + BIO) # # Path: crumbs/utils/tags.py # SUBJECT = 'subject' # # QUERY = 'query' # # ELONGATED = 'elongated' # # Path: crumbs/utils/segments_utils.py # def merge_overlaping_segments(segments, merge_segments_closer=1): # '''Given a list of segments it returns the overlapped segments. # # segments 1 ------- -----> ----------- # segments 2 ------ # returns ----------- ------ ----------- # merge_segments_closer is an integer. Segments closer than the given # number of residues will be merged. # ''' # # # we collect all start and ends # limits = [] # for segment in segments: # start = segment[0] # end = segment[1] # if start > end: # a reversed item # start, end = end, start # limit_1 = (START, start) # limit_2 = (END, end) # limits.append(limit_1) # limits.append(limit_2) # # # sort by secondary key: start before end # limits.sort(key=itemgetter(0)) # # sort by location (primary key) # limits.sort(key=itemgetter(1)) # # # merge the ends and start that differ in only one base # filtered_limits = [] # previous_limit = None # for limit in limits: # if previous_limit is None: # previous_limit = limit # continue # if (previous_limit[0] == END and limit[0] == START and # previous_limit[1] >= limit[1] - merge_segments_closer): # # These limits cancelled each other # previous_limit = None # continue # filtered_limits.append(previous_limit) # previous_limit = limit # else: # filtered_limits.append(limit) # limits = filtered_limits # # # now we create the merged hsps # starts = 0 # segments = [] # for limit in limits: # if limit[0] == START: # starts += 1 # if starts == 1: # segment_start = limit[1] # elif limit[0] == END: # starts -= 1 # if starts == 0: # segment = (segment_start, limit[1]) # segments.append(segment) # return segments , which may contain function names, class names, or code. Output only the next line.
match['start'] = query_start
Based on the snippet: <|code_start|> 'subject_end': match_subject_end, 'scores': {'expect': match_parts[0]['scores']['expect']}, 'match_parts': match_parts}) result = {'query': query, 'matches': matches} return result def _get_blast_metadata(self): 'It gets blast parser version' tell_ = self._blast_file.tell() version = None db_name = None plus = False for line in self._blast_file: line = line.strip() if line.startswith('<BlastOutput_version>'): version = line.split('>')[1].split('<')[0].split()[1] if line.startswith('<BlastOutput_db>'): db_name = line.split('>')[1].split('<')[0] db_name = os.path.basename(db_name) if version is not None and db_name is not None: break if version and '+' in version: plus = True version = version[:-1] self._blast_file.seek(tell_) return {'version': version, 'plus': plus, 'db_name': db_name} def next(self): <|code_end|> , predict the immediate next line with the help of imports: import itertools import copy import os from math import log10 from crumbs.utils.optional_modules import NCBIXML from crumbs.utils.tags import SUBJECT, QUERY, ELONGATED from crumbs.utils.segments_utils import merge_overlaping_segments and context (classes, functions, sometimes code) from other files: # Path: crumbs/utils/optional_modules.py # NCBIXML = create_fake_class(MSG + BIO) # # Path: crumbs/utils/tags.py # SUBJECT = 'subject' # # QUERY = 'query' # # ELONGATED = 'elongated' # # Path: crumbs/utils/segments_utils.py # def merge_overlaping_segments(segments, merge_segments_closer=1): # '''Given a list of segments it returns the overlapped segments. # # segments 1 ------- -----> ----------- # segments 2 ------ # returns ----------- ------ ----------- # merge_segments_closer is an integer. Segments closer than the given # number of residues will be merged. # ''' # # # we collect all start and ends # limits = [] # for segment in segments: # start = segment[0] # end = segment[1] # if start > end: # a reversed item # start, end = end, start # limit_1 = (START, start) # limit_2 = (END, end) # limits.append(limit_1) # limits.append(limit_2) # # # sort by secondary key: start before end # limits.sort(key=itemgetter(0)) # # sort by location (primary key) # limits.sort(key=itemgetter(1)) # # # merge the ends and start that differ in only one base # filtered_limits = [] # previous_limit = None # for limit in limits: # if previous_limit is None: # previous_limit = limit # continue # if (previous_limit[0] == END and limit[0] == START and # previous_limit[1] >= limit[1] - merge_segments_closer): # # These limits cancelled each other # previous_limit = None # continue # filtered_limits.append(previous_limit) # previous_limit = limit # else: # filtered_limits.append(limit) # limits = filtered_limits # # # now we create the merged hsps # starts = 0 # segments = [] # for limit in limits: # if limit[0] == START: # starts += 1 # if starts == 1: # segment_start = limit[1] # elif limit[0] == END: # starts -= 1 # if starts == 0: # segment = (segment_start, limit[1]) # segments.append(segment) # return segments . Output only the next line.
'It returns the next blast result'
Given the code snippet: <|code_start|> # TODO - Refactor this and the __init__ method to reduce code # duplication? handle = self._handle handle.seek(offset) line = handle.readline() data = line at_char = _as_bytes("@") plus_char = _as_bytes("+") if line[0:1] != at_char: raise ValueError("Problem with FASTQ @ line:\n%s" % repr(line)) # Find the seq line(s) seq_len = 0 while line: line = handle.readline() data += line if line.startswith(plus_char): break seq_len += len(line.strip()) if not line: raise ValueError("Premature end of file in seq section") assert line[0:1] == plus_char # Find the qual line(s) qual_len = 0 while line: if seq_len == qual_len: # Should be end of record... pos = handle.tell() line = handle.readline() if line and line[0:1] != at_char: ValueError("Problem with line %s" % repr(line)) <|code_end|> , generate the next line using the imports in this file: from collections import UserDict as _dict_base from UserDict import DictMixin as _dict_base from crumbs.utils.optional_modules import (_bytes_to_string, _as_bytes, SeqFileRandomAccess, Alphabet, AlphabetEncoder, _FormatToRandomAccess) and context (functions, classes, or occasionally code) from other files: # Path: crumbs/utils/optional_modules.py # MSG = 'A python package to run this executable is required,' # BIO = 'biopython' # BIO_BGZF = 'biopython with Bgzf support' # NCBIXML = create_fake_class(MSG + BIO) # NCBIWWW = create_fake_class(MSG + BIO) # def create_fake_class(msg): # def __init__(self, *args, **kwargs): # def create_fake_funct(msg): # def FakeRequiredfunct(*args, **kwargs): # class FakePythonRequiredClass(object): . Output only the next line.
break
Predict the next line after this snippet: <|code_start|> string.""" # TODO - Refactor this and the __init__ method to reduce code # duplication? handle = self._handle handle.seek(offset) line = handle.readline() data = line at_char = _as_bytes("@") plus_char = _as_bytes("+") if line[0:1] != at_char: raise ValueError("Problem with FASTQ @ line:\n%s" % repr(line)) # Find the seq line(s) seq_len = 0 while line: line = handle.readline() data += line if line.startswith(plus_char): break seq_len += len(line.strip()) if not line: raise ValueError("Premature end of file in seq section") assert line[0:1] == plus_char # Find the qual line(s) qual_len = 0 while line: if seq_len == qual_len: # Should be end of record... pos = handle.tell() line = handle.readline() if line and line[0:1] != at_char: <|code_end|> using the current file's imports: from collections import UserDict as _dict_base from UserDict import DictMixin as _dict_base from crumbs.utils.optional_modules import (_bytes_to_string, _as_bytes, SeqFileRandomAccess, Alphabet, AlphabetEncoder, _FormatToRandomAccess) and any relevant context from other files: # Path: crumbs/utils/optional_modules.py # MSG = 'A python package to run this executable is required,' # BIO = 'biopython' # BIO_BGZF = 'biopython with Bgzf support' # NCBIXML = create_fake_class(MSG + BIO) # NCBIWWW = create_fake_class(MSG + BIO) # def create_fake_class(msg): # def __init__(self, *args, **kwargs): # def create_fake_funct(msg): # def FakeRequiredfunct(*args, **kwargs): # class FakePythonRequiredClass(object): . Output only the next line.
ValueError("Problem with line %s" % repr(line))
Given snippet: <|code_start|> ValueError("Problem with line %s" % repr(line)) break else: line = handle.readline() qual_len += len(line.strip()) length += len(line) if seq_len != qual_len: raise ValueError("Problem with quality section") yield _bytes_to_string(id), start_offset, length start_offset = end_offset # print "EOF" def get_raw(self, offset): """Similar to the get method, but returns the record as a raw string.""" # TODO - Refactor this and the __init__ method to reduce code # duplication? handle = self._handle handle.seek(offset) line = handle.readline() data = line at_char = _as_bytes("@") plus_char = _as_bytes("+") if line[0:1] != at_char: raise ValueError("Problem with FASTQ @ line:\n%s" % repr(line)) # Find the seq line(s) seq_len = 0 while line: line = handle.readline() data += line <|code_end|> , continue by predicting the next line. Consider current file imports: from collections import UserDict as _dict_base from UserDict import DictMixin as _dict_base from crumbs.utils.optional_modules import (_bytes_to_string, _as_bytes, SeqFileRandomAccess, Alphabet, AlphabetEncoder, _FormatToRandomAccess) and context: # Path: crumbs/utils/optional_modules.py # MSG = 'A python package to run this executable is required,' # BIO = 'biopython' # BIO_BGZF = 'biopython with Bgzf support' # NCBIXML = create_fake_class(MSG + BIO) # NCBIWWW = create_fake_class(MSG + BIO) # def create_fake_class(msg): # def __init__(self, *args, **kwargs): # def create_fake_funct(msg): # def FakeRequiredfunct(*args, **kwargs): # class FakePythonRequiredClass(object): which might include code, classes, or functions. Output only the next line.
if line.startswith(plus_char):
Based on the snippet: <|code_start|> if line and line[0:1] != at_char: ValueError("Problem with line %s" % repr(line)) break else: line = handle.readline() qual_len += len(line.strip()) length += len(line) if seq_len != qual_len: raise ValueError("Problem with quality section") yield _bytes_to_string(id), start_offset, length start_offset = end_offset # print "EOF" def get_raw(self, offset): """Similar to the get method, but returns the record as a raw string.""" # TODO - Refactor this and the __init__ method to reduce code # duplication? handle = self._handle handle.seek(offset) line = handle.readline() data = line at_char = _as_bytes("@") plus_char = _as_bytes("+") if line[0:1] != at_char: raise ValueError("Problem with FASTQ @ line:\n%s" % repr(line)) # Find the seq line(s) seq_len = 0 while line: line = handle.readline() <|code_end|> , predict the immediate next line with the help of imports: from collections import UserDict as _dict_base from UserDict import DictMixin as _dict_base from crumbs.utils.optional_modules import (_bytes_to_string, _as_bytes, SeqFileRandomAccess, Alphabet, AlphabetEncoder, _FormatToRandomAccess) and context (classes, functions, sometimes code) from other files: # Path: crumbs/utils/optional_modules.py # MSG = 'A python package to run this executable is required,' # BIO = 'biopython' # BIO_BGZF = 'biopython with Bgzf support' # NCBIXML = create_fake_class(MSG + BIO) # NCBIWWW = create_fake_class(MSG + BIO) # def create_fake_class(msg): # def __init__(self, *args, **kwargs): # def create_fake_funct(msg): # def FakeRequiredfunct(*args, **kwargs): # class FakePythonRequiredClass(object): . Output only the next line.
data += line
Using the snippet: <|code_start|> while line: if seq_len == qual_len: # Should be end of record... end_offset = handle.tell() line = handle.readline() if line and line[0:1] != at_char: ValueError("Problem with line %s" % repr(line)) break else: line = handle.readline() qual_len += len(line.strip()) length += len(line) if seq_len != qual_len: raise ValueError("Problem with quality section") yield _bytes_to_string(id), start_offset, length start_offset = end_offset # print "EOF" def get_raw(self, offset): """Similar to the get method, but returns the record as a raw string.""" # TODO - Refactor this and the __init__ method to reduce code # duplication? handle = self._handle handle.seek(offset) line = handle.readline() data = line at_char = _as_bytes("@") plus_char = _as_bytes("+") if line[0:1] != at_char: <|code_end|> , determine the next line of code. You have imports: from collections import UserDict as _dict_base from UserDict import DictMixin as _dict_base from crumbs.utils.optional_modules import (_bytes_to_string, _as_bytes, SeqFileRandomAccess, Alphabet, AlphabetEncoder, _FormatToRandomAccess) and context (class names, function names, or code) available: # Path: crumbs/utils/optional_modules.py # MSG = 'A python package to run this executable is required,' # BIO = 'biopython' # BIO_BGZF = 'biopython with Bgzf support' # NCBIXML = create_fake_class(MSG + BIO) # NCBIWWW = create_fake_class(MSG + BIO) # def create_fake_class(msg): # def __init__(self, *args, **kwargs): # def create_fake_funct(msg): # def FakeRequiredfunct(*args, **kwargs): # class FakePythonRequiredClass(object): . Output only the next line.
raise ValueError("Problem with FASTQ @ line:\n%s" % repr(line))
Predict the next line for this snippet: <|code_start|> # duplication? handle = self._handle handle.seek(offset) line = handle.readline() data = line at_char = _as_bytes("@") plus_char = _as_bytes("+") if line[0:1] != at_char: raise ValueError("Problem with FASTQ @ line:\n%s" % repr(line)) # Find the seq line(s) seq_len = 0 while line: line = handle.readline() data += line if line.startswith(plus_char): break seq_len += len(line.strip()) if not line: raise ValueError("Premature end of file in seq section") assert line[0:1] == plus_char # Find the qual line(s) qual_len = 0 while line: if seq_len == qual_len: # Should be end of record... pos = handle.tell() line = handle.readline() if line and line[0:1] != at_char: ValueError("Problem with line %s" % repr(line)) break <|code_end|> with the help of current file imports: from collections import UserDict as _dict_base from UserDict import DictMixin as _dict_base from crumbs.utils.optional_modules import (_bytes_to_string, _as_bytes, SeqFileRandomAccess, Alphabet, AlphabetEncoder, _FormatToRandomAccess) and context from other files: # Path: crumbs/utils/optional_modules.py # MSG = 'A python package to run this executable is required,' # BIO = 'biopython' # BIO_BGZF = 'biopython with Bgzf support' # NCBIXML = create_fake_class(MSG + BIO) # NCBIWWW = create_fake_class(MSG + BIO) # def create_fake_class(msg): # def __init__(self, *args, **kwargs): # def create_fake_funct(msg): # def FakeRequiredfunct(*args, **kwargs): # class FakePythonRequiredClass(object): , which may contain function names, class names, or code. Output only the next line.
else:
Given the code snippet: <|code_start|> SAM = '''@HD\tVN:1.3\tSO:coordinate @SQ\tSN:ref\tLN:45 r001\t0\tref\t7\t30\t8M2I4M1D3M\t=\t37\t39\tTAAGATAAAGGATACTG\t* r002\t0\tref\t9\t30\t3S6M1P1I4M\t*\t0\t0\tAAAAGATAAGGATA\t* <|code_end|> , generate the next line using the imports in this file: import unittest import pysam from tempfile import NamedTemporaryFile from crumbs.bam.coord_transforms import ReadRefCoord and context (functions, classes, or occasionally code) from other files: # Path: crumbs/bam/coord_transforms.py # class ReadRefCoord(object): # def __init__(self, alig_read, sam, hard_clip_as_soft=False): # self._alig_read = alig_read # self._sam = sam # self.hard_clip_as_soft = hard_clip_as_soft # self._blocks = None # self._read_len = None # self._last_position = None # # @property # def read_len(self): # if self._read_len is None: # self.blocks # return self._read_len # # @property # def blocks(self): # alig_read = self._alig_read # if self._blocks is not None: # return self._block # ref_start = alig_read.reference_start # # cigar_tuples = alig_read.cigartuples # is_fwd = not(alig_read.is_reverse) # if not is_fwd: # cigar_tuples = reversed(cigar_tuples) # # read_pos = 0 # if is reversed this is not true, but we fixed later # read_len = 0 # ref_pos = ref_start # blocks = [] # for operation, length in alig_read.cigartuples: # blk_start = ref_pos, read_pos # if operation == 5: # if self.hard_clip_as_soft: # operation = 4 # if like a soft clip # else: # continue # if operation in (0, 7, 8): # match # read_len += length # ref_pos += length # if is_fwd: # read_pos += length # else: # read_pos -= length # elif operation == 1: # insertion in read # read_len += length # if is_fwd: # read_pos += length # else: # read_pos -= length # elif operation == 2 or operation == 3: # deletion in read # ref_pos += length # elif operation == 4: # soft clip # # This is not a block to be returned because it is not aligned # read_len += length # if is_fwd: # read_pos += length # else: # read_pos -= length # elif operation == 6: # continue # blk_end = ref_pos - 1, read_pos - 1 # if operation != 4: # ref_start = blk_start[0] # ref_end = blk_end[0] # read_start = blk_start[1] # read_end = blk_end[1] # if operation in (2, 3): # read_start, read_end = None, None # elif operation == 1: # ref_start, ref_end = None, None # block = Block(ref_start, ref_end, read_start, read_end) # blocks.append(block) # # if not is_fwd: # rev_blocks = [] # for blk in blocks: # if blk.read_stop is not None and blk.read_start is not None: # blk_read_start = blk.read_start + read_len - 1 # blk_read_end = blk.read_stop + read_len + 1 # else: # blk_read_start = None # blk_read_end = None # block = Block(blk.ref_start, blk.ref_stop, blk_read_start, # blk_read_end) # rev_blocks.append(block) # blocks = rev_blocks # self._block = blocks # self._read_len = read_len # return blocks # # def get_read_pos(self, ref_pos): # if (self._last_position is not None and # self._last_position[0] == ref_pos): # return self._last_position[1] # alig_read = self._alig_read # sam = self._sam # chrom = sam.getrname(alig_read.reference_id) # if chrom != ref_pos[0]: # msg = 'The aligned read is not aligned to the given chrom: ' # msg += chrom # raise ValueError(msg) # ref_pos = ref_pos[1] # # blocks = self.blocks # # block_with_ref_pos = None # for block in blocks: # if block.ref_start <= ref_pos <= block.ref_stop: # block_with_ref_pos = block # break # if block_with_ref_pos is None: # read_pos = None # else: # read_start = block_with_ref_pos.read_start # read_stop = block_with_ref_pos.read_stop # # if read_start is None or read_stop is None: # read_pos = None # else: # ref_start = block_with_ref_pos.ref_start # ref_stop = block_with_ref_pos.ref_stop # # if alig_read.is_reverse: # read_pos = read_start - (ref_pos - ref_start) # else: # read_pos = read_stop - (ref_stop - ref_pos) # # self._last_position = ref_pos, read_pos # return read_pos # # def get_read_pos_counting_from_end(self, ref_pos): # if self._last_position is None: # read_pos = self.get_read_pos(ref_pos) # else: # read_pos = self._last_position[1] # read_len = self.read_len # if read_pos is not None: # return read_pos - read_len . Output only the next line.
r003\t0\tref\t9\t30\t5H6M\t*\t0\t0\tAGCTAA\t*\tNM:i:1
Predict the next line after this snippet: <|code_start|> # seq_crumbs is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with seq_crumbs. If not, see <http://www.gnu.org/licenses/>. class _ListLikeDb(object): def __init__(self): self._db_fhand = NamedTemporaryFile(suffix='.sqlite.db') self._conn = sqlite3.connect(self._db_fhand.name) create = 'CREATE TABLE items(idx INTEGER PRIMARY KEY, item BLOB);' self._conn.execute(create) self._conn.commit() self._last_item_returned = None def __len__(self): conn = self._conn cursor = conn.execute('SELECT COUNT(*) FROM items;') return cursor.fetchone()[0] def append(self, item): conn = self._conn insert = "INSERT INTO items(item) VALUES (?)" conn.execute(insert, (pickle.dumps(item),)) <|code_end|> using the current file's imports: import random import cPickle as pickle import sqlite3 from itertools import izip_longest, islice, tee, izip from tempfile import NamedTemporaryFile from collections import namedtuple from crumbs.utils.optional_modules import merge_sorted from crumbs.exceptions import SampleSizeError and any relevant context from other files: # Path: crumbs/utils/optional_modules.py # MSG = 'A python package to run this executable is required,' # BIO = 'biopython' # BIO_BGZF = 'biopython with Bgzf support' # NCBIXML = create_fake_class(MSG + BIO) # NCBIWWW = create_fake_class(MSG + BIO) # def create_fake_class(msg): # def __init__(self, *args, **kwargs): # def create_fake_funct(msg): # def FakeRequiredfunct(*args, **kwargs): # class FakePythonRequiredClass(object): # # Path: crumbs/exceptions.py # class SampleSizeError(Exception): # 'The asked sample size is bigger than the population' # pass . Output only the next line.
conn.commit()
Using the snippet: <|code_start|> self._conn = sqlite3.connect(self._db_fhand.name) create = 'CREATE TABLE items(idx INTEGER PRIMARY KEY, item BLOB);' self._conn.execute(create) self._conn.commit() self._last_item_returned = None def __len__(self): conn = self._conn cursor = conn.execute('SELECT COUNT(*) FROM items;') return cursor.fetchone()[0] def append(self, item): conn = self._conn insert = "INSERT INTO items(item) VALUES (?)" conn.execute(insert, (pickle.dumps(item),)) conn.commit() def __setitem__(self, key, item): update = "UPDATE items SET item=? WHERE idx=?" conn = self._conn conn.execute(update, (pickle.dumps(item), key)) conn.commit() def __iter__(self): return self def next(self): if self._last_item_returned is None: idx = 1 else: <|code_end|> , determine the next line of code. You have imports: import random import cPickle as pickle import sqlite3 from itertools import izip_longest, islice, tee, izip from tempfile import NamedTemporaryFile from collections import namedtuple from crumbs.utils.optional_modules import merge_sorted from crumbs.exceptions import SampleSizeError and context (class names, function names, or code) available: # Path: crumbs/utils/optional_modules.py # MSG = 'A python package to run this executable is required,' # BIO = 'biopython' # BIO_BGZF = 'biopython with Bgzf support' # NCBIXML = create_fake_class(MSG + BIO) # NCBIWWW = create_fake_class(MSG + BIO) # def create_fake_class(msg): # def __init__(self, *args, **kwargs): # def create_fake_funct(msg): # def FakeRequiredfunct(*args, **kwargs): # class FakePythonRequiredClass(object): # # Path: crumbs/exceptions.py # class SampleSizeError(Exception): # 'The asked sample size is bigger than the population' # pass . Output only the next line.
idx = self._last_item_returned + 1
Next line prediction: <|code_start|> non_A_alleles = list(alleles_snp1.difference(allele_A)) non_B_alleles = list(alleles_snp2.difference(allele_B)) if not non_A_alleles or not non_B_alleles: return None allele_a = non_A_alleles[0] allele_b = non_B_alleles[0] count_AB = haplo_count.get(haplo_AB, 0) count_Ab = haplo_count.get((allele_A, allele_b), 0) count_aB = haplo_count.get((allele_a, allele_B), 0) count_ab = haplo_count.get((allele_a, allele_b), 0) counts = HaploCount(count_AB, count_Ab, count_aB, count_ab) if return_alleles: alleles = Alleles(allele_A, allele_B, allele_a, allele_b) return counts, alleles else: return counts def _calc_recomb_rate(calls1, calls2, pop_type): haplo_count = _count_biallelic_haplotypes(calls1, calls2) if haplo_count is None: return None recomb_haplos = haplo_count.aB + haplo_count.Ab tot_haplos = sum(haplo_count) if pop_type == 'ril_self': <|code_end|> . Use current file imports: (from itertools import chain from collections import Counter, namedtuple from scipy.stats import fisher_exact as scipy_fisher from vcf import Reader as pyvcfReader from crumbs.vcf.statistics import choose_samples from crumbs.iterutils import RandomAccessIterator from crumbs.plot import build_histogram, draw_density_plot from os.path import join as pjoin from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure from scipy.stats import gaussian_kde import numpy) and context including class names, function names, or small code snippets from other files: # Path: crumbs/vcf/statistics.py # def choose_samples(record, sample_names): # if sample_names is None: # chosen_samples = record.samples # else: # filter_by_name = lambda x: True if x.sample in sample_names else False # chosen_samples = filter(filter_by_name, record.samples, ) # return chosen_samples # # Path: crumbs/iterutils.py # class RandomAccessIterator(object): # def __init__(self, iterable, rnd_access_win): # self._stream = iterable # if not rnd_access_win % 2: # msg = 'rnd_access_win should be odd' # raise ValueError(msg) # self._rnd_access_win = rnd_access_win # self._buff = [] # self._curr_item_in_buff = None # self._buffer_pos = 0 # self._stream_consumed = False # self._fill_buffer() # # def _fill_buffer(self): # half_win = (self._rnd_access_win - 1) // 2 # self._buff = list(islice(self._stream, half_win)) # if len(self._buff) < half_win: # self._stream_consumed = True # # def __iter__(self): # return self # # def next(self): # in_buffer = self._buff # try: # stream_next = self._stream.next() # except StopIteration: # self._stream_consumed = True # # if not self._stream_consumed: # in_buffer.append(stream_next) # # if self._curr_item_in_buff is None: # self._curr_item_in_buff = 0 # else: # self._curr_item_in_buff += 1 # # try: # item_to_yield = in_buffer[self._curr_item_in_buff] # except IndexError: # raise StopIteration # # if len(in_buffer) > self._rnd_access_win: # in_buffer.pop(0) # self._curr_item_in_buff -= 1 # self._buffer_pos += 1 # # return item_to_yield # # def _getitem(self, start): # start -= self._buffer_pos # if start < 0: # raise IndexError('Negative indexes not supported') # return self._buff[start] # # def __getitem__(self, index): # if isinstance(index, int): # start = index # return self._getitem(start) # else: # start = index.start # stop = index.stop # step = index.step # if start is None: # start = 0 # # if start < 0 or stop < 0: # raise IndexError('Negative indexes not supported') # # buff_pos = self._buffer_pos # start -= buff_pos # stop -= buff_pos # # buff = self._buff # if start < 0: # raise IndexError('Index outside buffered window') # if (not self._stream_consumed and # (stop is None or stop > len(buff))): # raise IndexError('Index outside buffered window') # # return buff[start:stop:step] . Output only the next line.
recomb = recomb_haplos * (tot_haplos - recomb_haplos - 1)
Predict the next line for this snippet: <|code_start|> p_val=DEF_P_VAL, bonferroni=True, snv_win=DEF_SNV_WIN, min_phys_dist=MIN_PHYS_DIST, log_fhand=None): if not snv_win % 2: msg = 'The window should have an odd number of snvs' raise ValueError(msg) half_win = (snv_win - 1) // 2 if bonferroni: p_val /= (snv_win - 1) snvs = RandomAccessIterator(snvs, rnd_access_win=snv_win) linked_snvs = set() total_snvs = 0 passed_snvs = 0 prev_chrom = None stats_cache = _LDStatsCache() for snv_i, snv in enumerate(snvs): total_snvs += 1 if snv_i in linked_snvs: yield snv passed_snvs += 1 linked_snvs.remove(snv_i) continue linked = None win_start = snv_i - half_win this_chrom = snv.chrom if prev_chrom is None: prev_chrom = this_chrom if prev_chrom != this_chrom: <|code_end|> with the help of current file imports: from itertools import chain from collections import Counter, namedtuple from scipy.stats import fisher_exact as scipy_fisher from vcf import Reader as pyvcfReader from crumbs.vcf.statistics import choose_samples from crumbs.iterutils import RandomAccessIterator from crumbs.plot import build_histogram, draw_density_plot from os.path import join as pjoin from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure from scipy.stats import gaussian_kde import numpy and context from other files: # Path: crumbs/vcf/statistics.py # def choose_samples(record, sample_names): # if sample_names is None: # chosen_samples = record.samples # else: # filter_by_name = lambda x: True if x.sample in sample_names else False # chosen_samples = filter(filter_by_name, record.samples, ) # return chosen_samples # # Path: crumbs/iterutils.py # class RandomAccessIterator(object): # def __init__(self, iterable, rnd_access_win): # self._stream = iterable # if not rnd_access_win % 2: # msg = 'rnd_access_win should be odd' # raise ValueError(msg) # self._rnd_access_win = rnd_access_win # self._buff = [] # self._curr_item_in_buff = None # self._buffer_pos = 0 # self._stream_consumed = False # self._fill_buffer() # # def _fill_buffer(self): # half_win = (self._rnd_access_win - 1) // 2 # self._buff = list(islice(self._stream, half_win)) # if len(self._buff) < half_win: # self._stream_consumed = True # # def __iter__(self): # return self # # def next(self): # in_buffer = self._buff # try: # stream_next = self._stream.next() # except StopIteration: # self._stream_consumed = True # # if not self._stream_consumed: # in_buffer.append(stream_next) # # if self._curr_item_in_buff is None: # self._curr_item_in_buff = 0 # else: # self._curr_item_in_buff += 1 # # try: # item_to_yield = in_buffer[self._curr_item_in_buff] # except IndexError: # raise StopIteration # # if len(in_buffer) > self._rnd_access_win: # in_buffer.pop(0) # self._curr_item_in_buff -= 1 # self._buffer_pos += 1 # # return item_to_yield # # def _getitem(self, start): # start -= self._buffer_pos # if start < 0: # raise IndexError('Negative indexes not supported') # return self._buff[start] # # def __getitem__(self, index): # if isinstance(index, int): # start = index # return self._getitem(start) # else: # start = index.start # stop = index.stop # step = index.step # if start is None: # start = 0 # # if start < 0 or stop < 0: # raise IndexError('Negative indexes not supported') # # buff_pos = self._buffer_pos # start -= buff_pos # stop -= buff_pos # # buff = self._buff # if start < 0: # raise IndexError('Index outside buffered window') # if (not self._stream_consumed and # (stop is None or stop > len(buff))): # raise IndexError('Index outside buffered window') # # return buff[start:stop:step] , which may contain function names, class names, or code. Output only the next line.
stats_cache = _LDStatsCache()
Predict the next line for this snippet: <|code_start|> # seq_crumbs is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with seq_crumbs. If not, see <http://www.gnu.org/licenses/>. # pylint: disable=R0201 # pylint: disable=R0904 class SegmentsTest(unittest.TestCase): 'It tests the segments functions' @staticmethod def test_get_longest_section(): 'It gets the longest section from a list of sections' segments = [(0, 3), (10, 34)] assert (10, 34) == get_longest_segment(segments) segments = [(0, 3), (10, 13)] segment = get_longest_segment(segments) assert segment == (0, 3) or segment == (10, 13) @staticmethod <|code_end|> with the help of current file imports: import unittest from crumbs.utils.segments_utils import (get_longest_segment, get_all_segments, get_complementary_segments, get_longest_complementary_segment) and context from other files: # Path: crumbs/utils/segments_utils.py # def get_longest_segment(segments): # 'It returns the longest segment' # longest = None # longest_size = None # for segment in segments: # size = segment[1] - segment[0] # if longest is None: # longest = [segment] # longest_size = size # elif size > longest_size: # longest = [segment] # longest_size = size # elif size == longest_size: # longest.append(segment) # # if longest is None: # return None # elif len(longest) == 1: # return longest[0] # else: # return random.choice(longest) # # def get_all_segments(segments, seq_len): # '''Given a set of some non overlapping regions it returns all regions. # # input: --- ---- ---- # output: ---+----+++++++---- # # ''' # segments_ = copy.deepcopy(segments) # if not segments_: # return [((0, seq_len - 1), False)] # # all_segments = [] # # If the first segment doesn't start at zero we create a new one # if segments_[0][0] == 0: # start = segments_[0][1] + 1 # all_segments.append((segments_.pop(0), True)) # else: # start = 0 # # for loc in segments_: # all_segments.append(((start, loc[0] - 1), False)) # all_segments.append((loc, True)) # start = loc[1] + 1 # else: # # if the last segment does not ends at the end of the sequence we add # # an extra one # end = seq_len - 1 # if start <= end: # all_segments.append(((start, end), False)) # return all_segments # # def get_complementary_segments(segments, seq_len): # 'Given a set of regions in a seq it returns the complementary ones' # non_matched = [] # for segment in get_all_segments(segments, seq_len): # if not segment[1]: # non_matched.append(segment[0]) # return non_matched # # def get_longest_complementary_segment(segments, seq_len): # 'Given a seq and the locations it returns the longest region not covered' # # segments = merge_overlaping_segments(segments) # # # we want the non-matched locations # segments = get_complementary_segments(segments, seq_len) # # # now we return the longest one # return get_longest_segment(segments) , which may contain function names, class names, or code. Output only the next line.
def test_get_all_segments():
Next line prediction: <|code_start|> assert segment == (0, 3) or segment == (10, 13) @staticmethod def test_get_all_segments(): 'Give a list of discontinious segments we get all segments' segments = get_all_segments([(0, 10), (15, 20)], 30) assert segments == [((0, 10), True), ((11, 14), False), ((15, 20), True), ((21, 29), False)] segments = get_all_segments([(15, 20)], 30) assert segments == [((0, 14), False), ((15, 20), True), ((21, 29), False)] segments = get_all_segments([(15, 29)], 30) assert segments == [((0, 14), False), ((15, 29), True)] @staticmethod def test_non_matched(): 'Given a list of segments we get the complementary matches' segments = get_complementary_segments([(0, 10), (15, 20)], 30) assert segments == [(11, 14), (21, 29)] @staticmethod def test_get_longest_complementary(): 'It test that we can get the longest complementary segment' segments = [(0, 200)] result = get_longest_complementary_segment(segments, seq_len=200) assert result is None if __name__ == '__main__': #import sys;sys.argv = ['', 'SffExtractTest.test_items_in_gff'] <|code_end|> . Use current file imports: (import unittest from crumbs.utils.segments_utils import (get_longest_segment, get_all_segments, get_complementary_segments, get_longest_complementary_segment)) and context including class names, function names, or small code snippets from other files: # Path: crumbs/utils/segments_utils.py # def get_longest_segment(segments): # 'It returns the longest segment' # longest = None # longest_size = None # for segment in segments: # size = segment[1] - segment[0] # if longest is None: # longest = [segment] # longest_size = size # elif size > longest_size: # longest = [segment] # longest_size = size # elif size == longest_size: # longest.append(segment) # # if longest is None: # return None # elif len(longest) == 1: # return longest[0] # else: # return random.choice(longest) # # def get_all_segments(segments, seq_len): # '''Given a set of some non overlapping regions it returns all regions. # # input: --- ---- ---- # output: ---+----+++++++---- # # ''' # segments_ = copy.deepcopy(segments) # if not segments_: # return [((0, seq_len - 1), False)] # # all_segments = [] # # If the first segment doesn't start at zero we create a new one # if segments_[0][0] == 0: # start = segments_[0][1] + 1 # all_segments.append((segments_.pop(0), True)) # else: # start = 0 # # for loc in segments_: # all_segments.append(((start, loc[0] - 1), False)) # all_segments.append((loc, True)) # start = loc[1] + 1 # else: # # if the last segment does not ends at the end of the sequence we add # # an extra one # end = seq_len - 1 # if start <= end: # all_segments.append(((start, end), False)) # return all_segments # # def get_complementary_segments(segments, seq_len): # 'Given a set of regions in a seq it returns the complementary ones' # non_matched = [] # for segment in get_all_segments(segments, seq_len): # if not segment[1]: # non_matched.append(segment[0]) # return non_matched # # def get_longest_complementary_segment(segments, seq_len): # 'Given a seq and the locations it returns the longest region not covered' # # segments = merge_overlaping_segments(segments) # # # we want the non-matched locations # segments = get_complementary_segments(segments, seq_len) # # # now we return the longest one # return get_longest_segment(segments) . Output only the next line.
unittest.main()
Predict the next line for this snippet: <|code_start|> class SegmentsTest(unittest.TestCase): 'It tests the segments functions' @staticmethod def test_get_longest_section(): 'It gets the longest section from a list of sections' segments = [(0, 3), (10, 34)] assert (10, 34) == get_longest_segment(segments) segments = [(0, 3), (10, 13)] segment = get_longest_segment(segments) assert segment == (0, 3) or segment == (10, 13) @staticmethod def test_get_all_segments(): 'Give a list of discontinious segments we get all segments' segments = get_all_segments([(0, 10), (15, 20)], 30) assert segments == [((0, 10), True), ((11, 14), False), ((15, 20), True), ((21, 29), False)] segments = get_all_segments([(15, 20)], 30) assert segments == [((0, 14), False), ((15, 20), True), ((21, 29), False)] segments = get_all_segments([(15, 29)], 30) assert segments == [((0, 14), False), ((15, 29), True)] @staticmethod <|code_end|> with the help of current file imports: import unittest from crumbs.utils.segments_utils import (get_longest_segment, get_all_segments, get_complementary_segments, get_longest_complementary_segment) and context from other files: # Path: crumbs/utils/segments_utils.py # def get_longest_segment(segments): # 'It returns the longest segment' # longest = None # longest_size = None # for segment in segments: # size = segment[1] - segment[0] # if longest is None: # longest = [segment] # longest_size = size # elif size > longest_size: # longest = [segment] # longest_size = size # elif size == longest_size: # longest.append(segment) # # if longest is None: # return None # elif len(longest) == 1: # return longest[0] # else: # return random.choice(longest) # # def get_all_segments(segments, seq_len): # '''Given a set of some non overlapping regions it returns all regions. # # input: --- ---- ---- # output: ---+----+++++++---- # # ''' # segments_ = copy.deepcopy(segments) # if not segments_: # return [((0, seq_len - 1), False)] # # all_segments = [] # # If the first segment doesn't start at zero we create a new one # if segments_[0][0] == 0: # start = segments_[0][1] + 1 # all_segments.append((segments_.pop(0), True)) # else: # start = 0 # # for loc in segments_: # all_segments.append(((start, loc[0] - 1), False)) # all_segments.append((loc, True)) # start = loc[1] + 1 # else: # # if the last segment does not ends at the end of the sequence we add # # an extra one # end = seq_len - 1 # if start <= end: # all_segments.append(((start, end), False)) # return all_segments # # def get_complementary_segments(segments, seq_len): # 'Given a set of regions in a seq it returns the complementary ones' # non_matched = [] # for segment in get_all_segments(segments, seq_len): # if not segment[1]: # non_matched.append(segment[0]) # return non_matched # # def get_longest_complementary_segment(segments, seq_len): # 'Given a seq and the locations it returns the longest region not covered' # # segments = merge_overlaping_segments(segments) # # # we want the non-matched locations # segments = get_complementary_segments(segments, seq_len) # # # now we return the longest one # return get_longest_segment(segments) , which may contain function names, class names, or code. Output only the next line.
def test_non_matched():
Given snippet: <|code_start|># You should have received a copy of the GNU General Public License # along with seq_crumbs. If not, see <http://www.gnu.org/licenses/>. FILETYPE = 'file' STRINGIOTYPE = 'stringio' OTHERTYPE = 'othertype' def _get_some_qual_and_lengths(fhand, force_file_as_non_seek): 'It returns the quality characters and the lengths' seqs_to_peek = get_setting('SEQS_TO_GUESS_FASTQ_VERSION') chunk_size = get_setting('CHUNK_TO_GUESS_FASTQ_VERSION') lengths = array('I') seqs_analyzed = 0 if fhand_is_seekable(fhand) and not force_file_as_non_seek: fmt_fhand = fhand chunk = fmt_fhand.read(chunk_size) fhand.seek(0) else: chunk = peek_chunk_from_file(fhand, chunk_size) fmt_fhand = cStringIO.StringIO(chunk) try: for seq in FastqGeneralIterator(fmt_fhand): qual = [ord(char) for char in seq[2]] sanger_chars = [q for q in qual if q < 64] if sanger_chars: <|code_end|> , continue by predicting the next line. Consider current file imports: import cStringIO import hashlib from array import array from crumbs.utils.optional_modules import FastqGeneralIterator from crumbs.settings import get_setting from crumbs.utils.file_utils import fhand_is_seekable, peek_chunk_from_file from crumbs.exceptions import (UnknownFormatError, UndecidedFastqVersionError, FileIsEmptyError) and context: # Path: crumbs/utils/optional_modules.py # MSG = 'A python package to run this executable is required,' # BIO = 'biopython' # BIO_BGZF = 'biopython with Bgzf support' # NCBIXML = create_fake_class(MSG + BIO) # NCBIWWW = create_fake_class(MSG + BIO) # def create_fake_class(msg): # def __init__(self, *args, **kwargs): # def create_fake_funct(msg): # def FakeRequiredfunct(*args, **kwargs): # class FakePythonRequiredClass(object): # # Path: crumbs/settings.py # def get_setting(key): # 'It returns the value for one setting' # return _settings[key] # # Path: crumbs/utils/file_utils.py # def fhand_is_seekable(fhand): # 'It returns True if the fhand is seekable' # try: # try: # # The stdin stream in some instances has seek, has no seekable # fhand.tell() # except IOError: # return False # try: # if fhand.seekable(): # return True # else: # return False # except AttributeError: # return True # except AttributeError: # return False # # def peek_chunk_from_file(fhand, chunk_size): # 'It returns the beginning of a file without moving the pointer' # if fhand_is_seekable(fhand): # fhand.seek(0) # chunk = fhand.read(chunk_size) # fhand.seek(0) # else: # chunk = fhand.peek(chunk_size) # return chunk # # Path: crumbs/exceptions.py # class UnknownFormatError(Exception): # 'Raised when the format of a sequence file cannot be guessed' # pass # # class UndecidedFastqVersionError(Exception): # 'The file is Fastq, but the version is difficult to guess' # pass # # class FileIsEmptyError(Exception): # pass which might include code, classes, or functions. Output only the next line.
fhand.seek(0)
Given the code snippet: <|code_start|># seq_crumbs is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # seq_crumbs is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with seq_crumbs. If not, see <http://www.gnu.org/licenses/>. FILETYPE = 'file' STRINGIOTYPE = 'stringio' OTHERTYPE = 'othertype' def _get_some_qual_and_lengths(fhand, force_file_as_non_seek): 'It returns the quality characters and the lengths' seqs_to_peek = get_setting('SEQS_TO_GUESS_FASTQ_VERSION') chunk_size = get_setting('CHUNK_TO_GUESS_FASTQ_VERSION') lengths = array('I') seqs_analyzed = 0 if fhand_is_seekable(fhand) and not force_file_as_non_seek: fmt_fhand = fhand chunk = fmt_fhand.read(chunk_size) <|code_end|> , generate the next line using the imports in this file: import cStringIO import hashlib from array import array from crumbs.utils.optional_modules import FastqGeneralIterator from crumbs.settings import get_setting from crumbs.utils.file_utils import fhand_is_seekable, peek_chunk_from_file from crumbs.exceptions import (UnknownFormatError, UndecidedFastqVersionError, FileIsEmptyError) and context (functions, classes, or occasionally code) from other files: # Path: crumbs/utils/optional_modules.py # MSG = 'A python package to run this executable is required,' # BIO = 'biopython' # BIO_BGZF = 'biopython with Bgzf support' # NCBIXML = create_fake_class(MSG + BIO) # NCBIWWW = create_fake_class(MSG + BIO) # def create_fake_class(msg): # def __init__(self, *args, **kwargs): # def create_fake_funct(msg): # def FakeRequiredfunct(*args, **kwargs): # class FakePythonRequiredClass(object): # # Path: crumbs/settings.py # def get_setting(key): # 'It returns the value for one setting' # return _settings[key] # # Path: crumbs/utils/file_utils.py # def fhand_is_seekable(fhand): # 'It returns True if the fhand is seekable' # try: # try: # # The stdin stream in some instances has seek, has no seekable # fhand.tell() # except IOError: # return False # try: # if fhand.seekable(): # return True # else: # return False # except AttributeError: # return True # except AttributeError: # return False # # def peek_chunk_from_file(fhand, chunk_size): # 'It returns the beginning of a file without moving the pointer' # if fhand_is_seekable(fhand): # fhand.seek(0) # chunk = fhand.read(chunk_size) # fhand.seek(0) # else: # chunk = fhand.peek(chunk_size) # return chunk # # Path: crumbs/exceptions.py # class UnknownFormatError(Exception): # 'Raised when the format of a sequence file cannot be guessed' # pass # # class UndecidedFastqVersionError(Exception): # 'The file is Fastq, but the version is difficult to guess' # pass # # class FileIsEmptyError(Exception): # pass . Output only the next line.
fhand.seek(0)
Using the snippet: <|code_start|>STRINGIOTYPE = 'stringio' OTHERTYPE = 'othertype' def _get_some_qual_and_lengths(fhand, force_file_as_non_seek): 'It returns the quality characters and the lengths' seqs_to_peek = get_setting('SEQS_TO_GUESS_FASTQ_VERSION') chunk_size = get_setting('CHUNK_TO_GUESS_FASTQ_VERSION') lengths = array('I') seqs_analyzed = 0 if fhand_is_seekable(fhand) and not force_file_as_non_seek: fmt_fhand = fhand chunk = fmt_fhand.read(chunk_size) fhand.seek(0) else: chunk = peek_chunk_from_file(fhand, chunk_size) fmt_fhand = cStringIO.StringIO(chunk) try: for seq in FastqGeneralIterator(fmt_fhand): qual = [ord(char) for char in seq[2]] sanger_chars = [q for q in qual if q < 64] if sanger_chars: fhand.seek(0) return None, True, chunk # no quals, no lengths, is_sanger lengths.append(len(qual)) seqs_analyzed += 1 if seqs_analyzed > seqs_to_peek: break <|code_end|> , determine the next line of code. You have imports: import cStringIO import hashlib from array import array from crumbs.utils.optional_modules import FastqGeneralIterator from crumbs.settings import get_setting from crumbs.utils.file_utils import fhand_is_seekable, peek_chunk_from_file from crumbs.exceptions import (UnknownFormatError, UndecidedFastqVersionError, FileIsEmptyError) and context (class names, function names, or code) available: # Path: crumbs/utils/optional_modules.py # MSG = 'A python package to run this executable is required,' # BIO = 'biopython' # BIO_BGZF = 'biopython with Bgzf support' # NCBIXML = create_fake_class(MSG + BIO) # NCBIWWW = create_fake_class(MSG + BIO) # def create_fake_class(msg): # def __init__(self, *args, **kwargs): # def create_fake_funct(msg): # def FakeRequiredfunct(*args, **kwargs): # class FakePythonRequiredClass(object): # # Path: crumbs/settings.py # def get_setting(key): # 'It returns the value for one setting' # return _settings[key] # # Path: crumbs/utils/file_utils.py # def fhand_is_seekable(fhand): # 'It returns True if the fhand is seekable' # try: # try: # # The stdin stream in some instances has seek, has no seekable # fhand.tell() # except IOError: # return False # try: # if fhand.seekable(): # return True # else: # return False # except AttributeError: # return True # except AttributeError: # return False # # def peek_chunk_from_file(fhand, chunk_size): # 'It returns the beginning of a file without moving the pointer' # if fhand_is_seekable(fhand): # fhand.seek(0) # chunk = fhand.read(chunk_size) # fhand.seek(0) # else: # chunk = fhand.peek(chunk_size) # return chunk # # Path: crumbs/exceptions.py # class UnknownFormatError(Exception): # 'Raised when the format of a sequence file cannot be guessed' # pass # # class UndecidedFastqVersionError(Exception): # 'The file is Fastq, but the version is difficult to guess' # pass # # class FileIsEmptyError(Exception): # pass . Output only the next line.
except ValueError:
Predict the next line after this snippet: <|code_start|># MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with seq_crumbs. If not, see <http://www.gnu.org/licenses/>. FILETYPE = 'file' STRINGIOTYPE = 'stringio' OTHERTYPE = 'othertype' def _get_some_qual_and_lengths(fhand, force_file_as_non_seek): 'It returns the quality characters and the lengths' seqs_to_peek = get_setting('SEQS_TO_GUESS_FASTQ_VERSION') chunk_size = get_setting('CHUNK_TO_GUESS_FASTQ_VERSION') lengths = array('I') seqs_analyzed = 0 if fhand_is_seekable(fhand) and not force_file_as_non_seek: fmt_fhand = fhand chunk = fmt_fhand.read(chunk_size) fhand.seek(0) else: chunk = peek_chunk_from_file(fhand, chunk_size) fmt_fhand = cStringIO.StringIO(chunk) try: for seq in FastqGeneralIterator(fmt_fhand): <|code_end|> using the current file's imports: import cStringIO import hashlib from array import array from crumbs.utils.optional_modules import FastqGeneralIterator from crumbs.settings import get_setting from crumbs.utils.file_utils import fhand_is_seekable, peek_chunk_from_file from crumbs.exceptions import (UnknownFormatError, UndecidedFastqVersionError, FileIsEmptyError) and any relevant context from other files: # Path: crumbs/utils/optional_modules.py # MSG = 'A python package to run this executable is required,' # BIO = 'biopython' # BIO_BGZF = 'biopython with Bgzf support' # NCBIXML = create_fake_class(MSG + BIO) # NCBIWWW = create_fake_class(MSG + BIO) # def create_fake_class(msg): # def __init__(self, *args, **kwargs): # def create_fake_funct(msg): # def FakeRequiredfunct(*args, **kwargs): # class FakePythonRequiredClass(object): # # Path: crumbs/settings.py # def get_setting(key): # 'It returns the value for one setting' # return _settings[key] # # Path: crumbs/utils/file_utils.py # def fhand_is_seekable(fhand): # 'It returns True if the fhand is seekable' # try: # try: # # The stdin stream in some instances has seek, has no seekable # fhand.tell() # except IOError: # return False # try: # if fhand.seekable(): # return True # else: # return False # except AttributeError: # return True # except AttributeError: # return False # # def peek_chunk_from_file(fhand, chunk_size): # 'It returns the beginning of a file without moving the pointer' # if fhand_is_seekable(fhand): # fhand.seek(0) # chunk = fhand.read(chunk_size) # fhand.seek(0) # else: # chunk = fhand.peek(chunk_size) # return chunk # # Path: crumbs/exceptions.py # class UnknownFormatError(Exception): # 'Raised when the format of a sequence file cannot be guessed' # pass # # class UndecidedFastqVersionError(Exception): # 'The file is Fastq, but the version is difficult to guess' # pass # # class FileIsEmptyError(Exception): # pass . Output only the next line.
qual = [ord(char) for char in seq[2]]
Based on the snippet: <|code_start|> def _get_some_qual_and_lengths(fhand, force_file_as_non_seek): 'It returns the quality characters and the lengths' seqs_to_peek = get_setting('SEQS_TO_GUESS_FASTQ_VERSION') chunk_size = get_setting('CHUNK_TO_GUESS_FASTQ_VERSION') lengths = array('I') seqs_analyzed = 0 if fhand_is_seekable(fhand) and not force_file_as_non_seek: fmt_fhand = fhand chunk = fmt_fhand.read(chunk_size) fhand.seek(0) else: chunk = peek_chunk_from_file(fhand, chunk_size) fmt_fhand = cStringIO.StringIO(chunk) try: for seq in FastqGeneralIterator(fmt_fhand): qual = [ord(char) for char in seq[2]] sanger_chars = [q for q in qual if q < 64] if sanger_chars: fhand.seek(0) return None, True, chunk # no quals, no lengths, is_sanger lengths.append(len(qual)) seqs_analyzed += 1 if seqs_analyzed > seqs_to_peek: break except ValueError: msg = 'The file is Fastq, but the version is difficult to guess' raise UndecidedFastqVersionError(msg) <|code_end|> , predict the immediate next line with the help of imports: import cStringIO import hashlib from array import array from crumbs.utils.optional_modules import FastqGeneralIterator from crumbs.settings import get_setting from crumbs.utils.file_utils import fhand_is_seekable, peek_chunk_from_file from crumbs.exceptions import (UnknownFormatError, UndecidedFastqVersionError, FileIsEmptyError) and context (classes, functions, sometimes code) from other files: # Path: crumbs/utils/optional_modules.py # MSG = 'A python package to run this executable is required,' # BIO = 'biopython' # BIO_BGZF = 'biopython with Bgzf support' # NCBIXML = create_fake_class(MSG + BIO) # NCBIWWW = create_fake_class(MSG + BIO) # def create_fake_class(msg): # def __init__(self, *args, **kwargs): # def create_fake_funct(msg): # def FakeRequiredfunct(*args, **kwargs): # class FakePythonRequiredClass(object): # # Path: crumbs/settings.py # def get_setting(key): # 'It returns the value for one setting' # return _settings[key] # # Path: crumbs/utils/file_utils.py # def fhand_is_seekable(fhand): # 'It returns True if the fhand is seekable' # try: # try: # # The stdin stream in some instances has seek, has no seekable # fhand.tell() # except IOError: # return False # try: # if fhand.seekable(): # return True # else: # return False # except AttributeError: # return True # except AttributeError: # return False # # def peek_chunk_from_file(fhand, chunk_size): # 'It returns the beginning of a file without moving the pointer' # if fhand_is_seekable(fhand): # fhand.seek(0) # chunk = fhand.read(chunk_size) # fhand.seek(0) # else: # chunk = fhand.peek(chunk_size) # return chunk # # Path: crumbs/exceptions.py # class UnknownFormatError(Exception): # 'Raised when the format of a sequence file cannot be guessed' # pass # # class UndecidedFastqVersionError(Exception): # 'The file is Fastq, but the version is difficult to guess' # pass # # class FileIsEmptyError(Exception): # pass . Output only the next line.
finally:
Predict the next line after this snippet: <|code_start|># Copyright 2013 Jose Blanca, Peio Ziarsolo, COMAV-Univ. Politecnica Valencia # This file is part of seq_crumbs. # seq_crumbs is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # seq_crumbs is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with seq_crumbs. If not, see <http://www.gnu.org/licenses/>. FILETYPE = 'file' STRINGIOTYPE = 'stringio' OTHERTYPE = 'othertype' def _get_some_qual_and_lengths(fhand, force_file_as_non_seek): <|code_end|> using the current file's imports: import cStringIO import hashlib from array import array from crumbs.utils.optional_modules import FastqGeneralIterator from crumbs.settings import get_setting from crumbs.utils.file_utils import fhand_is_seekable, peek_chunk_from_file from crumbs.exceptions import (UnknownFormatError, UndecidedFastqVersionError, FileIsEmptyError) and any relevant context from other files: # Path: crumbs/utils/optional_modules.py # MSG = 'A python package to run this executable is required,' # BIO = 'biopython' # BIO_BGZF = 'biopython with Bgzf support' # NCBIXML = create_fake_class(MSG + BIO) # NCBIWWW = create_fake_class(MSG + BIO) # def create_fake_class(msg): # def __init__(self, *args, **kwargs): # def create_fake_funct(msg): # def FakeRequiredfunct(*args, **kwargs): # class FakePythonRequiredClass(object): # # Path: crumbs/settings.py # def get_setting(key): # 'It returns the value for one setting' # return _settings[key] # # Path: crumbs/utils/file_utils.py # def fhand_is_seekable(fhand): # 'It returns True if the fhand is seekable' # try: # try: # # The stdin stream in some instances has seek, has no seekable # fhand.tell() # except IOError: # return False # try: # if fhand.seekable(): # return True # else: # return False # except AttributeError: # return True # except AttributeError: # return False # # def peek_chunk_from_file(fhand, chunk_size): # 'It returns the beginning of a file without moving the pointer' # if fhand_is_seekable(fhand): # fhand.seek(0) # chunk = fhand.read(chunk_size) # fhand.seek(0) # else: # chunk = fhand.peek(chunk_size) # return chunk # # Path: crumbs/exceptions.py # class UnknownFormatError(Exception): # 'Raised when the format of a sequence file cannot be guessed' # pass # # class UndecidedFastqVersionError(Exception): # 'The file is Fastq, but the version is difficult to guess' # pass # # class FileIsEmptyError(Exception): # pass . Output only the next line.
'It returns the quality characters and the lengths'
Here is a snippet: <|code_start|> def _get_alleles(call, filter_alleles_gt): alleles = call.int_alleles if filter_alleles_gt is not None: alleles = [allele for allele in alleles if allele <= filter_alleles_gt] return alleles def _flatten_data(x_data, y_data): new_x_data = [] new_y_data = [] for x, ys in zip(x_data, y_data): for y in ys: new_x_data.append(x) new_y_data.append(y) return new_x_data, new_y_data def plot_haplotypes(vcf_fhand, plot_fhand, genotype_mode=REFERENCE, filter_alleles_gt=FILTER_ALLELES_GT): reader = VCFReader(vcf_fhand) # collect data genotypes = None samples = [] for snv in reader.parse_snvs(): if genotypes is None: <|code_end|> . Write the next line using the current file imports: from matplotlib.figure import Figure from matplotlib.backends.backend_agg import FigureCanvasAgg from crumbs.plot import get_fig_and_canvas from crumbs.vcf.snv import VCFReader and context from other files: # Path: crumbs/plot.py # def get_fig_and_canvas(num_rows=1, num_cols=1, figsize=None): # if figsize is None: # height = 5.0 * num_rows # width = 7.5 * num_cols # if height > 320.0: # height = 320.0 # figsize = (width, height) # try: # fig = Figure(figsize=figsize) # canvas = FigureCanvas(fig) # except NameError: # msg = 'Matplotlib module is required to draw graphical histograms' # raise OptionalRequirementError(msg) # return fig, canvas # # Path: crumbs/vcf/snv.py # class VCFReader(object): # def __init__(self, fhand, compressed=None, filename=None, # min_calls_for_pop_stats=DEF_MIN_CALLS_FOR_POP_STATS): # self.fhand = fhand # self.pyvcf_reader = pyvcfReader(fsock=fhand, compressed=compressed, # filename=filename) # self.min_calls_for_pop_stats = min_calls_for_pop_stats # self._snpcaller = None # # def parse_snvs(self): # min_calls_for_pop_stats = self.min_calls_for_pop_stats # last_snp = None # try: # counter =0 # for snp in self.pyvcf_reader: # counter +=1 # snp = SNV(snp, reader=self, # min_calls_for_pop_stats=min_calls_for_pop_stats) # last_snp = snp # yield snp # except Exception: # from traceback import print_exception # exc_type, exc_value, exc_traceback = sys.exc_info() # # print_exception(exc_type, exc_value, exc_traceback, # limit=20, file=sys.stderr) # # if last_snp is not None: # chrom = str(last_snp.chrom) # pos = last_snp.pos # msg = 'Last parsed SNP was: {} {}\n'.format(chrom, pos + 1) # sys.stderr.write(msg) # raise # # def fetch_snvs(self, chrom, start, end=None): # min_calls_for_pop_stats = self.min_calls_for_pop_stats # try: # snvs = self.pyvcf_reader.fetch(chrom, start + 1, end=end) # except KeyError: # snvs = [] # if snvs is None: # snvs = [] # # for snp in snvs: # snp = SNV(snp, reader=self, # min_calls_for_pop_stats=min_calls_for_pop_stats) # yield snp # # def sliding_windows(self, size, step=None, ref_fhand=None, # min_num_snps=DEF_MIN_NUM_SNPS_IN_WIN): # random_snp_reader = VCFReader(open(self.fhand.name)) # sliding_window = _SNPSlidingWindow(snp_reader=random_snp_reader, # win_size=size, win_step=step, # min_num_snps=min_num_snps, # ref_fhand=ref_fhand) # for window in sliding_window.windows(): # yield window # # @property # def snpcaller(self): # if self._snpcaller is not None: # return self._snpcaller # # metadata = self.pyvcf_reader.metadata # if 'source' in metadata: # if 'VarScan2' in metadata['source']: # snpcaller = VARSCAN # elif 'freebayes' in metadata['source'][0].lower(): # snpcaller = FREEBAYES # else: # snpcaller = GENERIC # elif 'UnifiedGenotyper' in metadata: # snpcaller = GATK # else: # snpcaller = GENERIC # self._snpcaller = snpcaller # return snpcaller # # @property # def samples(self): # return self.pyvcf_reader.samples # # @property # def filters(self): # return self.pyvcf_reader.filters # # @property # def infos(self): # return self.pyvcf_reader.infos # # @property # def header(self): # header = '\n'.join(self.pyvcf_reader._header_lines) # header += '\n#' + '\t'.join(self.pyvcf_reader._column_headers) # header += '\t' + '\t'.join(self.pyvcf_reader.samples) # return header , which may include functions, classes, or code. Output only the next line.
genotypes = {}
Here is a snippet: <|code_start|> # draw n_samples = len(samples) xsize = len(genotypes[sample]) / 100 if xsize >= 100: xsize = 100 if xsize <= 8: xsize = 8 ysize = n_samples * 2 if ysize >= 100: ysize = 100 # print xsize, ysize figure_size = (xsize, ysize) fig = Figure(figsize=figure_size) for index, sample in enumerate(samples): axes = fig.add_subplot(n_samples, 1, index) axes.set_title(sample) y_data = genotypes[sample] x_data = [i + 1 for i in range(len(y_data))] x_data, y_data = _flatten_data(x_data, y_data) axes.plot(x_data, y_data, marker='o', linestyle='None', markersize=3.0, markeredgewidth=0, markerfacecolor='red') ylim = axes.get_ylim() ylim = ylim[0] - 0.1, ylim[1] + 0.1 axes.set_ylim(ylim) axes.tick_params(axis='x', bottom='off', top='off', which='both', labelbottom='off') <|code_end|> . Write the next line using the current file imports: from matplotlib.figure import Figure from matplotlib.backends.backend_agg import FigureCanvasAgg from crumbs.plot import get_fig_and_canvas from crumbs.vcf.snv import VCFReader and context from other files: # Path: crumbs/plot.py # def get_fig_and_canvas(num_rows=1, num_cols=1, figsize=None): # if figsize is None: # height = 5.0 * num_rows # width = 7.5 * num_cols # if height > 320.0: # height = 320.0 # figsize = (width, height) # try: # fig = Figure(figsize=figsize) # canvas = FigureCanvas(fig) # except NameError: # msg = 'Matplotlib module is required to draw graphical histograms' # raise OptionalRequirementError(msg) # return fig, canvas # # Path: crumbs/vcf/snv.py # class VCFReader(object): # def __init__(self, fhand, compressed=None, filename=None, # min_calls_for_pop_stats=DEF_MIN_CALLS_FOR_POP_STATS): # self.fhand = fhand # self.pyvcf_reader = pyvcfReader(fsock=fhand, compressed=compressed, # filename=filename) # self.min_calls_for_pop_stats = min_calls_for_pop_stats # self._snpcaller = None # # def parse_snvs(self): # min_calls_for_pop_stats = self.min_calls_for_pop_stats # last_snp = None # try: # counter =0 # for snp in self.pyvcf_reader: # counter +=1 # snp = SNV(snp, reader=self, # min_calls_for_pop_stats=min_calls_for_pop_stats) # last_snp = snp # yield snp # except Exception: # from traceback import print_exception # exc_type, exc_value, exc_traceback = sys.exc_info() # # print_exception(exc_type, exc_value, exc_traceback, # limit=20, file=sys.stderr) # # if last_snp is not None: # chrom = str(last_snp.chrom) # pos = last_snp.pos # msg = 'Last parsed SNP was: {} {}\n'.format(chrom, pos + 1) # sys.stderr.write(msg) # raise # # def fetch_snvs(self, chrom, start, end=None): # min_calls_for_pop_stats = self.min_calls_for_pop_stats # try: # snvs = self.pyvcf_reader.fetch(chrom, start + 1, end=end) # except KeyError: # snvs = [] # if snvs is None: # snvs = [] # # for snp in snvs: # snp = SNV(snp, reader=self, # min_calls_for_pop_stats=min_calls_for_pop_stats) # yield snp # # def sliding_windows(self, size, step=None, ref_fhand=None, # min_num_snps=DEF_MIN_NUM_SNPS_IN_WIN): # random_snp_reader = VCFReader(open(self.fhand.name)) # sliding_window = _SNPSlidingWindow(snp_reader=random_snp_reader, # win_size=size, win_step=step, # min_num_snps=min_num_snps, # ref_fhand=ref_fhand) # for window in sliding_window.windows(): # yield window # # @property # def snpcaller(self): # if self._snpcaller is not None: # return self._snpcaller # # metadata = self.pyvcf_reader.metadata # if 'source' in metadata: # if 'VarScan2' in metadata['source']: # snpcaller = VARSCAN # elif 'freebayes' in metadata['source'][0].lower(): # snpcaller = FREEBAYES # else: # snpcaller = GENERIC # elif 'UnifiedGenotyper' in metadata: # snpcaller = GATK # else: # snpcaller = GENERIC # self._snpcaller = snpcaller # return snpcaller # # @property # def samples(self): # return self.pyvcf_reader.samples # # @property # def filters(self): # return self.pyvcf_reader.filters # # @property # def infos(self): # return self.pyvcf_reader.infos # # @property # def header(self): # header = '\n'.join(self.pyvcf_reader._header_lines) # header += '\n#' + '\t'.join(self.pyvcf_reader._column_headers) # header += '\t' + '\t'.join(self.pyvcf_reader.samples) # return header , which may include functions, classes, or code. Output only the next line.
axes.tick_params(axis='y', left='on', right='off', labelleft='off')
Using the snippet: <|code_start|># Copyright 2012 Jose Blanca, Peio Ziarsolo, COMAV-Univ. Politecnica Valencia # This file is part of seq_crumbs. # seq_crumbs is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # seq_crumbs is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with seq_crumbs. If not, see <http://www.gnu.org/licenses/>. class TestCollections(unittest.TestCase): def test_ordered_set(self): in_list = [1, 2, 3, 4, 5, 8, 10] not_in_list = [6, 9, 11, 13] ordered_set = OrderedSet(in_list) for item in in_list: assert item in ordered_set assert ordered_set.check_add(7) assert ordered_set._items == [1, 2, 3, 4, 5, 7, 8, 10] assert not ordered_set.check_add(2) <|code_end|> , determine the next line of code. You have imports: import unittest from crumbs.collectionz import OrderedSet, KeyedSet and context (class names, function names, or code) available: # Path: crumbs/collectionz.py # class OrderedSet(object): # # def __init__(self, ordered_set=None): # if ordered_set is None: # ordered_set = [] # self._items = ordered_set # # def check_add(self, item): # index = bisect(self._items, item) # if index == 0: # self._items.insert(0, item) # return True # else: # present = True if item == self._items[index - 1] else False # if present: # return False # else: # self._items.insert(index, item) # return True # # def __contains__(self, item): # index = bisect(self._items, item) # if index == 0: # return False # return True if item == self._items[index - 1] else False # # def __len__(self): # return len(self._items) # # class KeyedSet(object): # # def __init__(self, items=None, key=None): # if items is None: # items = set() # elif key: # items = set(map(key, items)) # else: # items = set(items) # self._items = items # self._len = len(self._items) # self._key = key # # def check_add(self, item): # item_key = self._key(item) if self._key else item # self._items.add(item_key) # if len(self._items) > self._len: # self._len = len(self._items) # return True # else: # return False # # def __contains__(self, item): # item_key = self._key(item) if self._key else item # return item_key in self._items # # def __len__(self): # return len(self._items) . Output only the next line.
assert ordered_set._items == [1, 2, 3, 4, 5, 7, 8, 10]
Here is a snippet: <|code_start|># GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with seq_crumbs. If not, see <http://www.gnu.org/licenses/>. class TestCollections(unittest.TestCase): def test_ordered_set(self): in_list = [1, 2, 3, 4, 5, 8, 10] not_in_list = [6, 9, 11, 13] ordered_set = OrderedSet(in_list) for item in in_list: assert item in ordered_set assert ordered_set.check_add(7) assert ordered_set._items == [1, 2, 3, 4, 5, 7, 8, 10] assert not ordered_set.check_add(2) assert ordered_set._items == [1, 2, 3, 4, 5, 7, 8, 10] assert ordered_set.check_add(0) assert ordered_set._items == [0, 1, 2, 3, 4, 5, 7, 8, 10] for item in not_in_list: assert item not in ordered_set def test_unordered_set(self): in_set = [1, 2, 3, 4, 5, 8, 10] not_in_set = [6, 9, 11, 13] keyed_set = KeyedSet(in_set) for item in in_set: assert item in keyed_set <|code_end|> . Write the next line using the current file imports: import unittest from crumbs.collectionz import OrderedSet, KeyedSet and context from other files: # Path: crumbs/collectionz.py # class OrderedSet(object): # # def __init__(self, ordered_set=None): # if ordered_set is None: # ordered_set = [] # self._items = ordered_set # # def check_add(self, item): # index = bisect(self._items, item) # if index == 0: # self._items.insert(0, item) # return True # else: # present = True if item == self._items[index - 1] else False # if present: # return False # else: # self._items.insert(index, item) # return True # # def __contains__(self, item): # index = bisect(self._items, item) # if index == 0: # return False # return True if item == self._items[index - 1] else False # # def __len__(self): # return len(self._items) # # class KeyedSet(object): # # def __init__(self, items=None, key=None): # if items is None: # items = set() # elif key: # items = set(map(key, items)) # else: # items = set(items) # self._items = items # self._len = len(self._items) # self._key = key # # def check_add(self, item): # item_key = self._key(item) if self._key else item # self._items.add(item_key) # if len(self._items) > self._len: # self._len = len(self._items) # return True # else: # return False # # def __contains__(self, item): # item_key = self._key(item) if self._key else item # return item_key in self._items # # def __len__(self): # return len(self._items) , which may include functions, classes, or code. Output only the next line.
assert keyed_set.check_add(7)
Predict the next line for this snippet: <|code_start|># Copyright 2012 Jose Blanca, Peio Ziarsolo, COMAV-Univ. Politecnica Valencia # This file is part of seq_crumbs. # seq_crumbs is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # seq_crumbs is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with seq_crumbs. If not, see <http://www.gnu.org/licenses/>. try: except ImportError: pass <|code_end|> with the help of current file imports: import tempfile import shutil import io import os.path from gzip import GzipFile from subprocess import check_call, Popen, PIPE from crumbs.utils.optional_modules import BgzfWriter from crumbs.utils.tags import BGZF, GZIP, BZIP2 from crumbs.utils import BZ2File from crumbs.exceptions import OptionalRequirementError and context from other files: # Path: crumbs/utils/optional_modules.py # MSG = 'A python package to run this executable is required,' # BIO = 'biopython' # BIO_BGZF = 'biopython with Bgzf support' # NCBIXML = create_fake_class(MSG + BIO) # NCBIWWW = create_fake_class(MSG + BIO) # def create_fake_class(msg): # def __init__(self, *args, **kwargs): # def create_fake_funct(msg): # def FakeRequiredfunct(*args, **kwargs): # class FakePythonRequiredClass(object): # # Path: crumbs/utils/tags.py # BGZF = 'bgzf' # # GZIP = 'gzip' # # BZIP2 = 'bzip2' # # Path: crumbs/exceptions.py # class OptionalRequirementError(Exception): # 'An optional module is not present' # pass , which may contain function names, class names, or code. Output only the next line.
DEF_FILE_BUFFER = 8192*4
Based on the snippet: <|code_start|># Copyright 2012 Jose Blanca, Peio Ziarsolo, COMAV-Univ. Politecnica Valencia # This file is part of seq_crumbs. # seq_crumbs is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # seq_crumbs is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with seq_crumbs. If not, see <http://www.gnu.org/licenses/>. try: except ImportError: pass <|code_end|> , predict the immediate next line with the help of imports: import tempfile import shutil import io import os.path from gzip import GzipFile from subprocess import check_call, Popen, PIPE from crumbs.utils.optional_modules import BgzfWriter from crumbs.utils.tags import BGZF, GZIP, BZIP2 from crumbs.utils import BZ2File from crumbs.exceptions import OptionalRequirementError and context (classes, functions, sometimes code) from other files: # Path: crumbs/utils/optional_modules.py # MSG = 'A python package to run this executable is required,' # BIO = 'biopython' # BIO_BGZF = 'biopython with Bgzf support' # NCBIXML = create_fake_class(MSG + BIO) # NCBIWWW = create_fake_class(MSG + BIO) # def create_fake_class(msg): # def __init__(self, *args, **kwargs): # def create_fake_funct(msg): # def FakeRequiredfunct(*args, **kwargs): # class FakePythonRequiredClass(object): # # Path: crumbs/utils/tags.py # BGZF = 'bgzf' # # GZIP = 'gzip' # # BZIP2 = 'bzip2' # # Path: crumbs/exceptions.py # class OptionalRequirementError(Exception): # 'An optional module is not present' # pass . Output only the next line.
DEF_FILE_BUFFER = 8192*4
Here is a snippet: <|code_start|># Copyright 2012 Jose Blanca, Peio Ziarsolo, COMAV-Univ. Politecnica Valencia # This file is part of seq_crumbs. # seq_crumbs is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # seq_crumbs is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with seq_crumbs. If not, see <http://www.gnu.org/licenses/>. try: except ImportError: pass <|code_end|> . Write the next line using the current file imports: import tempfile import shutil import io import os.path from gzip import GzipFile from subprocess import check_call, Popen, PIPE from crumbs.utils.optional_modules import BgzfWriter from crumbs.utils.tags import BGZF, GZIP, BZIP2 from crumbs.utils import BZ2File from crumbs.exceptions import OptionalRequirementError and context from other files: # Path: crumbs/utils/optional_modules.py # MSG = 'A python package to run this executable is required,' # BIO = 'biopython' # BIO_BGZF = 'biopython with Bgzf support' # NCBIXML = create_fake_class(MSG + BIO) # NCBIWWW = create_fake_class(MSG + BIO) # def create_fake_class(msg): # def __init__(self, *args, **kwargs): # def create_fake_funct(msg): # def FakeRequiredfunct(*args, **kwargs): # class FakePythonRequiredClass(object): # # Path: crumbs/utils/tags.py # BGZF = 'bgzf' # # GZIP = 'gzip' # # BZIP2 = 'bzip2' # # Path: crumbs/exceptions.py # class OptionalRequirementError(Exception): # 'An optional module is not present' # pass , which may include functions, classes, or code. Output only the next line.
DEF_FILE_BUFFER = 8192*4
Here is a snippet: <|code_start|> seq = record.seq if trim: record.annotations = {} record = record[clip:] else: annots['clip_qual_left'] = clip annots['clip_adapter_left'] = clip seq = seq[:clip].lower() + seq[clip:].upper() quals = record.letter_annotations['phred_quality'] record.letter_annotations = {} record.seq = seq dict.__setitem__(record._per_letter_annotations, "phred_quality", quals) yield record class SffExtractor(object): 'This class extracts the reads from an SFF file' def __init__(self, sff_fhands, trim=False, min_left_clip=0, nucls_to_check=50, max_nucl_freq_threshold=0.5): 'It inits the class' self.fhands = sff_fhands self.trim = trim self.min_left_clip = min_left_clip # checking self.nucls_to_check = nucls_to_check self.max_nucl_freq_threshold = max_nucl_freq_threshold self.nucl_counts = {} <|code_end|> . Write the next line using the current file imports: from array import array from crumbs.utils.optional_modules import SffIterator and context from other files: # Path: crumbs/utils/optional_modules.py # MSG = 'A python package to run this executable is required,' # BIO = 'biopython' # BIO_BGZF = 'biopython with Bgzf support' # NCBIXML = create_fake_class(MSG + BIO) # NCBIWWW = create_fake_class(MSG + BIO) # def create_fake_class(msg): # def __init__(self, *args, **kwargs): # def create_fake_funct(msg): # def FakeRequiredfunct(*args, **kwargs): # class FakePythonRequiredClass(object): , which may include functions, classes, or code. Output only the next line.
@property
Using the snippet: <|code_start|>except ImportError: class DummyConnection(object): "Used to detect a failed ConnectionCls import." pass try: # Compiled with SSL? HTTPSConnection = DummyConnection BaseSSLError = ssl.SSLError except (ImportError, AttributeError): # Platform-specific: No SSL. ssl = None class BaseSSLError(BaseException): pass port_by_scheme = { 'http': 80, 'https': 443, } RECENT_DATE = datetime.date(2014, 1, 1) <|code_end|> , determine the next line of code. You have imports: import datetime import sys import socket import warnings import ssl from socket import timeout as SocketTimeout from http.client import HTTPConnection as _HTTPConnection, HTTPException from httplib import HTTPConnection as _HTTPConnection, HTTPException from .exceptions import ( ConnectTimeoutError, SystemTimeWarning, ) from .packages.ssl_match_hostname import match_hostname from .packages import six from .util.ssl_ import ( resolve_cert_reqs, resolve_ssl_version, ssl_wrap_socket, assert_fingerprint, ) from .util import connection and context (class names, function names, or code) available: # Path: Custom/events/Zabbix/API/requests/packages/urllib3/util/ssl_.py # def resolve_cert_reqs(candidate): # """ # Resolves the argument to a numeric constant, which can be passed to # the wrap_socket function/method from the ssl module. # Defaults to :data:`ssl.CERT_NONE`. # If given a string it is assumed to be the name of the constant in the # :mod:`ssl` module or its abbrevation. # (So you can specify `REQUIRED` instead of `CERT_REQUIRED`. # If it's neither `None` nor a string we assume it is already the numeric # constant which can directly be passed to wrap_socket. # """ # if candidate is None: # return CERT_NONE # # if isinstance(candidate, str): # res = getattr(ssl, candidate, None) # if res is None: # res = getattr(ssl, 'CERT_' + candidate) # return res # # return candidate # # def resolve_ssl_version(candidate): # """ # like resolve_cert_reqs # """ # if candidate is None: # return PROTOCOL_SSLv23 # # if isinstance(candidate, str): # res = getattr(ssl, candidate, None) # if res is None: # res = getattr(ssl, 'PROTOCOL_' + candidate) # return res # # return candidate # # def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None, # ca_certs=None, server_hostname=None, # ssl_version=None): # """ # All arguments except `server_hostname` have the same meaning as for # :func:`ssl.wrap_socket` # # :param server_hostname: # Hostname of the expected certificate # """ # context = SSLContext(ssl_version) # context.verify_mode = cert_reqs # # # Disable TLS compression to migitate CRIME attack (issue #309) # OP_NO_COMPRESSION = 0x20000 # context.options |= OP_NO_COMPRESSION # # if ca_certs: # try: # context.load_verify_locations(ca_certs) # # Py32 raises IOError # # Py33 raises FileNotFoundError # except Exception as e: # Reraise as SSLError # raise SSLError(e) # if certfile: # # FIXME: This block needs a test. # context.load_cert_chain(certfile, keyfile) # if HAS_SNI: # Platform-specific: OpenSSL with enabled SNI # return context.wrap_socket(sock, server_hostname=server_hostname) # return context.wrap_socket(sock) # # def assert_fingerprint(cert, fingerprint): # """ # Checks if given fingerprint matches the supplied certificate. # # :param cert: # Certificate as bytes object. # :param fingerprint: # Fingerprint as string of hexdigits, can be interspersed by colons. # """ # # # Maps the length of a digest to a possible hash function producing # # this digest. # hashfunc_map = { # 16: md5, # 20: sha1 # } # # fingerprint = fingerprint.replace(':', '').lower() # digest_length, odd = divmod(len(fingerprint), 2) # # if odd or digest_length not in hashfunc_map: # raise SSLError('Fingerprint is of invalid length.') # # # We need encode() here for py32; works on py2 and p33. # fingerprint_bytes = unhexlify(fingerprint.encode()) # # hashfunc = hashfunc_map[digest_length] # # cert_digest = hashfunc(cert).digest() # # if not cert_digest == fingerprint_bytes: # raise SSLError('Fingerprints did not match. Expected "{0}", got "{1}".' # .format(hexlify(fingerprint_bytes), # hexlify(cert_digest))) . Output only the next line.
class HTTPConnection(_HTTPConnection, object):
Given snippet: <|code_start|> try: # Python 3 except ImportError: class DummyConnection(object): "Used to detect a failed ConnectionCls import." pass try: # Compiled with SSL? HTTPSConnection = DummyConnection BaseSSLError = ssl.SSLError except (ImportError, AttributeError): # Platform-specific: No SSL. ssl = None class BaseSSLError(BaseException): pass port_by_scheme = { 'http': 80, 'https': 443, <|code_end|> , continue by predicting the next line. Consider current file imports: import datetime import sys import socket import warnings import ssl from socket import timeout as SocketTimeout from http.client import HTTPConnection as _HTTPConnection, HTTPException from httplib import HTTPConnection as _HTTPConnection, HTTPException from .exceptions import ( ConnectTimeoutError, SystemTimeWarning, ) from .packages.ssl_match_hostname import match_hostname from .packages import six from .util.ssl_ import ( resolve_cert_reqs, resolve_ssl_version, ssl_wrap_socket, assert_fingerprint, ) from .util import connection and context: # Path: Custom/events/Zabbix/API/requests/packages/urllib3/util/ssl_.py # def resolve_cert_reqs(candidate): # """ # Resolves the argument to a numeric constant, which can be passed to # the wrap_socket function/method from the ssl module. # Defaults to :data:`ssl.CERT_NONE`. # If given a string it is assumed to be the name of the constant in the # :mod:`ssl` module or its abbrevation. # (So you can specify `REQUIRED` instead of `CERT_REQUIRED`. # If it's neither `None` nor a string we assume it is already the numeric # constant which can directly be passed to wrap_socket. # """ # if candidate is None: # return CERT_NONE # # if isinstance(candidate, str): # res = getattr(ssl, candidate, None) # if res is None: # res = getattr(ssl, 'CERT_' + candidate) # return res # # return candidate # # def resolve_ssl_version(candidate): # """ # like resolve_cert_reqs # """ # if candidate is None: # return PROTOCOL_SSLv23 # # if isinstance(candidate, str): # res = getattr(ssl, candidate, None) # if res is None: # res = getattr(ssl, 'PROTOCOL_' + candidate) # return res # # return candidate # # def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None, # ca_certs=None, server_hostname=None, # ssl_version=None): # """ # All arguments except `server_hostname` have the same meaning as for # :func:`ssl.wrap_socket` # # :param server_hostname: # Hostname of the expected certificate # """ # context = SSLContext(ssl_version) # context.verify_mode = cert_reqs # # # Disable TLS compression to migitate CRIME attack (issue #309) # OP_NO_COMPRESSION = 0x20000 # context.options |= OP_NO_COMPRESSION # # if ca_certs: # try: # context.load_verify_locations(ca_certs) # # Py32 raises IOError # # Py33 raises FileNotFoundError # except Exception as e: # Reraise as SSLError # raise SSLError(e) # if certfile: # # FIXME: This block needs a test. # context.load_cert_chain(certfile, keyfile) # if HAS_SNI: # Platform-specific: OpenSSL with enabled SNI # return context.wrap_socket(sock, server_hostname=server_hostname) # return context.wrap_socket(sock) # # def assert_fingerprint(cert, fingerprint): # """ # Checks if given fingerprint matches the supplied certificate. # # :param cert: # Certificate as bytes object. # :param fingerprint: # Fingerprint as string of hexdigits, can be interspersed by colons. # """ # # # Maps the length of a digest to a possible hash function producing # # this digest. # hashfunc_map = { # 16: md5, # 20: sha1 # } # # fingerprint = fingerprint.replace(':', '').lower() # digest_length, odd = divmod(len(fingerprint), 2) # # if odd or digest_length not in hashfunc_map: # raise SSLError('Fingerprint is of invalid length.') # # # We need encode() here for py32; works on py2 and p33. # fingerprint_bytes = unhexlify(fingerprint.encode()) # # hashfunc = hashfunc_map[digest_length] # # cert_digest = hashfunc(cert).digest() # # if not cert_digest == fingerprint_bytes: # raise SSLError('Fingerprints did not match. Expected "{0}", got "{1}".' # .format(hexlify(fingerprint_bytes), # hexlify(cert_digest))) which might include code, classes, or functions. Output only the next line.
}
Predict the next line for this snippet: <|code_start|>except ImportError: class DummyConnection(object): "Used to detect a failed ConnectionCls import." pass try: # Compiled with SSL? HTTPSConnection = DummyConnection BaseSSLError = ssl.SSLError except (ImportError, AttributeError): # Platform-specific: No SSL. ssl = None class BaseSSLError(BaseException): pass port_by_scheme = { 'http': 80, 'https': 443, } RECENT_DATE = datetime.date(2014, 1, 1) <|code_end|> with the help of current file imports: import datetime import sys import socket import warnings import ssl from socket import timeout as SocketTimeout from http.client import HTTPConnection as _HTTPConnection, HTTPException from httplib import HTTPConnection as _HTTPConnection, HTTPException from .exceptions import ( ConnectTimeoutError, SystemTimeWarning, ) from .packages.ssl_match_hostname import match_hostname from .packages import six from .util.ssl_ import ( resolve_cert_reqs, resolve_ssl_version, ssl_wrap_socket, assert_fingerprint, ) from .util import connection and context from other files: # Path: Custom/events/Zabbix/API/requests/packages/urllib3/util/ssl_.py # def resolve_cert_reqs(candidate): # """ # Resolves the argument to a numeric constant, which can be passed to # the wrap_socket function/method from the ssl module. # Defaults to :data:`ssl.CERT_NONE`. # If given a string it is assumed to be the name of the constant in the # :mod:`ssl` module or its abbrevation. # (So you can specify `REQUIRED` instead of `CERT_REQUIRED`. # If it's neither `None` nor a string we assume it is already the numeric # constant which can directly be passed to wrap_socket. # """ # if candidate is None: # return CERT_NONE # # if isinstance(candidate, str): # res = getattr(ssl, candidate, None) # if res is None: # res = getattr(ssl, 'CERT_' + candidate) # return res # # return candidate # # def resolve_ssl_version(candidate): # """ # like resolve_cert_reqs # """ # if candidate is None: # return PROTOCOL_SSLv23 # # if isinstance(candidate, str): # res = getattr(ssl, candidate, None) # if res is None: # res = getattr(ssl, 'PROTOCOL_' + candidate) # return res # # return candidate # # def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None, # ca_certs=None, server_hostname=None, # ssl_version=None): # """ # All arguments except `server_hostname` have the same meaning as for # :func:`ssl.wrap_socket` # # :param server_hostname: # Hostname of the expected certificate # """ # context = SSLContext(ssl_version) # context.verify_mode = cert_reqs # # # Disable TLS compression to migitate CRIME attack (issue #309) # OP_NO_COMPRESSION = 0x20000 # context.options |= OP_NO_COMPRESSION # # if ca_certs: # try: # context.load_verify_locations(ca_certs) # # Py32 raises IOError # # Py33 raises FileNotFoundError # except Exception as e: # Reraise as SSLError # raise SSLError(e) # if certfile: # # FIXME: This block needs a test. # context.load_cert_chain(certfile, keyfile) # if HAS_SNI: # Platform-specific: OpenSSL with enabled SNI # return context.wrap_socket(sock, server_hostname=server_hostname) # return context.wrap_socket(sock) # # def assert_fingerprint(cert, fingerprint): # """ # Checks if given fingerprint matches the supplied certificate. # # :param cert: # Certificate as bytes object. # :param fingerprint: # Fingerprint as string of hexdigits, can be interspersed by colons. # """ # # # Maps the length of a digest to a possible hash function producing # # this digest. # hashfunc_map = { # 16: md5, # 20: sha1 # } # # fingerprint = fingerprint.replace(':', '').lower() # digest_length, odd = divmod(len(fingerprint), 2) # # if odd or digest_length not in hashfunc_map: # raise SSLError('Fingerprint is of invalid length.') # # # We need encode() here for py32; works on py2 and p33. # fingerprint_bytes = unhexlify(fingerprint.encode()) # # hashfunc = hashfunc_map[digest_length] # # cert_digest = hashfunc(cert).digest() # # if not cert_digest == fingerprint_bytes: # raise SSLError('Fingerprints did not match. Expected "{0}", got "{1}".' # .format(hexlify(fingerprint_bytes), # hexlify(cert_digest))) , which may contain function names, class names, or code. Output only the next line.
class HTTPConnection(_HTTPConnection, object):
Using the snippet: <|code_start|> class DeflateDecoder(object): def __init__(self): self._first_try = True self._data = binary_type() self._obj = zlib.decompressobj() def __getattr__(self, name): return getattr(self._obj, name) def decompress(self, data): if not self._first_try: return self._obj.decompress(data) self._data += data <|code_end|> , determine the next line of code. You have imports: import zlib import io from socket import timeout as SocketTimeout from ._collections import HTTPHeaderDict from .exceptions import ProtocolError, DecodeError, ReadTimeoutError from .packages.six import string_types as basestring, binary_type from .connection import HTTPException, BaseSSLError from .util.response import is_fp_closed and context (class names, function names, or code) available: # Path: Custom/events/Zabbix/API/requests/packages/urllib3/connection.py # class DummyConnection(object): # class BaseSSLError(BaseException): # class HTTPConnection(_HTTPConnection, object): # class HTTPSConnection(HTTPConnection): # class VerifiedHTTPSConnection(HTTPSConnection): # RECENT_DATE = datetime.date(2014, 1, 1) # def __init__(self, *args, **kw): # def _new_conn(self): # def _prepare_conn(self, conn): # def connect(self): # def __init__(self, host, port=None, key_file=None, cert_file=None, # strict=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, **kw): # def connect(self): # def set_cert(self, key_file=None, cert_file=None, # cert_reqs=None, ca_certs=None, # assert_hostname=None, assert_fingerprint=None): # def connect(self): . Output only the next line.
try:
Here is a snippet: <|code_start|> class DeflateDecoder(object): def __init__(self): self._first_try = True self._data = binary_type() self._obj = zlib.decompressobj() def __getattr__(self, name): return getattr(self._obj, name) def decompress(self, data): if not self._first_try: return self._obj.decompress(data) self._data += data try: return self._obj.decompress(data) <|code_end|> . Write the next line using the current file imports: import zlib import io from socket import timeout as SocketTimeout from ._collections import HTTPHeaderDict from .exceptions import ProtocolError, DecodeError, ReadTimeoutError from .packages.six import string_types as basestring, binary_type from .connection import HTTPException, BaseSSLError from .util.response import is_fp_closed and context from other files: # Path: Custom/events/Zabbix/API/requests/packages/urllib3/connection.py # class DummyConnection(object): # class BaseSSLError(BaseException): # class HTTPConnection(_HTTPConnection, object): # class HTTPSConnection(HTTPConnection): # class VerifiedHTTPSConnection(HTTPSConnection): # RECENT_DATE = datetime.date(2014, 1, 1) # def __init__(self, *args, **kw): # def _new_conn(self): # def _prepare_conn(self, conn): # def connect(self): # def __init__(self, host, port=None, key_file=None, cert_file=None, # strict=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, **kw): # def connect(self): # def set_cert(self, key_file=None, cert_file=None, # cert_reqs=None, ca_certs=None, # assert_hostname=None, assert_fingerprint=None): # def connect(self): , which may include functions, classes, or code. Output only the next line.
except zlib.error:
Here is a snippet: <|code_start|># Put libraries such as Divisi in the PYTHONPATH. sys.path = ['/stuff/openmind'] + sys.path # Load the OMCS language model en = Language.get('en') en_nl=get_nl('en') # Load OMCS stopwords sw = open('stopwords.txt', 'r') swords = [x.strip() for x in sw.readlines()] # Parameters factor = 1 wsize = 2 def check_concept(concept): try: <|code_end|> . Write the next line using the current file imports: import sys, pickle, os from csc.divisi.cnet import * from csc.divisi.graphics import output_svg from vendor_db import iter_info from csamoa.corpus.models import * from csamoa.conceptnet.models import * and context from other files: # Path: csc/divisi/graphics.py # def output_svg(u, filename, concepts=None, xscale=1000, yscale=1000, min=0): # if concepts is None: concepts = u.label_list(0) # out = open(filename, 'w') # try: # print >> out, svg_header # diamonds = [] # for concept in concepts: # x, y = u[concept, 0], u[concept, 1] # diamonds.append(svg_diamond(x*xscale+350, y*yscale+450, # make_color(u[concept, 2], u[concept, 3], u[concept, 4]))) # if abs(x) > min or abs(y) > min: # print >> out, svg_text(x*xscale+350, y*yscale+450, xmlspecialchars(concept)).encode('utf-8') # print >> out, '\n'.join(diamonds).encode('utf-8') # print >> out, svg_footer # finally: # out.close() , which may include functions, classes, or code. Output only the next line.
Concept.get(concept, 'en')
Predict the next line after this snippet: <|code_start|> ## Utilities def get_shape_for_dict(expected): if len(expected.keys()) == 0: return () ndim = len(expected.keys()[0]) return tuple(len(set(k[dim] for k in expected.iterkeys())) for dim in xrange(ndim)) def nones_removed(d): return dict((k, v) for k, v in d.iteritems() if v is not None) def zeros_removed(d): return dict((k, v) for k, v in d.iteritems() if v) def dict_fill_in_missing_dims(d): <|code_end|> using the current file's imports: from nose.tools import eq_, assert_almost_equal from csc.divisi.util import nested_list_to_dict and any relevant context from other files: # Path: csc/divisi/util.py . Output only the next line.
items = d.items()
Continue the code snippet: <|code_start|> def cpu(): return (resource.getrusage(resource.RUSAGE_SELF).ru_utime+ resource.getrusage(resource.RUSAGE_SELF).ru_stime) _proc_status = '/proc/%d/status' % os.getpid() <|code_end|> . Use current file imports: from csc.divisi.labeled_tensor import SparseLabeledTensor import time import os import resource and context (classes, functions, or code) from other files: # Path: csc/divisi/labeled_tensor.py # class OldDenseLabeledTensor(LabeledView): # class OldSparseLabeledTensor(LabeledView): # def __repr__(self): # def __init__(self, *a, **kw): # def __repr__(self): # def dot(self, other): # def array_op(self, ufunc, *others): # def take_data(tensor): # def slice(self, mode, label): # def dense_slice(self, mode, label): # def load(cls, filebase): . Output only the next line.
_scale = {'kB': 1024.0, 'mB': 1024.0*1024.0,
Predict the next line for this snippet: <|code_start|>def test_pt_ordered_set(): tmpdir = tempfile.mkdtemp() tfile = os.path.join(tmpdir, 'pttensor.h5') ordered_set = PTOrderedSet.create(tfile, '/', 'labels_0') eq_(ordered_set.add('apple'), 0) eq_(ordered_set.add('banana'), 1) eq_(ordered_set[1], 'banana') eq_(ordered_set.index('apple'), 0) <|code_end|> with the help of current file imports: from csc.divisi.pt_ordered_set import PTOrderedSet from nose.tools import eq_ import tempfile, os.path and context from other files: # Path: csc/divisi/pt_ordered_set.py # class PTOrderedSet(OrderedSet): # @classmethod # def create(cls, filename, pt_path, pt_name, filters=None): # fileh = get_pyt_handle(filename) # array = fileh.createVLArray(pt_path, pt_name, tables.ObjectAtom(), filters=filters) # return cls(array) # # @classmethod # def open(cls, filename, pt_path, pt_name): # fileh = get_pyt_handle(filename) # array = fileh.getNode(pt_path, pt_name) # return cls(array) # # # def __init__(self, array): # self.items = array # self.indices = dict((item, idx) for idx, item in enumerate(array)) # self._setup_quick_lookup_methods() # # def __setitem__(self, n, newkey): # raise TypeError('Existing items in a PTOrderedSet cannot be changed.') # def __delitem__(self, n): # raise TypeError('Existing items in a PTOrderedSet cannot be changed.') # # #def __del__(self): # # self.array._ , which may contain function names, class names, or code. Output only the next line.
del ordered_set
Next line prediction: <|code_start|> n = min(self._iteration, self._remembrance) if n < self._bootstrap: w_old = float(n - 1) / n w_new = 1.0 / n else: l = self._amnesia w_old = float(n - l) / n w_new = float(l) / n # Compute the attractor attractor = self.compute_attractor(k, u) # Approach attractor self._v[k] *= w_old self._v[k] += attractor * w_new # Calculate component magnitudes v_hat = self._v[k].hat() if k == 0: if self._auto_baseline: base_mag = self._v[k].norm() else: base_mag = 0.0 else: base_mag = u * v_hat u_residue = u - (v_hat * base_mag) if k == 0: logger.debug('e0: %s' % str(self._v[k])) logger.debug('u: %s' % str(u)) if learn: logger.debug('attractor: %s' % str(attractor)) logger.debug('residue: %s' % str(u_residue)) <|code_end|> . Use current file imports: (import logging from csc.divisi.labeled_view import make_sparse_labeled_tensor) and context including class names, function names, or small code snippets from other files: # Path: csc/divisi/labeled_view.py # def make_sparse_labeled_tensor(ndim, labels=None, # initial=None, accumulate=None, # normalize=False): # ''' # Create a sparse labeled tensor. # # ndim: number of dimensions (usually 2) # # labels: if you already have label lists, pass them in here. (A # None in this list means an unlabeled dimension. If you simply # don't have labels yet, pass an OrderedSet().) # # initial / accumulate: sequences of (key, value) pairs to add to # the tensor. ``initial`` is applied first by ``.update``, meaning # that later values will override earlier ones. ``accumulate`` is # applied afterwards, and all values add to anything already there. # # normalize: # an int or tuple of ints: normalize along that dimension # True: normalize along axis 0 # 'tfidf': use tf-idf # 'tfidf.T': use tf-idf, transposed (matrix is documents by terms) # a class: adds that class as a layer. # ''' # if labels is None: labels = [OrderedSet() for _ in xrange(ndim)] # tensor = LabeledView(DictTensor(ndim), labels) # tensor.tensor._shape[:] = [len(label_list) for label_list in labels] # if initial is not None: # tensor.update(initial) # for k, v in accumulate or []: # tensor.inc(k, v) # # if normalize: # return tensor.normalized(normalize) # else: # return tensor . Output only the next line.
logger.debug('')
Using the snippet: <|code_start|>MAG_MAX = 100.0 K=6 # Prepare test vectors vecs = [numpy.array([random() for i in range(VEC_LEN)]) for j in range(VEC_COUNT)] vecs = [make_dense_labeled_tensor(v, None).to_sparse() for v in vecs] mags = sorted([MAG_MAX * random() for i in range(VEC_COUNT)]) print "Vectors prepared:" vecs = [v.hat() for v in vecs] for v in vecs: print v.values() print "\nMags selected:" print mags print "\n" # Prepare the CCIPCA instance ccipca = CCIPCA(k=K) # Prepare samples for i in range(ITERS): w = [random() * mags[j] for j in range(VEC_COUNT)] v = zerovec() for weight, vec in zip(w,vecs): v += vec * weight print "Training with vector: ", v.values() # Train #mags_res = ccipca.iteration([v], learn=True) #print "Mags:", mags_res <|code_end|> , determine the next line of code. You have imports: from csc.divisi.ccipca import CCIPCA, zerovec from csc.divisi.labeled_view import make_dense_labeled_tensor from random import random from math import sqrt import numpy and context (class names, function names, or code) available: # Path: csc/divisi/ccipca.py # class CCIPCA(object): # """A Candid Covariance-free Incremental Principal Component Analysis implementation""" # # def __init__(self, k, ev=None, i=0, bootstrap=20, amnesia=3.0, remembrance=100000.0, auto_baseline=True): # """Construct a CCIPCA computation with k initial eigenvectors ev at iteration i, using simple averaging until the iteration given by bootstrap, afterward using CCIPCA given amnesic parameter amnesia, rememberance parameter remembrance, and a weight vector and subspace criteria for simultaneous vector presentation""" # if ev is not None: self._v = ev # else: self._v = [zerovec() for iter in xrange(k)] # # self._k = k # self._amnesia = amnesia # self._iteration = i # self._bootstrap = bootstrap # self._remembrance = remembrance # self._auto_baseline = auto_baseline # # def compute_attractor(self, k, u, v_hat=None): # """Compute the attractor vector for eigenvector k with vector u""" # # if k == 0: return u # if v_hat is None: v_hat = self._v[k].hat() # partial = u * (u * v_hat) # return partial # # def update_eigenvector(self, k, u, learn=False): # """Update eigenvector k with vector u, returning pair # containing magnitude of eigenvector component and residue vector""" # if learn: # # Handle elementary cases # if self._iteration < k: # return 0.0, zerovec() # # if self._iteration == k: # self._v[k] = make_sparse_labeled_tensor(1, initial=u) # mag = self._v[k].norm() # return mag, zerovec() # # # Compute weighting factors # n = min(self._iteration, self._remembrance) # if n < self._bootstrap: # w_old = float(n - 1) / n # w_new = 1.0 / n # else: # l = self._amnesia # w_old = float(n - l) / n # w_new = float(l) / n # # # Compute the attractor # attractor = self.compute_attractor(k, u) # # # Approach attractor # self._v[k] *= w_old # self._v[k] += attractor * w_new # # # Calculate component magnitudes # v_hat = self._v[k].hat() # if k == 0: # if self._auto_baseline: base_mag = self._v[k].norm() # else: base_mag = 0.0 # else: base_mag = u * v_hat # # u_residue = u - (v_hat * base_mag) # if k == 0: # logger.debug('e0: %s' % str(self._v[k])) # logger.debug('u: %s' % str(u)) # if learn: # logger.debug('attractor: %s' % str(attractor)) # logger.debug('residue: %s' % str(u_residue)) # logger.debug('') # return base_mag, u_residue # # def iteration(self, u, learn=False): # """Train the eigenvector table with new vector u""" # print "iteration = ", self._iteration # mags = [] # u_copy = make_sparse_labeled_tensor(1, initial=u) # copy # for k in xrange(min(self._k, self._iteration+1)): # mag, new_u = self.update_eigenvector(k, u_copy, learn) # u_copy = new_u # mags.append(mag) # if learn: # self._iteration += 1 # self._v[1:] = sorted(self._v[1:], reverse=True, key=lambda v: v.norm()) # return mags # # def reconstruct(self, weights): # # Create a linear combination of the eigenvectors # sum = zerovec() # for index, w in enumerate(weights): # sum += self._v[index].hat() * w # return sum # # def smooth(self, u, k_max=None, learn=False): # mags = self.iteration(u, learn) # if k_max is not None: # mags = mags[:k_max] # vec = self.reconstruct(mags) # if not learn: # logger.debug("decomp: %s" % str(mags)) # return vec # # def zerovec(): # return make_sparse_labeled_tensor(1) # # Path: csc/divisi/labeled_view.py # def make_dense_labeled_tensor(data, labels): # return LabeledView(DenseTensor(data), labels) . Output only the next line.
v_out = ccipca.smooth(v, k_max=(VEC_COUNT+1), learn=True)
Next line prediction: <|code_start|> #os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'csamoa.settings') def pickledump(filename, obj): if not isinstance(filename, basestring): filename, obj = obj, filename f = gzip.open(filename, 'wb') pickle.dump(obj, f) f.close() def normalize_and_copy(tensor): newt = SparseLabeledTensor(ndim=2) newt.update(tensor.normalized()) return newt def normalize_and_copy_mode_one(tensor): newt = SparseLabeledTensor(ndim=2) newt.update(tensor.normalized(mode=1)) return newt def run_3blend_simple(tensor1, tensor2, tensor3, factor=None, factor2=None): <|code_end|> . Use current file imports: (from csc.divisi.cnet import conceptnet_2d_from_db #, conceptnet_2d_from_db_tuple from csc.divisi.labeled_tensor import SparseLabeledTensor from csc.divisi.util import get_picklecached_thing from csc.divisi.export_svdview import export_svdview import cPickle as pickle import gzip, os) and context including class names, function names, or small code snippets from other files: # Path: csc/divisi/cnet.py # # Path: csc/divisi/labeled_tensor.py # class OldDenseLabeledTensor(LabeledView): # class OldSparseLabeledTensor(LabeledView): # def __repr__(self): # def __init__(self, *a, **kw): # def __repr__(self): # def dot(self, other): # def array_op(self, ufunc, *others): # def take_data(tensor): # def slice(self, mode, label): # def dense_slice(self, mode, label): # def load(cls, filebase): # # Path: csc/divisi/util.py # # Path: csc/divisi/export_svdview.py # def denormalize(concept_text): # def null_denormalize(x): return x # def _sorted_rowvectors(m, denormalize, num_dims): # def fix_concept(c): # def write_tsv(matrix, outfn, denormalize=None, cutoff=40): # def write_packed(matrix, out_basename, denormalize=None, cutoff=40): # def write_annotated(matrix, out_basename, denormalize=None, cutoff=40, # filter=None, annotations=None, links=None): # def add_link_2way(links, source, target): # def feature_str(feature): # def svdview_single_tensor(tensor, out_basename): . Output only the next line.
tensor1 = normalize_and_copy(tensor1)
Here is a snippet: <|code_start|> #os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'csamoa.settings') def pickledump(filename, obj): if not isinstance(filename, basestring): filename, obj = obj, filename <|code_end|> . Write the next line using the current file imports: from csc.divisi.cnet import conceptnet_2d_from_db #, conceptnet_2d_from_db_tuple from csc.divisi.labeled_tensor import SparseLabeledTensor from csc.divisi.util import get_picklecached_thing from csc.divisi.export_svdview import export_svdview import cPickle as pickle import gzip, os and context from other files: # Path: csc/divisi/cnet.py # # Path: csc/divisi/labeled_tensor.py # class OldDenseLabeledTensor(LabeledView): # class OldSparseLabeledTensor(LabeledView): # def __repr__(self): # def __init__(self, *a, **kw): # def __repr__(self): # def dot(self, other): # def array_op(self, ufunc, *others): # def take_data(tensor): # def slice(self, mode, label): # def dense_slice(self, mode, label): # def load(cls, filebase): # # Path: csc/divisi/util.py # # Path: csc/divisi/export_svdview.py # def denormalize(concept_text): # def null_denormalize(x): return x # def _sorted_rowvectors(m, denormalize, num_dims): # def fix_concept(c): # def write_tsv(matrix, outfn, denormalize=None, cutoff=40): # def write_packed(matrix, out_basename, denormalize=None, cutoff=40): # def write_annotated(matrix, out_basename, denormalize=None, cutoff=40, # filter=None, annotations=None, links=None): # def add_link_2way(links, source, target): # def feature_str(feature): # def svdview_single_tensor(tensor, out_basename): , which may include functions, classes, or code. Output only the next line.
f = gzip.open(filename, 'wb')
Based on the snippet: <|code_start|> blend = tensor1*(1-factor) + tensor2*factor svd = blend.svd(k=50) #svd.summarize() return svd def find_rough_factor(tensor1, tensor2): # Only first sigmas t1 = tensor1.svd(k=20) sigma1 = t1.svals[0:10] a = sigma1[0] t2 = tensor2.svd(k=20) sigma2 = t2.svals[0:10] b = sigma2[0] return float(a/(a+b)) def pickledumpsvd(svd, basename): svd_u, svd_s, svd_v, svd_a = ['pickle/'+ basename + '_%s_.4f.pickle.gz' % (typ) for typ in ['u', 's', 'v', 'a']] pickledump(svd_u, svd.u) pickledump(svd_s, svd.svals) pickledump(svd_v, svd.v) pickledump(svd_a, blend) def conceptnet_with_custom_identities(identconst=20): cnet = conceptnet_2d_from_db('en', identities=0.0) for concept in cnet.label_list(0): cnet[concept, "DescribedAs/"+concept] = identconst cnet[concept, "IsA/"+concept] = identconst for (key, value) in cnet.iteritems(): concept, feature = key <|code_end|> , predict the immediate next line with the help of imports: from csc.divisi.cnet import conceptnet_2d_from_db #, conceptnet_2d_from_db_tuple from csc.divisi.labeled_tensor import SparseLabeledTensor from csc.divisi.util import get_picklecached_thing from csc.divisi.export_svdview import export_svdview import cPickle as pickle import gzip, os and context (classes, functions, sometimes code) from other files: # Path: csc/divisi/cnet.py # # Path: csc/divisi/labeled_tensor.py # class OldDenseLabeledTensor(LabeledView): # class OldSparseLabeledTensor(LabeledView): # def __repr__(self): # def __init__(self, *a, **kw): # def __repr__(self): # def dot(self, other): # def array_op(self, ufunc, *others): # def take_data(tensor): # def slice(self, mode, label): # def dense_slice(self, mode, label): # def load(cls, filebase): # # Path: csc/divisi/util.py # # Path: csc/divisi/export_svdview.py # def denormalize(concept_text): # def null_denormalize(x): return x # def _sorted_rowvectors(m, denormalize, num_dims): # def fix_concept(c): # def write_tsv(matrix, outfn, denormalize=None, cutoff=40): # def write_packed(matrix, out_basename, denormalize=None, cutoff=40): # def write_annotated(matrix, out_basename, denormalize=None, cutoff=40, # filter=None, annotations=None, links=None): # def add_link_2way(links, source, target): # def feature_str(feature): # def svdview_single_tensor(tensor, out_basename): . Output only the next line.
if value < 0:
Using the snippet: <|code_start|> filename, obj = obj, filename f = gzip.open(filename, 'wb') pickle.dump(obj, f) f.close() def normalize_and_copy(tensor): newt = SparseLabeledTensor(ndim=2) newt.update(tensor.normalized()) return newt def normalize_and_copy_mode_one(tensor): newt = SparseLabeledTensor(ndim=2) newt.update(tensor.normalized(mode=1)) return newt def run_3blend_simple(tensor1, tensor2, tensor3, factor=None, factor2=None): tensor1 = normalize_and_copy(tensor1) tensor2 = normalize_and_copy(tensor2) tensor3 = normalize_and_copy(tensor3) if factor is None: factor = find_rough_factor(tensor1, tensor2) print "Using factor: ", factor blend = tensor1*(1-factor) + tensor2*factor if factor2 is None: factor2 = find_rough_factor(blend, tensor3) print "Using factor2: ", factor2 <|code_end|> , determine the next line of code. You have imports: from csc.divisi.cnet import conceptnet_2d_from_db #, conceptnet_2d_from_db_tuple from csc.divisi.labeled_tensor import SparseLabeledTensor from csc.divisi.util import get_picklecached_thing from csc.divisi.export_svdview import export_svdview import cPickle as pickle import gzip, os and context (class names, function names, or code) available: # Path: csc/divisi/cnet.py # # Path: csc/divisi/labeled_tensor.py # class OldDenseLabeledTensor(LabeledView): # class OldSparseLabeledTensor(LabeledView): # def __repr__(self): # def __init__(self, *a, **kw): # def __repr__(self): # def dot(self, other): # def array_op(self, ufunc, *others): # def take_data(tensor): # def slice(self, mode, label): # def dense_slice(self, mode, label): # def load(cls, filebase): # # Path: csc/divisi/util.py # # Path: csc/divisi/export_svdview.py # def denormalize(concept_text): # def null_denormalize(x): return x # def _sorted_rowvectors(m, denormalize, num_dims): # def fix_concept(c): # def write_tsv(matrix, outfn, denormalize=None, cutoff=40): # def write_packed(matrix, out_basename, denormalize=None, cutoff=40): # def write_annotated(matrix, out_basename, denormalize=None, cutoff=40, # filter=None, annotations=None, links=None): # def add_link_2way(links, source, target): # def feature_str(feature): # def svdview_single_tensor(tensor, out_basename): . Output only the next line.
blend2 = blend*(1-factor2) + tensor3*factor2
Next line prediction: <|code_start|> thumbnail.allow_tags = True thumbnail.__name__ = 'Thumbnail' admin.site.register(Badge, BadgeAdmin) class AchievementInlineFormSet(BaseInlineFormSet): model = Achievement _enrollment_ids = None @property def enrollment_ids(self): if self.instance.badge_id == None: return [] if not self._enrollment_ids: self._enrollment_ids = list(Enrollment.objects.filter( course_class = self.instance.course_class ).order_by( 'student__full_name' ).values_list('id', flat=True)) return self._enrollment_ids def total_form_count(self): return len(self.enrollment_ids) if self.instance.id != None else 0 def __init__(self, *args, **kwargs): super(AchievementInlineFormSet, self).__init__(*args, **kwargs) enrollment_ids = list(self.enrollment_ids) # make a copy of the list index = 0 <|code_end|> . Use current file imports: (from django.contrib import admin from django.apps import apps from course.management.commands import refreshachievements from .models import * from .forms.forms import UserCreationForm, CaptchaPasswordResetForm from django.forms import BaseInlineFormSet, ModelForm from django.forms.widgets import TextInput from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from django.contrib import messages from django.utils.translation import gettext_lazy as _ from django.utils.translation import ungettext from django.utils.formats import date_format import markdown2) and context including class names, function names, or small code snippets from other files: # Path: course/management/commands/refreshachievements.py # class Command(BaseCommand): # def handle(self, *args, **options): # def refresh_achievements(course_classes): # # Path: course/forms/forms.py # class UserCreationForm(UserCreationForm): # """ # A UserCreationForm with optional password inputs. # """ # # def __init__(self, *args, **kwargs): # super(UserCreationForm, self).__init__(*args, **kwargs) # self.fields['password1'].required = False # self.fields['password2'].required = False # # If one field gets autocompleted but not the other, our 'neither # # password or both password' validation will be triggered. # self.fields['password1'].widget.attrs['autocomplete'] = 'off' # self.fields['password2'].widget.attrs['autocomplete'] = 'off' # # def clean_password2(self): # password1 = self.cleaned_data.get("password1") # password2 = self.cleaned_data.get("password2") # if password1 and password2 and password1 != password2: # raise forms.ValidationError( # self.error_messages['password_mismatch'], # code='password_mismatch', # ) # # if bool(password1) ^ bool(password2): # raise forms.ValidationError("Fill out both fields") # # return password2 # # class CaptchaPasswordResetForm(PasswordResetForm): # captcha = ( # ReCaptchaField() # if settings.RECAPTCHA_PUBLIC_KEY != '' and settings.RECAPTCHA_PRIVATE_KEY != '' # else None # ) # # def __init__(self, *args, **kwargs): # super().__init__(*args, **kwargs) # self.fields['email'].widget.attrs.update({'autofocus': 'autofocus'}) # # def get_users(self, email): # # removed check verifying if password is unusable # user_model = get_user_model() # active_users = user_model._default_manager.filter(**{ # '%s__iexact' % user_model.get_email_field_name(): email, # 'is_active': True, # }) # # return active_users . Output only the next line.
for form in self:
Next line prediction: <|code_start|> model = Grade raw_id_fields = ("assignment_task",) formset = EnrollmentGradeInlineFormSet ordering = ('assignment_task__assignment_id', 'assignment_task') def last_login_formatted_for_enrolment(self): return last_login_formatted(self.student.user) last_login_formatted_for_enrolment.short_description = _('Last Login') class EnrollmentAdmin(BasicAdmin): inlines = [SimpleGradeInline] list_display = ('student', 'id_number', 'course_class', 'total_score', last_login_formatted_for_enrolment) list_filter = ('course_class',) ordering = ('-course_class__start_date', 'student__full_name') search_fields = ('student__full_name',) def id_number(self, object): return object.student.id_number admin.site.register(Enrollment, EnrollmentAdmin) class StudentAdmin(BasicAdmin): inlines = [EnrollmentInline] list_display = ('full_name', 'id_number', 'enrollments') search_fields = ('full_name',) <|code_end|> . Use current file imports: (from django.contrib import admin from django.apps import apps from course.management.commands import refreshachievements from .models import * from .forms.forms import UserCreationForm, CaptchaPasswordResetForm from django.forms import BaseInlineFormSet, ModelForm from django.forms.widgets import TextInput from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from django.contrib import messages from django.utils.translation import gettext_lazy as _ from django.utils.translation import ungettext from django.utils.formats import date_format import markdown2) and context including class names, function names, or small code snippets from other files: # Path: course/management/commands/refreshachievements.py # class Command(BaseCommand): # def handle(self, *args, **options): # def refresh_achievements(course_classes): # # Path: course/forms/forms.py # class UserCreationForm(UserCreationForm): # """ # A UserCreationForm with optional password inputs. # """ # # def __init__(self, *args, **kwargs): # super(UserCreationForm, self).__init__(*args, **kwargs) # self.fields['password1'].required = False # self.fields['password2'].required = False # # If one field gets autocompleted but not the other, our 'neither # # password or both password' validation will be triggered. # self.fields['password1'].widget.attrs['autocomplete'] = 'off' # self.fields['password2'].widget.attrs['autocomplete'] = 'off' # # def clean_password2(self): # password1 = self.cleaned_data.get("password1") # password2 = self.cleaned_data.get("password2") # if password1 and password2 and password1 != password2: # raise forms.ValidationError( # self.error_messages['password_mismatch'], # code='password_mismatch', # ) # # if bool(password1) ^ bool(password2): # raise forms.ValidationError("Fill out both fields") # # return password2 # # class CaptchaPasswordResetForm(PasswordResetForm): # captcha = ( # ReCaptchaField() # if settings.RECAPTCHA_PUBLIC_KEY != '' and settings.RECAPTCHA_PRIVATE_KEY != '' # else None # ) # # def __init__(self, *args, **kwargs): # super().__init__(*args, **kwargs) # self.fields['email'].widget.attrs.update({'autofocus': 'autofocus'}) # # def get_users(self, email): # # removed check verifying if password is unusable # user_model = get_user_model() # active_users = user_model._default_manager.filter(**{ # '%s__iexact' % user_model.get_email_field_name(): email, # 'is_active': True, # }) # # return active_users . Output only the next line.
ordering = ('full_name',)
Using the snippet: <|code_start|> return last_login_formatted(self.student.user) last_login_formatted_for_enrolment.short_description = _('Last Login') class EnrollmentAdmin(BasicAdmin): inlines = [SimpleGradeInline] list_display = ('student', 'id_number', 'course_class', 'total_score', last_login_formatted_for_enrolment) list_filter = ('course_class',) ordering = ('-course_class__start_date', 'student__full_name') search_fields = ('student__full_name',) def id_number(self, object): return object.student.id_number admin.site.register(Enrollment, EnrollmentAdmin) class StudentAdmin(BasicAdmin): inlines = [EnrollmentInline] list_display = ('full_name', 'id_number', 'enrollments') search_fields = ('full_name',) ordering = ('full_name',) raw_id_fields = ("user",) admin.site.register(Student, StudentAdmin) class ClassInstructorInline(admin.TabularInline): model = ClassInstructor <|code_end|> , determine the next line of code. You have imports: from django.contrib import admin from django.apps import apps from course.management.commands import refreshachievements from .models import * from .forms.forms import UserCreationForm, CaptchaPasswordResetForm from django.forms import BaseInlineFormSet, ModelForm from django.forms.widgets import TextInput from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from django.contrib import messages from django.utils.translation import gettext_lazy as _ from django.utils.translation import ungettext from django.utils.formats import date_format import markdown2 and context (class names, function names, or code) available: # Path: course/management/commands/refreshachievements.py # class Command(BaseCommand): # def handle(self, *args, **options): # def refresh_achievements(course_classes): # # Path: course/forms/forms.py # class UserCreationForm(UserCreationForm): # """ # A UserCreationForm with optional password inputs. # """ # # def __init__(self, *args, **kwargs): # super(UserCreationForm, self).__init__(*args, **kwargs) # self.fields['password1'].required = False # self.fields['password2'].required = False # # If one field gets autocompleted but not the other, our 'neither # # password or both password' validation will be triggered. # self.fields['password1'].widget.attrs['autocomplete'] = 'off' # self.fields['password2'].widget.attrs['autocomplete'] = 'off' # # def clean_password2(self): # password1 = self.cleaned_data.get("password1") # password2 = self.cleaned_data.get("password2") # if password1 and password2 and password1 != password2: # raise forms.ValidationError( # self.error_messages['password_mismatch'], # code='password_mismatch', # ) # # if bool(password1) ^ bool(password2): # raise forms.ValidationError("Fill out both fields") # # return password2 # # class CaptchaPasswordResetForm(PasswordResetForm): # captcha = ( # ReCaptchaField() # if settings.RECAPTCHA_PUBLIC_KEY != '' and settings.RECAPTCHA_PRIVATE_KEY != '' # else None # ) # # def __init__(self, *args, **kwargs): # super().__init__(*args, **kwargs) # self.fields['email'].widget.attrs.update({'autofocus': 'autofocus'}) # # def get_users(self, email): # # removed check verifying if password is unusable # user_model = get_user_model() # active_users = user_model._default_manager.filter(**{ # '%s__iexact' % user_model.get_email_field_name(): email, # 'is_active': True, # }) # # return active_users . Output only the next line.
ordering = ('course_class_id',)
Given the following code snippet before the placeholder: <|code_start|> class CheckPeriodThrottle(BaseThrottle): def allow_request(self, request, view): request.server = None allow = True <|code_end|> , predict the next line using imports from the current file: from rest_framework.throttling import BaseThrottle from amon.apps.servers.models import server_model from amon.apps.api.utils import throttle_status and context including class names, function names, and sometimes code from other files: # Path: amon/apps/api/utils.py # def throttle_status(server=None): # result = AmonStruct() # result.allow = False # # last_check = server.get('last_check') # server_check_period = server.get('check_every', 60) # # if last_check: # period_since_last_check = unix_utc_now() - last_check # # # Add 15 seconds buffer, for statsd # period_since_last_check = period_since_last_check + 15 # # if period_since_last_check >= server_check_period: # result.allow = True # else: # result.allow = True # Never checked # # return result . Output only the next line.
view_name = view.get_view_name()
Next line prediction: <|code_start|> def test_forgotten_password_form(self): self._cleanup() url = reverse('forgotten_password') response = self.c.post(url, {'email': self.email}) assert response.context['form'].errors # Create user and reset password self.user = User.objects.create_user(password='qwerty', email=self.email) response = self.c.post(url, {'email': self.email}) # assert forgotten_pass_tokens_model.collection.find().count() == 1 response = self.c.post(url, {'email': self.email}) # assert forgotten_pass_tokens_model.collection.find().count() == 1 def test_reset_password_form(self): self._cleanup() self.user = User.objects.create_user(self.email, 'qwerty') # Generate token url = reverse('forgotten_password') response = self.c.post(url, {'email': self.email}) assert forgotten_pass_tokens_model.collection.find().count() == 1 <|code_end|> . Use current file imports: (from django.test.client import Client from django.urls import reverse from django.test import TestCase from nose.tools import * from django.contrib.auth import get_user_model from amon.apps.users.forms import InviteForm from amon.apps.users.models import invite_model ) and context including class names, function names, or small code snippets from other files: # Path: amon/apps/users/forms.py # class InviteForm(forms.Form): # # def __init__(self, *args, **kwargs): # self.user = kwargs.pop('user', None) # super(InviteForm, self).__init__(*args, **kwargs) # # # email = forms.EmailField(required=True, widget=forms.TextInput(attrs={'placeholder': 'Email'})) # # # # def clean_email(self): # cleaned_data = self.cleaned_data # # email = cleaned_data['email'] # # # Check if invitation already exists # email_count = invite_model.collection.find({'email': email}).count() # # if email_count > 0: # raise forms.ValidationError('This user has already been invited.') # # # # Ignore invitations for the same email as the logged in user # if email == self.user.email: # raise forms.ValidationError("You can't invite yourself.") # # return cleaned_data['email'] # # # def save(self): # cleaned_data = self.cleaned_data # new_invite_email = cleaned_data['email'] # # data = { # 'email': new_invite_email, # 'invited_by': self.user.id, # 'sent': unix_utc_now() # } # # # invitation_code_string = "{0}{1}{2}".format(self.user.id, new_invite_email , unix_utc_now()) # encoded_invitation_code = invitation_code_string.encode() # data['invitation_code'] = hashlib.sha224(encoded_invitation_code).hexdigest() # # invite_model.create_invitation(data=data) # # return data # # Path: amon/apps/users/models.py # class AmonUserManager(BaseUserManager): # class AmonUser(AbstractBaseUser, PermissionsMixin): # class Meta: # class ResetPasswordCode(models.Model): # def create_user(self, email=None, password=None): # def create_superuser(self, email, password=None): # def get_short_name(self): # def get_username(self): # def __str__(self): # def generate_password_reset_token(user): # def __str__(self): # USERNAME_FIELD = 'email' . Output only the next line.
token = forgotten_pass_tokens_model.collection.find_one()
Based on the snippet: <|code_start|> User = get_user_model() class TestInvite(TestCase): def setUp(self): self.c = Client() self.user = User.objects.create_user(password='qwerty', email='foo@test.com') self.c.login(username='foo@test.com', password='qwerty') <|code_end|> , predict the immediate next line with the help of imports: from django.test.client import Client from django.urls import reverse from django.test import TestCase from nose.tools import * from django.contrib.auth import get_user_model from amon.apps.users.forms import InviteForm from amon.apps.users.models import invite_model and context (classes, functions, sometimes code) from other files: # Path: amon/apps/users/forms.py # class InviteForm(forms.Form): # # def __init__(self, *args, **kwargs): # self.user = kwargs.pop('user', None) # super(InviteForm, self).__init__(*args, **kwargs) # # # email = forms.EmailField(required=True, widget=forms.TextInput(attrs={'placeholder': 'Email'})) # # # # def clean_email(self): # cleaned_data = self.cleaned_data # # email = cleaned_data['email'] # # # Check if invitation already exists # email_count = invite_model.collection.find({'email': email}).count() # # if email_count > 0: # raise forms.ValidationError('This user has already been invited.') # # # # Ignore invitations for the same email as the logged in user # if email == self.user.email: # raise forms.ValidationError("You can't invite yourself.") # # return cleaned_data['email'] # # # def save(self): # cleaned_data = self.cleaned_data # new_invite_email = cleaned_data['email'] # # data = { # 'email': new_invite_email, # 'invited_by': self.user.id, # 'sent': unix_utc_now() # } # # # invitation_code_string = "{0}{1}{2}".format(self.user.id, new_invite_email , unix_utc_now()) # encoded_invitation_code = invitation_code_string.encode() # data['invitation_code'] = hashlib.sha224(encoded_invitation_code).hexdigest() # # invite_model.create_invitation(data=data) # # return data # # Path: amon/apps/users/models.py # class AmonUserManager(BaseUserManager): # class AmonUser(AbstractBaseUser, PermissionsMixin): # class Meta: # class ResetPasswordCode(models.Model): # def create_user(self, email=None, password=None): # def create_superuser(self, email, password=None): # def get_short_name(self): # def get_username(self): # def __str__(self): # def generate_password_reset_token(user): # def __str__(self): # USERNAME_FIELD = 'email' . Output only the next line.
def tearDown(self):
Given snippet: <|code_start|>register = template.Library() @register.filter def format_plugin_value(value, column): if column in ['size', 'totalIndexSize', 'indexes', 'total', 'bytes']: try: value = size(value) except Exception as e: pass <|code_end|> , continue by predicting the next line. Consider current file imports: from django import template from amon.utils.filesize import size and context: # Path: amon/utils/filesize.py # def size(bytes, system=alternative): # """Human-readable file size. # # Using the traditional system, where a factor of 1024 is used:: # # >>> size(10) # '10B' # >>> size(100) # '100B' # >>> size(1000) # '1000B' # >>> size(2000) # '1K' # >>> size(10000) # '9K' # >>> size(20000) # '19K' # >>> size(100000) # '97K' # >>> size(200000) # '195K' # >>> size(1000000) # '976K' # >>> size(2000000) # '1M' # # Using the SI system, with a factor 1000:: # # >>> size(10, system=si) # '10B' # >>> size(100, system=si) # '100B' # >>> size(1000, system=si) # '1K' # >>> size(2000, system=si) # '2K' # >>> size(10000, system=si) # '10K' # >>> size(20000, system=si) # '20K' # >>> size(100000, system=si) # '100K' # >>> size(200000, system=si) # '200K' # >>> size(1000000, system=si) # '1M' # >>> size(2000000, system=si) # '2M' # # """ # for factor, suffix in system: # if bytes >= factor: # break # amount = int(bytes/factor) # if isinstance(suffix, tuple): # singular, multiple = suffix # if amount == 1: # suffix = singular # else: # suffix = multiple # return str(amount) + suffix which might include code, classes, or functions. Output only the next line.
return value
Based on the snippet: <|code_start|> @login_required def data(request): if request.method == 'POST': form = DataRetentionForm(request.POST) if form.is_valid(): form.save() messages.add_message(request, messages.INFO, 'Data Retention settings updated') redirect_url = reverse('settings_data') return redirect(redirect_url) else: form = DataRetentionForm() return render(request, 'settings/data.html', { <|code_end|> , predict the immediate next line with the help of imports: from django.shortcuts import render from django.contrib import messages from django.shortcuts import redirect from django.urls import reverse from django.contrib.auth.decorators import login_required from amon.apps.settings.forms import DataRetentionForm, ApiKeyForm, CleanupDataForm from amon.apps.api.models import api_key_model, api_history_model and context (classes, functions, sometimes code) from other files: # Path: amon/apps/api/models.py . Output only the next line.
"form": form
Predict the next line for this snippet: <|code_start|> return redirect(redirect_url) else: form = DataRetentionForm() return render(request, 'settings/data.html', { "form": form }) @login_required def cleanup(request): if request.method == 'POST': form = CleanupDataForm(request.POST) if form.is_valid(): form.save() messages.add_message(request, messages.INFO, 'Cleaning up') redirect_url = reverse('settings_cleanup') return redirect(redirect_url) else: form = CleanupDataForm() return render(request, 'settings/cleanup.html', { "form": form }) <|code_end|> with the help of current file imports: from django.shortcuts import render from django.contrib import messages from django.shortcuts import redirect from django.urls import reverse from django.contrib.auth.decorators import login_required from amon.apps.settings.forms import DataRetentionForm, ApiKeyForm, CleanupDataForm from amon.apps.api.models import api_key_model, api_history_model and context from other files: # Path: amon/apps/api/models.py , which may contain function names, class names, or code. Output only the next line.
@login_required
Predict the next line for this snippet: <|code_start|> if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return Response({'ip': ip}) class TestView(APIView): def get(self, request, server_key): server = server_model.get_server_by_key(server_key) response_status = status.HTTP_200_OK if server else status.HTTP_403_FORBIDDEN return Response(status=response_status) def post(self, request, server_key): server = server_model.get_server_by_key(server_key) response_status = status.HTTP_200_OK if server else status.HTTP_403_FORBIDDEN return Response(status=response_status) # New golang agent data, format before saving it class SystemDataView(APIView): permission_classes = (ApiKeyPermission,) def post(self, request): <|code_end|> with the help of current file imports: from django.conf import settings from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from amon.apps.servers.models import server_model from amon.apps.api.throttle import CheckPeriodThrottle from amon.apps.api.permissions import ApiKeyPermission from amon.apps.notifications.sender import send_notifications from amon.apps.api.models import api_model and context from other files: # Path: amon/apps/api/throttle.py # class CheckPeriodThrottle(BaseThrottle): # # def allow_request(self, request, view): # request.server = None # allow = True # # view_name = view.get_view_name() # # allowed_views = [u'System Data', u'Collectd Data', u'Legacy System Data'] # # if view_name in allowed_views: # server_key = view.kwargs.get('server_key') # server = server_model.get_server_by_key(server_key) # # if server: # # request.server = server # Needed in the Models # server_status = throttle_status(server=server) # # # if server_status.allow == False: # allow = False # # # return allow # # Path: amon/apps/api/models.py , which may contain function names, class names, or code. Output only the next line.
status = settings.API_RESULTS['not-found']
Here is a snippet: <|code_start|> class CheckIpAddressView(APIView): def get(self, request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return Response({'ip': ip}) class TestView(APIView): <|code_end|> . Write the next line using the current file imports: from django.conf import settings from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from amon.apps.servers.models import server_model from amon.apps.api.throttle import CheckPeriodThrottle from amon.apps.api.permissions import ApiKeyPermission from amon.apps.notifications.sender import send_notifications from amon.apps.api.models import api_model and context from other files: # Path: amon/apps/api/throttle.py # class CheckPeriodThrottle(BaseThrottle): # # def allow_request(self, request, view): # request.server = None # allow = True # # view_name = view.get_view_name() # # allowed_views = [u'System Data', u'Collectd Data', u'Legacy System Data'] # # if view_name in allowed_views: # server_key = view.kwargs.get('server_key') # server = server_model.get_server_by_key(server_key) # # if server: # # request.server = server # Needed in the Models # server_status = throttle_status(server=server) # # # if server_status.allow == False: # allow = False # # # return allow # # Path: amon/apps/api/models.py , which may include functions, classes, or code. Output only the next line.
def get(self, request, server_key):
Next line prediction: <|code_start|> def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(InviteForm, self).__init__(*args, **kwargs) email = forms.EmailField(required=True, widget=forms.TextInput(attrs={'placeholder': 'Email'})) def clean_email(self): cleaned_data = self.cleaned_data email = cleaned_data['email'] # Check if invitation already exists email_count = invite_model.collection.find({'email': email}).count() if email_count > 0: raise forms.ValidationError('This user has already been invited.') # Ignore invitations for the same email as the logged in user if email == self.user.email: raise forms.ValidationError("You can't invite yourself.") return cleaned_data['email'] def save(self): <|code_end|> . Use current file imports: (import hashlib import uuid from django import forms from annoying.functions import get_object_or_None from django.contrib.auth import get_user_model from amon.utils.dates import unix_utc_now from amon.apps.users.models import invite_model ) and context including class names, function names, or small code snippets from other files: # Path: amon/apps/users/models.py # class AmonUserManager(BaseUserManager): # class AmonUser(AbstractBaseUser, PermissionsMixin): # class Meta: # class ResetPasswordCode(models.Model): # def create_user(self, email=None, password=None): # def create_superuser(self, email, password=None): # def get_short_name(self): # def get_username(self): # def __str__(self): # def generate_password_reset_token(user): # def __str__(self): # USERNAME_FIELD = 'email' . Output only the next line.
cleaned_data = self.cleaned_data
Predict the next line for this snippet: <|code_start|> self.c.login(username='foo@test.com', password='qwerty') def tearDown(self): self.c.logout() self.user.delete() def _cleanup(self): tags_model.collection.remove() tag_groups_model.collection.remove() bookmarks_model.collection.remove() def add_delete_bookmark_test(self): self._cleanup() url = reverse('bookmarks_add') tags = {'provider': 'digitalocean', 'credentials': 'production'} tag_ids = [str(x) for x in tags_model.create_and_return_ids(tags)] tag_ids_str = ",".join(tag_ids) form_data = {'name': 'test', 'tags': tag_ids_str, 'type': 'server'} <|code_end|> with the help of current file imports: from django.test.client import Client from django.urls import reverse from django.test import TestCase from nose.tools import * from django.contrib.auth import get_user_model from amon.apps.tags.models import tags_model, tag_groups_model from amon.apps.bookmarks.models import bookmarks_model and context from other files: # Path: amon/apps/bookmarks/models.py # class BookmarksModel(BaseModel): # def __init__(self): # def create(self, data=None): , which may contain function names, class names, or code. Output only the next line.
response = self.c.post(url, form_data)
Here is a snippet: <|code_start|> assert len(result['sorted_data']) == 10 assert result['sorted_data'][0]['value'] == 23 # 10 + 9 + 4 assert result['sorted_data'][0]['unit'] == '%' def test_sort_by_iface_data(self): self._cleanup() for i in range(10): data = { 'name': 'iface-server-{0}'.format(i), 'last_check': 100 } server_id = server_model.collection.insert(data.copy()) for v in range(5): device_data = { 'name': 'eth{0}'.format(v), 'server_id': server_id, 'last_update': 100, } device_id = interfaces_model.collection.insert(device_data.copy()) data_dict = { "server_id": server_id, "device_id": device_id, <|code_end|> . Write the next line using the current file imports: import unittest from time import time from amon.apps.servers.models import server_model from amon.apps.map.models import map_model from amon.apps.devices.models import interfaces_model, volumes_model from amon.apps.processes.models import process_model from amon.apps.system.models import system_model from amon.apps.tags.models import tags_model, tag_groups_model and context from other files: # Path: amon/apps/map/models.py # class MapModel(BaseModel): # def __init__(self): # def _get_device_stats(self, value=None, data=None): # def group_by(self, group_id=None, data=None): # def sort_by(self, field=None): # def get_fields(self): , which may include functions, classes, or code. Output only the next line.
"i": i + v + 100,
Given the code snippet: <|code_start|>from __future__ import division register = template.Library() @register.filter def kb_to_mb(value): <|code_end|> , generate the next line using the imports in this file: from django import template from amon.utils.filesize import size and context (functions, classes, or occasionally code) from other files: # Path: amon/utils/filesize.py # def size(bytes, system=alternative): # """Human-readable file size. # # Using the traditional system, where a factor of 1024 is used:: # # >>> size(10) # '10B' # >>> size(100) # '100B' # >>> size(1000) # '1000B' # >>> size(2000) # '1K' # >>> size(10000) # '9K' # >>> size(20000) # '19K' # >>> size(100000) # '97K' # >>> size(200000) # '195K' # >>> size(1000000) # '976K' # >>> size(2000000) # '1M' # # Using the SI system, with a factor 1000:: # # >>> size(10, system=si) # '10B' # >>> size(100, system=si) # '100B' # >>> size(1000, system=si) # '1K' # >>> size(2000, system=si) # '2K' # >>> size(10000, system=si) # '10K' # >>> size(20000, system=si) # '20K' # >>> size(100000, system=si) # '100K' # >>> size(200000, system=si) # '200K' # >>> size(1000000, system=si) # '1M' # >>> size(2000000, system=si) # '2M' # # """ # for factor, suffix in system: # if bytes >= factor: # break # amount = int(bytes/factor) # if isinstance(suffix, tuple): # singular, multiple = suffix # if amount == 1: # suffix = singular # else: # suffix = multiple # return str(amount) + suffix . Output only the next line.
mb = float(value)/1000
Based on the snippet: <|code_start|># from amon.apps.servers.models import server_model def charts_global_variables(request): if request.user.is_authenticated: # all_servers = server_model.get_all(account_itd=request.account_id) global_variables_dict = { 'duration_form': DurationForm(), 'system_charts_form': SystemChartsForm(), 'process_charts_form': ProcessChartsForm(), # 'all_servers': all_servers } else: global_variables_dict = { 'duration_form': DurationForm(), <|code_end|> , predict the immediate next line with the help of imports: from amon.apps.charts.forms import ( DurationForm, SystemChartsForm, ProcessChartsForm ) and context (classes, functions, sometimes code) from other files: # Path: amon/apps/charts/forms.py # class DurationForm(forms.Form): # duration = forms.ChoiceField(choices=DURATION_CHOICES) # # class SystemChartsForm(forms.Form): # charts = forms.ChoiceField(choices=SYSTEM_CHARTS) # # class ProcessChartsForm(forms.Form): # charts = forms.ChoiceField(choices=PROCESS_CHARTS) . Output only the next line.
}
Given snippet: <|code_start|># from amon.apps.servers.models import server_model def charts_global_variables(request): if request.user.is_authenticated: # all_servers = server_model.get_all(account_itd=request.account_id) global_variables_dict = { 'duration_form': DurationForm(), 'system_charts_form': SystemChartsForm(), 'process_charts_form': ProcessChartsForm(), # 'all_servers': all_servers <|code_end|> , continue by predicting the next line. Consider current file imports: from amon.apps.charts.forms import ( DurationForm, SystemChartsForm, ProcessChartsForm ) and context: # Path: amon/apps/charts/forms.py # class DurationForm(forms.Form): # duration = forms.ChoiceField(choices=DURATION_CHOICES) # # class SystemChartsForm(forms.Form): # charts = forms.ChoiceField(choices=SYSTEM_CHARTS) # # class ProcessChartsForm(forms.Form): # charts = forms.ChoiceField(choices=PROCESS_CHARTS) which might include code, classes, or functions. Output only the next line.
}
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- from __future__ import absolute_import SQL = { "sqlite": [""" CREATE TABLE "vote" ( list_name VARCHAR(255) NOT NULL, message_id VARCHAR(255) NOT NULL, user_id VARCHAR(255) NOT NULL, value TINYINT NOT NULL, PRIMARY KEY (list_name, message_id, user_id), FOREIGN KEY (list_name) REFERENCES list(name) ON DELETE CASCADE, FOREIGN KEY (list_name, message_id) REFERENCES email(list_name, message_id) ON DELETE CASCADE, FOREIGN KEY (user_id) REFERENCES user(id) );""", 'CREATE INDEX "ix_vote_list_name_message_id" ON "vote" (list_name, message_id);', 'CREATE INDEX "ix_vote_user_id" ON "vote" (user_id);', 'CREATE INDEX "ix_vote_value" ON "vote" (value);', <|code_end|> with the help of current file imports: from .utils import get_db_type and context from other files: # Path: kittystore/storm/schema/utils.py # def get_db_type(store): # database = store.get_database() # return database.__class__.__module__.split(".")[-1] , which may contain function names, class names, or code. Output only the next line.
],
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- from __future__ import absolute_import SQL = { "sqlite": [ # no adding of the "description" column because it couln't have been # remove in the past (SQLite has no REMOVE COLUMN statement) 'ALTER TABLE "list" ADD COLUMN recent_participants_count INTEGER;', 'ALTER TABLE "list" ADD COLUMN recent_threads_count INTEGER;', 'ALTER TABLE "thread" ADD COLUMN emails_count INTEGER;', 'ALTER TABLE "thread" ADD COLUMN participants_count INTEGER;', 'ALTER TABLE "thread" ADD COLUMN subject TEXT;', ], "postgres": [ 'ALTER TABLE "list" ADD COLUMN description TEXT;', <|code_end|> , predict the immediate next line with the help of imports: from .utils import get_db_type and context (classes, functions, sometimes code) from other files: # Path: kittystore/storm/schema/utils.py # def get_db_type(store): # database = store.get_database() # return database.__class__.__module__.split(".")[-1] . Output only the next line.
'ALTER TABLE "list" ADD COLUMN recent_participants_count INTEGER;',
Given snippet: <|code_start|> from __future__ import absolute_import SQL_step_1 = { "sqlite": [""" CREATE TABLE "user" ( id VARCHAR(255) NOT NULL, PRIMARY KEY (id) );""", """ CREATE TABLE "sender" ( email VARCHAR(255) NOT NULL, name VARCHAR(255), user_id VARCHAR(255), PRIMARY KEY (email), FOREIGN KEY (user_id) REFERENCES user(id) );""", 'CREATE INDEX "ix_sender_user_id" ON "sender" (user_id);', 'CREATE INDEX "ix_email_list_name_thread_id" ON "email" (list_name, thread_id);', 'CREATE INDEX "ix_attachment_list_name_message_id" ON "attachment" (list_name, message_id);', ], "postgres": [""" CREATE TABLE "user" ( id VARCHAR(255) NOT NULL, PRIMARY KEY (id) );""", """ CREATE TABLE "sender" ( email VARCHAR(255) NOT NULL, name VARCHAR(255), <|code_end|> , continue by predicting the next line. Consider current file imports: from .utils import get_db_type and context: # Path: kittystore/storm/schema/utils.py # def get_db_type(store): # database = store.get_database() # return database.__class__.__module__.split(".")[-1] which might include code, classes, or functions. Output only the next line.
user_id VARCHAR(255),
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- from __future__ import absolute_import SQL = { "sqlite": [""" CREATE TABLE "list_month_activity" ( list_name VARCHAR(255) NOT NULL, year INTEGER NOT NULL, month INTEGER NOT NULL, participants_count INTEGER, <|code_end|> , predict the immediate next line with the help of imports: from .utils import get_db_type and context (classes, functions, sometimes code) from other files: # Path: kittystore/storm/schema/utils.py # def get_db_type(store): # database = store.get_database() # return database.__class__.__module__.split(".")[-1] . Output only the next line.
threads_count INTEGER,
Using the snippet: <|code_start|># -*- coding: utf-8 -*- from __future__ import absolute_import SQL = { "sqlite": [ 'CREATE INDEX "ix_thread_list_name" ON "thread" (list_name);', ], "postgres": [ 'CREATE INDEX "ix_thread_list_name" ON "thread" (list_name);', ], "mysql": [ 'CREATE INDEX `ix_thread_list_name` ON `thread` (list_name);', ], } <|code_end|> , determine the next line of code. You have imports: from .utils import get_db_type and context (class names, function names, or code) available: # Path: kittystore/storm/schema/utils.py # def get_db_type(store): # database = store.get_database() # return database.__class__.__module__.split(".")[-1] . Output only the next line.
def apply(store):
Here is a snippet: <|code_start|> # UUIDs yet so it'll error out. metadata = sa.MetaData() metadata.bind = connection User = Base.metadata.tables["user"].tometadata(metadata) User = sa.Table("user", metadata, sa.Column("id", sa.Unicode(255), primary_key=True), extend_existing=True) if connection.dialect.name != "sqlite": drop_user_id_fkeys() create_user_id_fkeys("CASCADE") transaction = connection.begin() for user in User.select().execute(): try: new_user_id = unicode(UUID(int=int(user.id))) except ValueError: continue # Already converted User.update().where( User.c.id == user.id ).values(id=new_user_id).execute() transaction.commit() # Convert to UUID for PostreSQL or to CHAR(32) for others if op.get_context().dialect.name == 'sqlite': pass # No difference between varchar and char in SQLite elif op.get_context().dialect.name == 'postgresql': drop_user_id_fkeys() for table, col in ( ("user", "id"), ("sender", "user_id"), ("vote", "user_id") ): op.execute(''' ALTER TABLE "{table}" <|code_end|> . Write the next line using the current file imports: from uuid import UUID from alembic import op, context from mailman.database import types from kittystore.sa.model import Base import sqlalchemy as sa and context from other files: # Path: kittystore/sa/model.py # class List(Base): # class User(Base): # class Sender(Base): # class Email(Base): # class EmailFull(Base): # class Attachment(Base): # class Thread(Base): # class Category(Base): # class Vote(Base): # def get_recent_dates(self): # def recent_participants_count(self): # def recent_threads_count(self): # def get_month_activity(self, year, month): # def on_new_message(event): # will be called unbound (no self as 1st arg) # def messages(self): # def get_votes_in_list(self, list_name): # def getvotes(): # def __init__(self, *args, **kw): # def full(self): # def sender_name(self): # def user_id(self): # def _get_votes_query(self): # def likes(self): # def dislikes(self): # def likestatus(self): # def vote(self, value, user_id): # def get_vote_by_user_id(self, user_id): # def starting_email(self): # def last_email(self): # def _get_participants(self): # def participants(self): # def participants_count(self): # def get_emails(self, sort="date", limit=None, offset=None): # def email_ids(self): # def email_id_hashes(self): # def replies_after(self, date): # def _get_category(self): # def _set_category(self, name): # def __len__(self): # def emails_count(self): # def subject(self): # def _getvotes(self): # def likes(self): # def dislikes(self): # def likestatus(self): # def on_new_message(event): # will be called unbound (no self as 1st argument) # def on_new_thread(event): # will be called unbound (no self as 1st argument) # def Thread_before_insert(mapper, connection, target): , which may include functions, classes, or code. Output only the next line.
ALTER COLUMN {col} TYPE UUID USING {col}::uuid
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- from __future__ import absolute_import SQL = { "sqlite": [""" CREATE TABLE "category" ( id INTEGER NOT NULL, name VARCHAR(255) NOT NULL, PRIMARY KEY (id) );""", 'ALTER TABLE "thread" ADD COLUMN category_id INTEGER;', 'CREATE UNIQUE INDEX "ix_category_name" ON "category" (name);', ], "postgres": [""" <|code_end|> using the current file's imports: from .utils import get_db_type and any relevant context from other files: # Path: kittystore/storm/schema/utils.py # def get_db_type(store): # database = store.get_database() # return database.__class__.__module__.split(".")[-1] . Output only the next line.
CREATE TABLE "category" (
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- from __future__ import absolute_import SQL = { "sqlite": [ 'ALTER TABLE "email" ADD COLUMN "timezone" INTEGER NOT NULL DEFAULT 0;', ], "postgres": [ 'ALTER TABLE "email" ADD COLUMN "timezone" INTEGER;', 'UPDATE "email" SET "timezone" = EXTRACT(TIMEZONE_MINUTE FROM date)', 'UPDATE "email" SET date = date AT TIME ZONE \'UTC\';', 'ALTER TABLE "email" ALTER COLUMN "date" TYPE TIMESTAMP WITHOUT TIME ZONE;', <|code_end|> , predict the immediate next line with the help of imports: from .utils import get_db_type and context (classes, functions, sometimes code) from other files: # Path: kittystore/storm/schema/utils.py # def get_db_type(store): # database = store.get_database() # return database.__class__.__module__.split(".")[-1] . Output only the next line.
'ALTER TABLE "email" ALTER COLUMN "timezone" SET NOT NULL;',
Based on the snippet: <|code_start|> def _generate_public_image(self): private_file = storage.open(self.private_image.name, 'r') private_file = Image.open(private_file) image = private_file.filter(ImageFilter.GaussianBlur(self._determine_blur_radius(private_file))) private_file.close() # Path to save to, name, and extension image_name, image_extension = os.path.splitext(self.private_image.name) image_extension = image_extension.lower() image_filename = image_name + '_public' + image_extension if image_extension in ['.jpg', '.jpeg']: FTYPE = 'JPEG' elif image_extension == '.gif': FTYPE = 'GIF' elif image_extension == '.png': FTYPE = 'PNG' else: return False # Unrecognized file type # Save thumbnail to in-memory file as StringIO temp_image = StringIO() image.save(temp_image, FTYPE) temp_image.seek(0) # Load a ContentFile into the thumbnail field so it gets saved self.public_image.save(image_filename, ContentFile(temp_image.read()), save=True) temp_image.close() <|code_end|> , predict the immediate next line with the help of imports: import os import random from math import fabs from PIL import Image, ImageFilter from StringIO import StringIO from django.db import models from django.dispatch import receiver from django.core.files.base import ContentFile from django.db.models.signals import post_save from django.core.urlresolvers import reverse from django.contrib.auth.models import User from django.core.files.storage import default_storage as storage from btcimg.libs.common.models import SlugModel and context (classes, functions, sometimes code) from other files: # Path: btcimg/libs/common/models.py # class SlugModel(models.Model): # """ # A base class for any model that wants to implement an auto generated slug # field. # """ # # how many times we'll retry creating a slug before giving up # MAX_RETRIES = 1000 # regenerate_slug_on_save = False # slug = models.SlugField(_('slug'), max_length=255, unique=True, # editable=False) # # class Meta: # abstract = True # # @classmethod # def is_valid_slug(cls, slug): # """Convenience method to check if the given slug already exists.""" # manager = getattr(cls, 'all_objects', cls.objects) # return not manager.filter(slug=slug).exists() # # @classmethod # def get_by_slug(cls, slug, **extra): # """ # Return the :class:`nauman.libs.common.models.SlugModel` for the given # slug. If the slug dosen't exist, return None. # # :param slug: the slug value to search for # """ # try: # return cls.objects.get(slug=slug, **extra) # except cls.DoesNotExist: # return None # # @classmethod # def get_by_pk_or_slug(cls, value): # """ # Return the :class:`nauman.libs.common.models.SlugModel` for the given # slug or primary key. If either value doesn't exist, return None. # # :param value: the slug or id value to search for # """ # try: # return cls.objects.get(Q(slug=value) | Q(pk__iexact=value)) # except cls.DoesNotExist: # return None # # def base_slug_value(self): # """ # As a subclass of :class:`nauman.libs.common.models.SlugModel` one must # implement the :method:`nauman.libs.common.models.SlugModel.base_slug_value` # which returns a unicode value that is used as the basis of the slug value. # """ # raise NotImplementedError # # def generate_slug(self): # """ # Create a slug based on the value of # :method:`nauman.libs.common.models.SlugModel.base_slug_value`, ensure # that the slug is unique by comparing it to existing slugs. # """ # value = self.base_slug_value() # field = self._meta.get_field('slug') # return slugify(value, max_length=field.max_length, # usable=self.is_valid_slug, max_retries=self.MAX_RETRIES) # # def save(self, *args, **kwargs): # """ # Right before a model is saved, check to see if the slug field has yet # to be defined. If so, generate and set the # :attr:`nauman.libs.common.models.SlugModel.slug`. # """ # if not self.slug or self.regenerate_slug_on_save: # # a slug has not yet been defined, or updates are requested, generate one # self.slug = self.generate_slug() # return super(SlugModel, self).save(*args, **kwargs) # # def pusher_channel(self): # return self.slug.replace('-', '') . Output only the next line.
def get_public_image(self, btc_received):
Based on the snippet: <|code_start|> class AssetForm(ModelForm): btc_address = BCAddressField(label=_("Bitcoin Address"), help_text=_("Please use an address with no previous transactions.")) class Meta: model = Asset fields = ['name', 'btc_address', 'private_image'] labels = { 'private_image': 'Image' <|code_end|> , predict the immediate next line with the help of imports: from django.forms import ModelForm from django.utils.translation import ugettext_lazy as _ from btcimg.libs.common.forms.fields import BCAddressField from .models import Asset and context (classes, functions, sometimes code) from other files: # Path: btcimg/libs/common/forms/fields.py # class BCAddressField(forms.CharField): # # Django field type for a Bitcoin Address # # by Gavin Andresen via https://bitcointalk.org/index.php?topic=1026.0 # default_error_messages = { # 'invalid': 'Invalid Bitcoin address.', # } # # def clean(self, value): # value = value.strip() # if re.match(r"[a-zA-Z1-9]{27,35}$", value) is None: # raise ValidationError(self.error_messages['invalid']) # version = get_bcaddress_version(value) # if version is None: # raise ValidationError(self.error_messages['invalid']) # return value # # Path: btcimg/apps/locker/models.py # class Asset(SlugModel, models.Model): # owner = models.ForeignKey(User, null=True) # name = models.CharField(max_length=255) # unlock_value = models.DecimalField(max_digits=19, decimal_places=2, default=1.0) # btc_address = models.CharField(max_length=255) # description = models.TextField(blank=True) # # public_image = models.ImageField(max_length=255, blank=True, upload_to='public_images') # public_image_blur_ratio = models.FloatField(null=True, blank=True) # private_image = models.ImageField(max_length=255, upload_to='private_images') # # blocked = models.BooleanField(default=False) # edit_hash = models.CharField(max_length=255, blank=True) # # created = models.DateTimeField(auto_now_add=True) # updated = models.DateTimeField(auto_now=True) # # def base_slug_value(self): # return unicode(self.name) # # def __unicode__(self): # return self.name # # def get_absolute_url(self): # return reverse('locker:asset-detail', kwargs={'slug': self.slug}) # # def _determine_blur_radius(self, image): # return 0.25 * image.size[0] * self.public_image_blur_ratio # # def _generate_public_image(self): # private_file = storage.open(self.private_image.name, 'r') # private_file = Image.open(private_file) # image = private_file.filter(ImageFilter.GaussianBlur(self._determine_blur_radius(private_file))) # private_file.close() # # # Path to save to, name, and extension # image_name, image_extension = os.path.splitext(self.private_image.name) # image_extension = image_extension.lower() # # image_filename = image_name + '_public' + image_extension # # if image_extension in ['.jpg', '.jpeg']: # FTYPE = 'JPEG' # elif image_extension == '.gif': # FTYPE = 'GIF' # elif image_extension == '.png': # FTYPE = 'PNG' # else: # return False # Unrecognized file type # # # Save thumbnail to in-memory file as StringIO # temp_image = StringIO() # image.save(temp_image, FTYPE) # temp_image.seek(0) # # # Load a ContentFile into the thumbnail field so it gets saved # self.public_image.save(image_filename, ContentFile(temp_image.read()), save=True) # temp_image.close() # # def get_public_image(self, btc_received): # if btc_received >= self.unlock_value: # self.public_image_blur_ratio = 0 # self.public_image = self.private_image # self.save() # return self.private_image # # current_blur_ratio = self.public_image_blur_ratio # actual_blur_ratio = float(1.0) - float(btc_received) / self.unlock_value.__float__() # if not current_blur_ratio or fabs(1 - actual_blur_ratio / current_blur_ratio) > 0.1: # # If there is a >10% difference, update the image & the ratio # # This means that images are comprised of 10 steps, 1 being "most blurry" # # and 10 being "completely clear". # self.public_image_blur_ratio = actual_blur_ratio # self.save() # self._generate_public_image() # return self.public_image # # class Meta: # ordering = ['-name'] . Output only the next line.
}
Given snippet: <|code_start|> urlpatterns = patterns('', url(r'^create/', AssetCreate.as_view(), name='asset-create'), url(r'^list/', AssetList.as_view(), name='asset-list'), url(r'^img/(?P<slug>[\w\-\.\~\+&,]+)/', AssetView.as_view(), name='asset-detail'), <|code_end|> , continue by predicting the next line. Consider current file imports: from django.conf.urls import patterns, url from .views import AssetView, AssetCreate, AssetList and context: # Path: btcimg/apps/locker/views.py # class AssetView(generic.View): # def _get_btc_received(self, asset): # '''Returns a Decimal value or None''' # url = 'https://blockchain.info/address/%s?format=json&limit=0' % asset.btc_address # req = requests.get(url) # if req.status_code == 200: # if 'total_received' in req.json(): # return _satoshi_to_bitcoin(req.json()['total_received']) # return 0 # # def get(self, request, *args, **kwargs): # asset = get_object_or_404(Asset, slug=kwargs['slug']) # btc_received = self._get_btc_received(asset) # # btc_left = asset.unlock_value - btc_received # # data = { # 'asset': asset, # 'btc_left': btc_left, # 'public_image': asset.get_public_image(btc_received), # 'btc_received': btc_received, # } # return render(request, 'locker/detail.html', data) # # class AssetCreate(generic.edit.CreateView): # model = Asset # form_class = AssetForm # # def form_valid(self, form): # if self.request.user.is_authenticated(): # form.fields['owner'] = self.request.user.id # return super(AssetCreate, self).form_valid(form) # # def get_success_url(self): # return self.object.get_absolute_url() # # class AssetList(generic.TemplateView): # template_name = 'locker/list.html' which might include code, classes, or functions. Output only the next line.
)
Predict the next line for this snippet: <|code_start|> class AssetList(generics.ListAPIView): queryset = Asset.objects.filter(blocked=False) serializer_class = AssetSerializer permission_classes = (permissions.AllowAny,) filter_backends = (filters.OrderingFilter,) ordering_fields = ('created') ordering = ('-created',) paginate_by = 20 # @cache_response(60 * 60) def get(self, request, *args, **kwargs): return super(AssetList, self).get(request, *args, **kwargs) <|code_end|> with the help of current file imports: from django.conf.urls import patterns, url from rest_framework import generics, permissions, filters from .serializers import AssetSerializer from .models import Asset and context from other files: # Path: btcimg/apps/locker/serializers.py # class AssetSerializer(serializers.ModelSerializer): # url = serializers.SerializerMethodField() # # class Meta: # model = Asset # fields = ('id', 'name', 'unlock_value', 'btc_address', 'url', 'public_image',) # # def get_url(self, obj): # return obj.get_absolute_url() # # Path: btcimg/apps/locker/models.py # class Asset(SlugModel, models.Model): # owner = models.ForeignKey(User, null=True) # name = models.CharField(max_length=255) # unlock_value = models.DecimalField(max_digits=19, decimal_places=2, default=1.0) # btc_address = models.CharField(max_length=255) # description = models.TextField(blank=True) # # public_image = models.ImageField(max_length=255, blank=True, upload_to='public_images') # public_image_blur_ratio = models.FloatField(null=True, blank=True) # private_image = models.ImageField(max_length=255, upload_to='private_images') # # blocked = models.BooleanField(default=False) # edit_hash = models.CharField(max_length=255, blank=True) # # created = models.DateTimeField(auto_now_add=True) # updated = models.DateTimeField(auto_now=True) # # def base_slug_value(self): # return unicode(self.name) # # def __unicode__(self): # return self.name # # def get_absolute_url(self): # return reverse('locker:asset-detail', kwargs={'slug': self.slug}) # # def _determine_blur_radius(self, image): # return 0.25 * image.size[0] * self.public_image_blur_ratio # # def _generate_public_image(self): # private_file = storage.open(self.private_image.name, 'r') # private_file = Image.open(private_file) # image = private_file.filter(ImageFilter.GaussianBlur(self._determine_blur_radius(private_file))) # private_file.close() # # # Path to save to, name, and extension # image_name, image_extension = os.path.splitext(self.private_image.name) # image_extension = image_extension.lower() # # image_filename = image_name + '_public' + image_extension # # if image_extension in ['.jpg', '.jpeg']: # FTYPE = 'JPEG' # elif image_extension == '.gif': # FTYPE = 'GIF' # elif image_extension == '.png': # FTYPE = 'PNG' # else: # return False # Unrecognized file type # # # Save thumbnail to in-memory file as StringIO # temp_image = StringIO() # image.save(temp_image, FTYPE) # temp_image.seek(0) # # # Load a ContentFile into the thumbnail field so it gets saved # self.public_image.save(image_filename, ContentFile(temp_image.read()), save=True) # temp_image.close() # # def get_public_image(self, btc_received): # if btc_received >= self.unlock_value: # self.public_image_blur_ratio = 0 # self.public_image = self.private_image # self.save() # return self.private_image # # current_blur_ratio = self.public_image_blur_ratio # actual_blur_ratio = float(1.0) - float(btc_received) / self.unlock_value.__float__() # if not current_blur_ratio or fabs(1 - actual_blur_ratio / current_blur_ratio) > 0.1: # # If there is a >10% difference, update the image & the ratio # # This means that images are comprised of 10 steps, 1 being "most blurry" # # and 10 being "completely clear". # self.public_image_blur_ratio = actual_blur_ratio # self.save() # self._generate_public_image() # return self.public_image # # class Meta: # ordering = ['-name'] , which may contain function names, class names, or code. Output only the next line.
urlpatterns = patterns('',
Predict the next line for this snippet: <|code_start|> class AssetList(generics.ListAPIView): queryset = Asset.objects.filter(blocked=False) serializer_class = AssetSerializer permission_classes = (permissions.AllowAny,) filter_backends = (filters.OrderingFilter,) ordering_fields = ('created') <|code_end|> with the help of current file imports: from django.conf.urls import patterns, url from rest_framework import generics, permissions, filters from .serializers import AssetSerializer from .models import Asset and context from other files: # Path: btcimg/apps/locker/serializers.py # class AssetSerializer(serializers.ModelSerializer): # url = serializers.SerializerMethodField() # # class Meta: # model = Asset # fields = ('id', 'name', 'unlock_value', 'btc_address', 'url', 'public_image',) # # def get_url(self, obj): # return obj.get_absolute_url() # # Path: btcimg/apps/locker/models.py # class Asset(SlugModel, models.Model): # owner = models.ForeignKey(User, null=True) # name = models.CharField(max_length=255) # unlock_value = models.DecimalField(max_digits=19, decimal_places=2, default=1.0) # btc_address = models.CharField(max_length=255) # description = models.TextField(blank=True) # # public_image = models.ImageField(max_length=255, blank=True, upload_to='public_images') # public_image_blur_ratio = models.FloatField(null=True, blank=True) # private_image = models.ImageField(max_length=255, upload_to='private_images') # # blocked = models.BooleanField(default=False) # edit_hash = models.CharField(max_length=255, blank=True) # # created = models.DateTimeField(auto_now_add=True) # updated = models.DateTimeField(auto_now=True) # # def base_slug_value(self): # return unicode(self.name) # # def __unicode__(self): # return self.name # # def get_absolute_url(self): # return reverse('locker:asset-detail', kwargs={'slug': self.slug}) # # def _determine_blur_radius(self, image): # return 0.25 * image.size[0] * self.public_image_blur_ratio # # def _generate_public_image(self): # private_file = storage.open(self.private_image.name, 'r') # private_file = Image.open(private_file) # image = private_file.filter(ImageFilter.GaussianBlur(self._determine_blur_radius(private_file))) # private_file.close() # # # Path to save to, name, and extension # image_name, image_extension = os.path.splitext(self.private_image.name) # image_extension = image_extension.lower() # # image_filename = image_name + '_public' + image_extension # # if image_extension in ['.jpg', '.jpeg']: # FTYPE = 'JPEG' # elif image_extension == '.gif': # FTYPE = 'GIF' # elif image_extension == '.png': # FTYPE = 'PNG' # else: # return False # Unrecognized file type # # # Save thumbnail to in-memory file as StringIO # temp_image = StringIO() # image.save(temp_image, FTYPE) # temp_image.seek(0) # # # Load a ContentFile into the thumbnail field so it gets saved # self.public_image.save(image_filename, ContentFile(temp_image.read()), save=True) # temp_image.close() # # def get_public_image(self, btc_received): # if btc_received >= self.unlock_value: # self.public_image_blur_ratio = 0 # self.public_image = self.private_image # self.save() # return self.private_image # # current_blur_ratio = self.public_image_blur_ratio # actual_blur_ratio = float(1.0) - float(btc_received) / self.unlock_value.__float__() # if not current_blur_ratio or fabs(1 - actual_blur_ratio / current_blur_ratio) > 0.1: # # If there is a >10% difference, update the image & the ratio # # This means that images are comprised of 10 steps, 1 being "most blurry" # # and 10 being "completely clear". # self.public_image_blur_ratio = actual_blur_ratio # self.save() # self._generate_public_image() # return self.public_image # # class Meta: # ordering = ['-name'] , which may contain function names, class names, or code. Output only the next line.
ordering = ('-created',)
Continue the code snippet: <|code_start|> self.assertEqual(self.tracks.query.tags, '-ql') self.assertEqual(self.tracks.query.added, expected) def test_new_music_single(self): self.settings['single_track'] = True self.tracks = Music.MHMusic(self.settings, self.push) # Check results expected = r"(Tagging track)\:\s(.*)\nURL\:\n\s{1,4}(.*)\n" self.assertEqual(self.tracks.query.tags, '-sql') self.assertEqual(self.tracks.query.added, expected) def test_music_add_log(self): # Make dummy logfile name = 'test-{0}.log'.format(common.get_test_id()) folder = os.path.join(os.path.dirname(self.conf), 'tmpl') log_file = os.path.join(folder, name) self.tracks.log_file = log_file # Run tests regex = r'Unable to match music files: {0}'.format(escape(self.tmp_file)) self.assertRaisesRegexp( SystemExit, regex, self.tracks.add, self.tmp_file) self.assertTrue(os.path.exists(folder)) # Clean up shutil.rmtree(folder) def test_music_output_good(self): output = """ /Downloaded/Music/Alt-J - This Is All Yours (2014) CD RIP [MP3 @ 320 KBPS] (13 items) Correcting tags from: Alt-J - This Is All Yours <|code_end|> . Use current file imports: import os import shutil import tests.common as common import mediahandler.types.music as Music from re import escape from tests.common import unittest from tests.common import MHTestSuite from tests.test_media import MediaObjectTests from mediahandler.util.config import _find_app and context (classes, functions, or code) from other files: # Path: tests/common.py # class MHTestSuite(unittest.TestSuite): # def setUpSuite(self): # def tearDownSuite(self): # def run(self, result): # def skip_unless_has_mod(module, submodule): # def get_test_id(size=4): # def random_string(size=5): # def temp_file(name=None): # def make_tmp_file(text=None, tdir=None): # def get_conf_file(): # def get_orig_settings(): # def get_settings(conf=None): # def get_types_by_string(): # def get_types_by_id(): # def get_pushover_api(): # def get_pushbullet_api(): # def get_google_api(): # def remove_file(file_path): # # Path: tests/common.py # class MHTestSuite(unittest.TestSuite): # # def setUpSuite(self): # # Back up current config # curr_config = get_conf_file() # backup = '{0}.orig'.format(curr_config) # if not os.path.exists(backup): # shutil.move(curr_config, backup) # # Make new config for testing # Config.make_config() # # def tearDownSuite(self): # # Restore original config # curr_config = get_conf_file() # backup = '{0}.orig'.format(curr_config) # if os.path.exists(backup): # shutil.move(backup, curr_config) # # def run(self, result): # # Before tests # self.setUpSuite() # # Set buffering # result.buffer = True # # Run tests # super(MHTestSuite, self).run(result) # # After tests # self.tearDownSuite() # # Path: tests/test_media.py # class MediaObjectTests(unittest.TestCase): # # def setUp(self): # # Conf # self.conf = common.get_conf_file() # # Set up push object # self.push = Notify.MHPush({ # 'enabled': False, # 'notify_name': '', # 'pushover':{ # 'api_key': common.random_string(), # 'user_key': common.random_string(), # }, # }, True) # # Make temp stuff # self.folder = tempfile.mkdtemp( # dir=os.path.dirname(self.conf)) # self.tmp_file = common.make_tmp_file('.avi') # # Build base settings # self.settings = common.get_settings()['TV'] # self.settings['folder'] = self.folder # # def tearDown(self): # if os.path.exists(self.folder): # shutil.rmtree(self.folder) # if os.path.exists(self.tmp_file): # os.unlink(self.tmp_file) # # Path: mediahandler/util/config.py # def _find_app(settings, app): # """Looks for an installed application in the user's local $PATH. # # Raises an ImportError if the application is not found. # """ # # # Save in settings # name = app['name'].lower() # settings[name] = None # # # Retrieve local paths # split_token = ';' if mh.__iswin__ else ':' # local_paths = os.environ['PATH'].rsplit(split_token) # # # Look for app in local paths # for local_path in local_paths: # path = os.path.join(local_path, app['exec']) # # # If the path exists, store & exit the loop # if os.path.isfile(path): # settings[name] = path # break # # # Try .exe for windows # if mh.__iswin__: # win_path = path + '.exe' # if os.path.isfile(win_path): # settings[name] = win_path # break # # # If app not found, raise ImportError # if settings[name] is None: # error = '{0} application not found'.format(app['name']) # raise ImportError(error) . Output only the next line.
To:
Continue the code snippet: <|code_start|> self.assertEqual(self.tracks.query.tags, '-ql') self.assertEqual(self.tracks.query.added, expected) def test_new_music_single(self): self.settings['single_track'] = True self.tracks = Music.MHMusic(self.settings, self.push) # Check results expected = r"(Tagging track)\:\s(.*)\nURL\:\n\s{1,4}(.*)\n" self.assertEqual(self.tracks.query.tags, '-sql') self.assertEqual(self.tracks.query.added, expected) def test_music_add_log(self): # Make dummy logfile name = 'test-{0}.log'.format(common.get_test_id()) folder = os.path.join(os.path.dirname(self.conf), 'tmpl') log_file = os.path.join(folder, name) self.tracks.log_file = log_file # Run tests regex = r'Unable to match music files: {0}'.format(escape(self.tmp_file)) self.assertRaisesRegexp( SystemExit, regex, self.tracks.add, self.tmp_file) self.assertTrue(os.path.exists(folder)) # Clean up shutil.rmtree(folder) def test_music_output_good(self): output = """ /Downloaded/Music/Alt-J - This Is All Yours (2014) CD RIP [MP3 @ 320 KBPS] (13 items) Correcting tags from: Alt-J - This Is All Yours <|code_end|> . Use current file imports: import os import shutil import tests.common as common import mediahandler.types.music as Music from re import escape from tests.common import unittest from tests.common import MHTestSuite from tests.test_media import MediaObjectTests from mediahandler.util.config import _find_app and context (classes, functions, or code) from other files: # Path: tests/common.py # class MHTestSuite(unittest.TestSuite): # def setUpSuite(self): # def tearDownSuite(self): # def run(self, result): # def skip_unless_has_mod(module, submodule): # def get_test_id(size=4): # def random_string(size=5): # def temp_file(name=None): # def make_tmp_file(text=None, tdir=None): # def get_conf_file(): # def get_orig_settings(): # def get_settings(conf=None): # def get_types_by_string(): # def get_types_by_id(): # def get_pushover_api(): # def get_pushbullet_api(): # def get_google_api(): # def remove_file(file_path): # # Path: tests/common.py # class MHTestSuite(unittest.TestSuite): # # def setUpSuite(self): # # Back up current config # curr_config = get_conf_file() # backup = '{0}.orig'.format(curr_config) # if not os.path.exists(backup): # shutil.move(curr_config, backup) # # Make new config for testing # Config.make_config() # # def tearDownSuite(self): # # Restore original config # curr_config = get_conf_file() # backup = '{0}.orig'.format(curr_config) # if os.path.exists(backup): # shutil.move(backup, curr_config) # # def run(self, result): # # Before tests # self.setUpSuite() # # Set buffering # result.buffer = True # # Run tests # super(MHTestSuite, self).run(result) # # After tests # self.tearDownSuite() # # Path: tests/test_media.py # class MediaObjectTests(unittest.TestCase): # # def setUp(self): # # Conf # self.conf = common.get_conf_file() # # Set up push object # self.push = Notify.MHPush({ # 'enabled': False, # 'notify_name': '', # 'pushover':{ # 'api_key': common.random_string(), # 'user_key': common.random_string(), # }, # }, True) # # Make temp stuff # self.folder = tempfile.mkdtemp( # dir=os.path.dirname(self.conf)) # self.tmp_file = common.make_tmp_file('.avi') # # Build base settings # self.settings = common.get_settings()['TV'] # self.settings['folder'] = self.folder # # def tearDown(self): # if os.path.exists(self.folder): # shutil.rmtree(self.folder) # if os.path.exists(self.tmp_file): # os.unlink(self.tmp_file) # # Path: mediahandler/util/config.py # def _find_app(settings, app): # """Looks for an installed application in the user's local $PATH. # # Raises an ImportError if the application is not found. # """ # # # Save in settings # name = app['name'].lower() # settings[name] = None # # # Retrieve local paths # split_token = ';' if mh.__iswin__ else ':' # local_paths = os.environ['PATH'].rsplit(split_token) # # # Look for app in local paths # for local_path in local_paths: # path = os.path.join(local_path, app['exec']) # # # If the path exists, store & exit the loop # if os.path.isfile(path): # settings[name] = path # break # # # Try .exe for windows # if mh.__iswin__: # win_path = path + '.exe' # if os.path.isfile(win_path): # settings[name] = win_path # break # # # If app not found, raise ImportError # if settings[name] is None: # error = '{0} application not found'.format(app['name']) # raise ImportError(error) . Output only the next line.
To:
Given the following code snippet before the placeholder: <|code_start|> expected = r"(Tagging|To)\:\n\s{1,4}(.*)\nURL\:\n\s{1,4}(.*)\n" self.assertEqual(self.tracks.query.tags, '-ql') self.assertEqual(self.tracks.query.added, expected) def test_new_music_single(self): self.settings['single_track'] = True self.tracks = Music.MHMusic(self.settings, self.push) # Check results expected = r"(Tagging track)\:\s(.*)\nURL\:\n\s{1,4}(.*)\n" self.assertEqual(self.tracks.query.tags, '-sql') self.assertEqual(self.tracks.query.added, expected) def test_music_add_log(self): # Make dummy logfile name = 'test-{0}.log'.format(common.get_test_id()) folder = os.path.join(os.path.dirname(self.conf), 'tmpl') log_file = os.path.join(folder, name) self.tracks.log_file = log_file # Run tests regex = r'Unable to match music files: {0}'.format(escape(self.tmp_file)) self.assertRaisesRegexp( SystemExit, regex, self.tracks.add, self.tmp_file) self.assertTrue(os.path.exists(folder)) # Clean up shutil.rmtree(folder) def test_music_output_good(self): output = """ /Downloaded/Music/Alt-J - This Is All Yours (2014) CD RIP [MP3 @ 320 KBPS] (13 items) Correcting tags from: <|code_end|> , predict the next line using imports from the current file: import os import shutil import tests.common as common import mediahandler.types.music as Music from re import escape from tests.common import unittest from tests.common import MHTestSuite from tests.test_media import MediaObjectTests from mediahandler.util.config import _find_app and context including class names, function names, and sometimes code from other files: # Path: tests/common.py # class MHTestSuite(unittest.TestSuite): # def setUpSuite(self): # def tearDownSuite(self): # def run(self, result): # def skip_unless_has_mod(module, submodule): # def get_test_id(size=4): # def random_string(size=5): # def temp_file(name=None): # def make_tmp_file(text=None, tdir=None): # def get_conf_file(): # def get_orig_settings(): # def get_settings(conf=None): # def get_types_by_string(): # def get_types_by_id(): # def get_pushover_api(): # def get_pushbullet_api(): # def get_google_api(): # def remove_file(file_path): # # Path: tests/common.py # class MHTestSuite(unittest.TestSuite): # # def setUpSuite(self): # # Back up current config # curr_config = get_conf_file() # backup = '{0}.orig'.format(curr_config) # if not os.path.exists(backup): # shutil.move(curr_config, backup) # # Make new config for testing # Config.make_config() # # def tearDownSuite(self): # # Restore original config # curr_config = get_conf_file() # backup = '{0}.orig'.format(curr_config) # if os.path.exists(backup): # shutil.move(backup, curr_config) # # def run(self, result): # # Before tests # self.setUpSuite() # # Set buffering # result.buffer = True # # Run tests # super(MHTestSuite, self).run(result) # # After tests # self.tearDownSuite() # # Path: tests/test_media.py # class MediaObjectTests(unittest.TestCase): # # def setUp(self): # # Conf # self.conf = common.get_conf_file() # # Set up push object # self.push = Notify.MHPush({ # 'enabled': False, # 'notify_name': '', # 'pushover':{ # 'api_key': common.random_string(), # 'user_key': common.random_string(), # }, # }, True) # # Make temp stuff # self.folder = tempfile.mkdtemp( # dir=os.path.dirname(self.conf)) # self.tmp_file = common.make_tmp_file('.avi') # # Build base settings # self.settings = common.get_settings()['TV'] # self.settings['folder'] = self.folder # # def tearDown(self): # if os.path.exists(self.folder): # shutil.rmtree(self.folder) # if os.path.exists(self.tmp_file): # os.unlink(self.tmp_file) # # Path: mediahandler/util/config.py # def _find_app(settings, app): # """Looks for an installed application in the user's local $PATH. # # Raises an ImportError if the application is not found. # """ # # # Save in settings # name = app['name'].lower() # settings[name] = None # # # Retrieve local paths # split_token = ';' if mh.__iswin__ else ':' # local_paths = os.environ['PATH'].rsplit(split_token) # # # Look for app in local paths # for local_path in local_paths: # path = os.path.join(local_path, app['exec']) # # # If the path exists, store & exit the loop # if os.path.isfile(path): # settings[name] = path # break # # # Try .exe for windows # if mh.__iswin__: # win_path = path + '.exe' # if os.path.isfile(win_path): # settings[name] = win_path # break # # # If app not found, raise ImportError # if settings[name] is None: # error = '{0} application not found'.format(app['name']) # raise ImportError(error) . Output only the next line.
Alt-J - This Is All Yours
Continue the code snippet: <|code_start|> self.assertEqual(self.tracks.query.added, expected) def test_new_music_single(self): self.settings['single_track'] = True self.tracks = Music.MHMusic(self.settings, self.push) # Check results expected = r"(Tagging track)\:\s(.*)\nURL\:\n\s{1,4}(.*)\n" self.assertEqual(self.tracks.query.tags, '-sql') self.assertEqual(self.tracks.query.added, expected) def test_music_add_log(self): # Make dummy logfile name = 'test-{0}.log'.format(common.get_test_id()) folder = os.path.join(os.path.dirname(self.conf), 'tmpl') log_file = os.path.join(folder, name) self.tracks.log_file = log_file # Run tests regex = r'Unable to match music files: {0}'.format(escape(self.tmp_file)) self.assertRaisesRegexp( SystemExit, regex, self.tracks.add, self.tmp_file) self.assertTrue(os.path.exists(folder)) # Clean up shutil.rmtree(folder) def test_music_output_good(self): output = """ /Downloaded/Music/Alt-J - This Is All Yours (2014) CD RIP [MP3 @ 320 KBPS] (13 items) Correcting tags from: Alt-J - This Is All Yours To: <|code_end|> . Use current file imports: import os import shutil import tests.common as common import mediahandler.types.music as Music from re import escape from tests.common import unittest from tests.common import MHTestSuite from tests.test_media import MediaObjectTests from mediahandler.util.config import _find_app and context (classes, functions, or code) from other files: # Path: tests/common.py # class MHTestSuite(unittest.TestSuite): # def setUpSuite(self): # def tearDownSuite(self): # def run(self, result): # def skip_unless_has_mod(module, submodule): # def get_test_id(size=4): # def random_string(size=5): # def temp_file(name=None): # def make_tmp_file(text=None, tdir=None): # def get_conf_file(): # def get_orig_settings(): # def get_settings(conf=None): # def get_types_by_string(): # def get_types_by_id(): # def get_pushover_api(): # def get_pushbullet_api(): # def get_google_api(): # def remove_file(file_path): # # Path: tests/common.py # class MHTestSuite(unittest.TestSuite): # # def setUpSuite(self): # # Back up current config # curr_config = get_conf_file() # backup = '{0}.orig'.format(curr_config) # if not os.path.exists(backup): # shutil.move(curr_config, backup) # # Make new config for testing # Config.make_config() # # def tearDownSuite(self): # # Restore original config # curr_config = get_conf_file() # backup = '{0}.orig'.format(curr_config) # if os.path.exists(backup): # shutil.move(backup, curr_config) # # def run(self, result): # # Before tests # self.setUpSuite() # # Set buffering # result.buffer = True # # Run tests # super(MHTestSuite, self).run(result) # # After tests # self.tearDownSuite() # # Path: tests/test_media.py # class MediaObjectTests(unittest.TestCase): # # def setUp(self): # # Conf # self.conf = common.get_conf_file() # # Set up push object # self.push = Notify.MHPush({ # 'enabled': False, # 'notify_name': '', # 'pushover':{ # 'api_key': common.random_string(), # 'user_key': common.random_string(), # }, # }, True) # # Make temp stuff # self.folder = tempfile.mkdtemp( # dir=os.path.dirname(self.conf)) # self.tmp_file = common.make_tmp_file('.avi') # # Build base settings # self.settings = common.get_settings()['TV'] # self.settings['folder'] = self.folder # # def tearDown(self): # if os.path.exists(self.folder): # shutil.rmtree(self.folder) # if os.path.exists(self.tmp_file): # os.unlink(self.tmp_file) # # Path: mediahandler/util/config.py # def _find_app(settings, app): # """Looks for an installed application in the user's local $PATH. # # Raises an ImportError if the application is not found. # """ # # # Save in settings # name = app['name'].lower() # settings[name] = None # # # Retrieve local paths # split_token = ';' if mh.__iswin__ else ':' # local_paths = os.environ['PATH'].rsplit(split_token) # # # Look for app in local paths # for local_path in local_paths: # path = os.path.join(local_path, app['exec']) # # # If the path exists, store & exit the loop # if os.path.isfile(path): # settings[name] = path # break # # # Try .exe for windows # if mh.__iswin__: # win_path = path + '.exe' # if os.path.isfile(win_path): # settings[name] = win_path # break # # # If app not found, raise ImportError # if settings[name] is None: # error = '{0} application not found'.format(app['name']) # raise ImportError(error) . Output only the next line.
alt-J - This Is All Yours
Given the code snippet: <|code_start|>from __future__ import annotations @pytest.fixture def temp_git_dir(tmpdir): <|code_end|> , generate the next line using the imports in this file: import pytest from pre_commit_hooks.util import cmd_output and context (functions, classes, or occasionally code) from other files: # Path: pre_commit_hooks/util.py # def cmd_output(*cmd: str, retcode: int | None = 0, **kwargs: Any) -> str: # kwargs.setdefault('stdout', subprocess.PIPE) # kwargs.setdefault('stderr', subprocess.PIPE) # proc = subprocess.Popen(cmd, **kwargs) # stdout, stderr = proc.communicate() # stdout = stdout.decode() # if retcode is not None and proc.returncode != retcode: # raise CalledProcessError(cmd, retcode, proc.returncode, stdout, stderr) # return stdout . Output only the next line.
git_dir = tmpdir.join('gits')
Next line prediction: <|code_start|> cmd_output('chmod', '+x', f_path) cmd_output('git', 'add', f_path) cmd_output('git', 'update-index', '--chmod=+x', f_path) files = (f_path,) assert _check_git_filemode(files) == 0 def test_check_git_filemode_failing(tmpdir): with tmpdir.as_cwd(): cmd_output('git', 'init', '.') f = tmpdir.join('f').ensure() f.write('#!/usr/bin/env bash') f_path = str(f) cmd_output('git', 'add', f_path) files = (f_path,) assert _check_git_filemode(files) == 1 @pytest.mark.parametrize( ('content', 'mode', 'expected'), ( pytest.param('#!python', '+x', 0, id='shebang with executable'), pytest.param('#!python', '-x', 1, id='shebang without executable'), pytest.param('', '+x', 0, id='no shebang with executable'), pytest.param('', '-x', 0, id='no shebang without executable'), ), ) <|code_end|> . Use current file imports: (import os import pytest from pre_commit_hooks.check_shebang_scripts_are_executable import \ _check_git_filemode from pre_commit_hooks.check_shebang_scripts_are_executable import main from pre_commit_hooks.util import cmd_output) and context including class names, function names, or small code snippets from other files: # Path: pre_commit_hooks/check_shebang_scripts_are_executable.py # def _check_git_filemode(paths: Sequence[str]) -> int: # seen: set[str] = set() # for ls_file in git_ls_files(paths): # is_executable = any(b in EXECUTABLE_VALUES for b in ls_file.mode[-3:]) # if not is_executable and has_shebang(ls_file.filename): # _message(ls_file.filename) # seen.add(ls_file.filename) # # return int(bool(seen)) # # Path: pre_commit_hooks/check_shebang_scripts_are_executable.py # def main(argv: Sequence[str] | None = None) -> int: # parser = argparse.ArgumentParser(description=__doc__) # parser.add_argument('filenames', nargs='*') # args = parser.parse_args(argv) # # return check_shebangs(args.filenames) # # Path: pre_commit_hooks/util.py # def cmd_output(*cmd: str, retcode: int | None = 0, **kwargs: Any) -> str: # kwargs.setdefault('stdout', subprocess.PIPE) # kwargs.setdefault('stderr', subprocess.PIPE) # proc = subprocess.Popen(cmd, **kwargs) # stdout, stderr = proc.communicate() # stdout = stdout.decode() # if retcode is not None and proc.returncode != retcode: # raise CalledProcessError(cmd, retcode, proc.returncode, stdout, stderr) # return stdout . Output only the next line.
def test_git_executable_shebang(temp_git_dir, content, mode, expected):
Based on the snippet: <|code_start|> def test_check_git_filemode_passing(tmpdir): with tmpdir.as_cwd(): cmd_output('git', 'init', '.') f = tmpdir.join('f') f.write('#!/usr/bin/env bash') f_path = str(f) cmd_output('chmod', '+x', f_path) cmd_output('git', 'add', f_path) cmd_output('git', 'update-index', '--chmod=+x', f_path) g = tmpdir.join('g').ensure() g_path = str(g) cmd_output('git', 'add', g_path) files = [f_path, g_path] assert _check_git_filemode(files) == 0 # this is the one we should trigger on h = tmpdir.join('h') h.write('#!/usr/bin/env bash') h_path = str(h) cmd_output('git', 'add', h_path) files = [h_path] assert _check_git_filemode(files) == 1 def test_check_git_filemode_passing_unusual_characters(tmpdir): <|code_end|> , predict the immediate next line with the help of imports: import os import pytest from pre_commit_hooks.check_shebang_scripts_are_executable import \ _check_git_filemode from pre_commit_hooks.check_shebang_scripts_are_executable import main from pre_commit_hooks.util import cmd_output and context (classes, functions, sometimes code) from other files: # Path: pre_commit_hooks/check_shebang_scripts_are_executable.py # def _check_git_filemode(paths: Sequence[str]) -> int: # seen: set[str] = set() # for ls_file in git_ls_files(paths): # is_executable = any(b in EXECUTABLE_VALUES for b in ls_file.mode[-3:]) # if not is_executable and has_shebang(ls_file.filename): # _message(ls_file.filename) # seen.add(ls_file.filename) # # return int(bool(seen)) # # Path: pre_commit_hooks/check_shebang_scripts_are_executable.py # def main(argv: Sequence[str] | None = None) -> int: # parser = argparse.ArgumentParser(description=__doc__) # parser.add_argument('filenames', nargs='*') # args = parser.parse_args(argv) # # return check_shebangs(args.filenames) # # Path: pre_commit_hooks/util.py # def cmd_output(*cmd: str, retcode: int | None = 0, **kwargs: Any) -> str: # kwargs.setdefault('stdout', subprocess.PIPE) # kwargs.setdefault('stderr', subprocess.PIPE) # proc = subprocess.Popen(cmd, **kwargs) # stdout, stderr = proc.communicate() # stdout = stdout.decode() # if retcode is not None and proc.returncode != retcode: # raise CalledProcessError(cmd, retcode, proc.returncode, stdout, stderr) # return stdout . Output only the next line.
with tmpdir.as_cwd():
Continue the code snippet: <|code_start|>from __future__ import annotations def test_check_git_filemode_passing(tmpdir): with tmpdir.as_cwd(): cmd_output('git', 'init', '.') <|code_end|> . Use current file imports: import os import pytest from pre_commit_hooks.check_shebang_scripts_are_executable import \ _check_git_filemode from pre_commit_hooks.check_shebang_scripts_are_executable import main from pre_commit_hooks.util import cmd_output and context (classes, functions, or code) from other files: # Path: pre_commit_hooks/check_shebang_scripts_are_executable.py # def _check_git_filemode(paths: Sequence[str]) -> int: # seen: set[str] = set() # for ls_file in git_ls_files(paths): # is_executable = any(b in EXECUTABLE_VALUES for b in ls_file.mode[-3:]) # if not is_executable and has_shebang(ls_file.filename): # _message(ls_file.filename) # seen.add(ls_file.filename) # # return int(bool(seen)) # # Path: pre_commit_hooks/check_shebang_scripts_are_executable.py # def main(argv: Sequence[str] | None = None) -> int: # parser = argparse.ArgumentParser(description=__doc__) # parser.add_argument('filenames', nargs='*') # args = parser.parse_args(argv) # # return check_shebangs(args.filenames) # # Path: pre_commit_hooks/util.py # def cmd_output(*cmd: str, retcode: int | None = 0, **kwargs: Any) -> str: # kwargs.setdefault('stdout', subprocess.PIPE) # kwargs.setdefault('stderr', subprocess.PIPE) # proc = subprocess.Popen(cmd, **kwargs) # stdout, stderr = proc.communicate() # stdout = stdout.decode() # if retcode is not None and proc.returncode != retcode: # raise CalledProcessError(cmd, retcode, proc.returncode, stdout, stderr) # return stdout . Output only the next line.
f = tmpdir.join('f')
Predict the next line for this snippet: <|code_start|>from __future__ import annotations TESTS = ( # Base cases ("''", "''", 0), <|code_end|> with the help of current file imports: import textwrap import pytest from pre_commit_hooks.string_fixer import main and context from other files: # Path: pre_commit_hooks/string_fixer.py # def main(argv: Sequence[str] | None = None) -> int: # parser = argparse.ArgumentParser() # parser.add_argument('filenames', nargs='*', help='Filenames to fix') # args = parser.parse_args(argv) # # retv = 0 # # for filename in args.filenames: # return_value = fix_strings(filename) # if return_value != 0: # print(f'Fixing strings in {filename}') # retv |= return_value # # return retv , which may contain function names, class names, or code. Output only the next line.
('""', "''", 1),
Predict the next line after this snippet: <|code_start|> 'PRE_COMMIT_TO_REF' in os.environ ): diff_arg = '...'.join(( os.environ['PRE_COMMIT_FROM_REF'], os.environ['PRE_COMMIT_TO_REF'], )) else: diff_arg = '--staged' added_diff = cmd_output( 'git', 'diff', '--diff-filter=A', '--raw', diff_arg, '--', *args.filenames, ) retv = 0 for line in added_diff.splitlines(): metadata, filename = line.split('\t', 1) new_mode = metadata.split(' ')[1] if new_mode == '160000': print(f'{filename}: new submodule introduced') retv = 1 if retv: print() print('This commit introduces new submodules.') print('Did you unintentionally `git add .`?') print('To fix: git rm {thesubmodule} # no trailing slash') print('Also check .gitmodules') return retv <|code_end|> using the current file's imports: import argparse import os from typing import Sequence from pre_commit_hooks.util import cmd_output and any relevant context from other files: # Path: pre_commit_hooks/util.py # def cmd_output(*cmd: str, retcode: int | None = 0, **kwargs: Any) -> str: # kwargs.setdefault('stdout', subprocess.PIPE) # kwargs.setdefault('stderr', subprocess.PIPE) # proc = subprocess.Popen(cmd, **kwargs) # stdout, stderr = proc.communicate() # stdout = stdout.decode() # if retcode is not None and proc.returncode != retcode: # raise CalledProcessError(cmd, retcode, proc.returncode, stdout, stderr) # return stdout . Output only the next line.
if __name__ == '__main__':
Based on the snippet: <|code_start|>from __future__ import annotations def test_failure(tmpdir): f = tmpdir.join('f.txt') f.write_text('ohai', encoding='utf-8-sig') assert fix_byte_order_marker.main((str(f),)) == 1 def test_success(tmpdir): f = tmpdir.join('f.txt') <|code_end|> , predict the immediate next line with the help of imports: from pre_commit_hooks import fix_byte_order_marker and context (classes, functions, sometimes code) from other files: # Path: pre_commit_hooks/fix_byte_order_marker.py # def main(argv: Sequence[str] | None = None) -> int: . Output only the next line.
f.write_text('ohai', encoding='utf-8')
Given snippet: <|code_start|> temp_git_dir.mkdir('dir').join('x').write('foo') temp_git_dir.join('DIR').write('foo') cmd_output('git', 'add', '-A') assert find_conflicting_filenames([]) == 1 def test_added_file_not_in_pre_commits_list(temp_git_dir): with temp_git_dir.as_cwd(): temp_git_dir.join('f.py').write("print('hello world')") cmd_output('git', 'add', 'f.py') assert find_conflicting_filenames(['g.py']) == 0 def test_file_conflicts_with_committed_file(temp_git_dir): with temp_git_dir.as_cwd(): temp_git_dir.join('f.py').write("print('hello world')") cmd_output('git', 'add', 'f.py') git_commit('-m', 'Add f.py') temp_git_dir.join('F.py').write("print('hello world')") cmd_output('git', 'add', 'F.py') assert find_conflicting_filenames(['F.py']) == 1 @skip_win32 # pragma: win32 no cover def test_file_conflicts_with_committed_dir(temp_git_dir): with temp_git_dir.as_cwd(): <|code_end|> , continue by predicting the next line. Consider current file imports: import sys import pytest from pre_commit_hooks.check_case_conflict import find_conflicting_filenames from pre_commit_hooks.check_case_conflict import main from pre_commit_hooks.check_case_conflict import parents from pre_commit_hooks.util import cmd_output from testing.util import git_commit and context: # Path: pre_commit_hooks/check_case_conflict.py # def find_conflicting_filenames(filenames: Sequence[str]) -> int: # repo_files = set(cmd_output('git', 'ls-files').splitlines()) # repo_files |= directories_for(repo_files) # relevant_files = set(filenames) | added_files() # relevant_files |= directories_for(relevant_files) # repo_files -= relevant_files # retv = 0 # # # new file conflicts with existing file # conflicts = lower_set(repo_files) & lower_set(relevant_files) # # # new file conflicts with other new file # lowercase_relevant_files = lower_set(relevant_files) # for filename in set(relevant_files): # if filename.lower() in lowercase_relevant_files: # lowercase_relevant_files.remove(filename.lower()) # else: # conflicts.add(filename.lower()) # # if conflicts: # conflicting_files = [ # x for x in repo_files | relevant_files # if x.lower() in conflicts # ] # for filename in sorted(conflicting_files): # print(f'Case-insensitivity conflict found: {filename}') # retv = 1 # # return retv # # Path: pre_commit_hooks/check_case_conflict.py # def main(argv: Sequence[str] | None = None) -> int: # parser = argparse.ArgumentParser() # parser.add_argument( # 'filenames', nargs='*', # help='Filenames pre-commit believes are changed.', # ) # # args = parser.parse_args(argv) # # return find_conflicting_filenames(args.filenames) # # Path: pre_commit_hooks/check_case_conflict.py # def parents(file: str) -> Iterator[str]: # path_parts = file.split('/') # path_parts.pop() # while path_parts: # yield '/'.join(path_parts) # path_parts.pop() # # Path: pre_commit_hooks/util.py # def cmd_output(*cmd: str, retcode: int | None = 0, **kwargs: Any) -> str: # kwargs.setdefault('stdout', subprocess.PIPE) # kwargs.setdefault('stderr', subprocess.PIPE) # proc = subprocess.Popen(cmd, **kwargs) # stdout, stderr = proc.communicate() # stdout = stdout.decode() # if retcode is not None and proc.returncode != retcode: # raise CalledProcessError(cmd, retcode, proc.returncode, stdout, stderr) # return stdout # # Path: testing/util.py # def git_commit(*args, **kwargs): # cmd = ('git', 'commit', '--no-gpg-sign', '--no-verify', '--no-edit', *args) # subprocess.check_call(cmd, **kwargs) which might include code, classes, or functions. Output only the next line.
temp_git_dir.mkdir('dir').join('x').write('foo')
Next line prediction: <|code_start|> temp_git_dir.join('f.py').write("print('hello world')") cmd_output('git', 'add', 'f.py') assert find_conflicting_filenames(['f.py']) == 0 def test_adding_something_with_conflict(temp_git_dir): with temp_git_dir.as_cwd(): temp_git_dir.join('f.py').write("print('hello world')") cmd_output('git', 'add', 'f.py') temp_git_dir.join('F.py').write("print('hello world')") cmd_output('git', 'add', 'F.py') assert find_conflicting_filenames(['f.py', 'F.py']) == 1 @skip_win32 # pragma: win32 no cover def test_adding_files_with_conflicting_directories(temp_git_dir): with temp_git_dir.as_cwd(): temp_git_dir.mkdir('dir').join('x').write('foo') temp_git_dir.mkdir('DIR').join('y').write('foo') cmd_output('git', 'add', '-A') assert find_conflicting_filenames([]) == 1 @skip_win32 # pragma: win32 no cover def test_adding_files_with_conflicting_deep_directories(temp_git_dir): with temp_git_dir.as_cwd(): temp_git_dir.mkdir('x').mkdir('y').join('z').write('foo') <|code_end|> . Use current file imports: (import sys import pytest from pre_commit_hooks.check_case_conflict import find_conflicting_filenames from pre_commit_hooks.check_case_conflict import main from pre_commit_hooks.check_case_conflict import parents from pre_commit_hooks.util import cmd_output from testing.util import git_commit) and context including class names, function names, or small code snippets from other files: # Path: pre_commit_hooks/check_case_conflict.py # def find_conflicting_filenames(filenames: Sequence[str]) -> int: # repo_files = set(cmd_output('git', 'ls-files').splitlines()) # repo_files |= directories_for(repo_files) # relevant_files = set(filenames) | added_files() # relevant_files |= directories_for(relevant_files) # repo_files -= relevant_files # retv = 0 # # # new file conflicts with existing file # conflicts = lower_set(repo_files) & lower_set(relevant_files) # # # new file conflicts with other new file # lowercase_relevant_files = lower_set(relevant_files) # for filename in set(relevant_files): # if filename.lower() in lowercase_relevant_files: # lowercase_relevant_files.remove(filename.lower()) # else: # conflicts.add(filename.lower()) # # if conflicts: # conflicting_files = [ # x for x in repo_files | relevant_files # if x.lower() in conflicts # ] # for filename in sorted(conflicting_files): # print(f'Case-insensitivity conflict found: {filename}') # retv = 1 # # return retv # # Path: pre_commit_hooks/check_case_conflict.py # def main(argv: Sequence[str] | None = None) -> int: # parser = argparse.ArgumentParser() # parser.add_argument( # 'filenames', nargs='*', # help='Filenames pre-commit believes are changed.', # ) # # args = parser.parse_args(argv) # # return find_conflicting_filenames(args.filenames) # # Path: pre_commit_hooks/check_case_conflict.py # def parents(file: str) -> Iterator[str]: # path_parts = file.split('/') # path_parts.pop() # while path_parts: # yield '/'.join(path_parts) # path_parts.pop() # # Path: pre_commit_hooks/util.py # def cmd_output(*cmd: str, retcode: int | None = 0, **kwargs: Any) -> str: # kwargs.setdefault('stdout', subprocess.PIPE) # kwargs.setdefault('stderr', subprocess.PIPE) # proc = subprocess.Popen(cmd, **kwargs) # stdout, stderr = proc.communicate() # stdout = stdout.decode() # if retcode is not None and proc.returncode != retcode: # raise CalledProcessError(cmd, retcode, proc.returncode, stdout, stderr) # return stdout # # Path: testing/util.py # def git_commit(*args, **kwargs): # cmd = ('git', 'commit', '--no-gpg-sign', '--no-verify', '--no-edit', *args) # subprocess.check_call(cmd, **kwargs) . Output only the next line.
temp_git_dir.join('X').write('foo')
Using the snippet: <|code_start|> @skip_win32 # pragma: win32 no cover def test_adding_files_with_conflicting_deep_directories(temp_git_dir): with temp_git_dir.as_cwd(): temp_git_dir.mkdir('x').mkdir('y').join('z').write('foo') temp_git_dir.join('X').write('foo') cmd_output('git', 'add', '-A') assert find_conflicting_filenames([]) == 1 @skip_win32 # pragma: win32 no cover def test_adding_file_with_conflicting_directory(temp_git_dir): with temp_git_dir.as_cwd(): temp_git_dir.mkdir('dir').join('x').write('foo') temp_git_dir.join('DIR').write('foo') cmd_output('git', 'add', '-A') assert find_conflicting_filenames([]) == 1 def test_added_file_not_in_pre_commits_list(temp_git_dir): with temp_git_dir.as_cwd(): temp_git_dir.join('f.py').write("print('hello world')") cmd_output('git', 'add', 'f.py') assert find_conflicting_filenames(['g.py']) == 0 <|code_end|> , determine the next line of code. You have imports: import sys import pytest from pre_commit_hooks.check_case_conflict import find_conflicting_filenames from pre_commit_hooks.check_case_conflict import main from pre_commit_hooks.check_case_conflict import parents from pre_commit_hooks.util import cmd_output from testing.util import git_commit and context (class names, function names, or code) available: # Path: pre_commit_hooks/check_case_conflict.py # def find_conflicting_filenames(filenames: Sequence[str]) -> int: # repo_files = set(cmd_output('git', 'ls-files').splitlines()) # repo_files |= directories_for(repo_files) # relevant_files = set(filenames) | added_files() # relevant_files |= directories_for(relevant_files) # repo_files -= relevant_files # retv = 0 # # # new file conflicts with existing file # conflicts = lower_set(repo_files) & lower_set(relevant_files) # # # new file conflicts with other new file # lowercase_relevant_files = lower_set(relevant_files) # for filename in set(relevant_files): # if filename.lower() in lowercase_relevant_files: # lowercase_relevant_files.remove(filename.lower()) # else: # conflicts.add(filename.lower()) # # if conflicts: # conflicting_files = [ # x for x in repo_files | relevant_files # if x.lower() in conflicts # ] # for filename in sorted(conflicting_files): # print(f'Case-insensitivity conflict found: {filename}') # retv = 1 # # return retv # # Path: pre_commit_hooks/check_case_conflict.py # def main(argv: Sequence[str] | None = None) -> int: # parser = argparse.ArgumentParser() # parser.add_argument( # 'filenames', nargs='*', # help='Filenames pre-commit believes are changed.', # ) # # args = parser.parse_args(argv) # # return find_conflicting_filenames(args.filenames) # # Path: pre_commit_hooks/check_case_conflict.py # def parents(file: str) -> Iterator[str]: # path_parts = file.split('/') # path_parts.pop() # while path_parts: # yield '/'.join(path_parts) # path_parts.pop() # # Path: pre_commit_hooks/util.py # def cmd_output(*cmd: str, retcode: int | None = 0, **kwargs: Any) -> str: # kwargs.setdefault('stdout', subprocess.PIPE) # kwargs.setdefault('stderr', subprocess.PIPE) # proc = subprocess.Popen(cmd, **kwargs) # stdout, stderr = proc.communicate() # stdout = stdout.decode() # if retcode is not None and proc.returncode != retcode: # raise CalledProcessError(cmd, retcode, proc.returncode, stdout, stderr) # return stdout # # Path: testing/util.py # def git_commit(*args, **kwargs): # cmd = ('git', 'commit', '--no-gpg-sign', '--no-verify', '--no-edit', *args) # subprocess.check_call(cmd, **kwargs) . Output only the next line.
def test_file_conflicts_with_committed_file(temp_git_dir):
Using the snippet: <|code_start|> temp_git_dir.join('X').write('foo') cmd_output('git', 'add', '-A') assert find_conflicting_filenames([]) == 1 @skip_win32 # pragma: win32 no cover def test_adding_file_with_conflicting_directory(temp_git_dir): with temp_git_dir.as_cwd(): temp_git_dir.mkdir('dir').join('x').write('foo') temp_git_dir.join('DIR').write('foo') cmd_output('git', 'add', '-A') assert find_conflicting_filenames([]) == 1 def test_added_file_not_in_pre_commits_list(temp_git_dir): with temp_git_dir.as_cwd(): temp_git_dir.join('f.py').write("print('hello world')") cmd_output('git', 'add', 'f.py') assert find_conflicting_filenames(['g.py']) == 0 def test_file_conflicts_with_committed_file(temp_git_dir): with temp_git_dir.as_cwd(): temp_git_dir.join('f.py').write("print('hello world')") cmd_output('git', 'add', 'f.py') git_commit('-m', 'Add f.py') <|code_end|> , determine the next line of code. You have imports: import sys import pytest from pre_commit_hooks.check_case_conflict import find_conflicting_filenames from pre_commit_hooks.check_case_conflict import main from pre_commit_hooks.check_case_conflict import parents from pre_commit_hooks.util import cmd_output from testing.util import git_commit and context (class names, function names, or code) available: # Path: pre_commit_hooks/check_case_conflict.py # def find_conflicting_filenames(filenames: Sequence[str]) -> int: # repo_files = set(cmd_output('git', 'ls-files').splitlines()) # repo_files |= directories_for(repo_files) # relevant_files = set(filenames) | added_files() # relevant_files |= directories_for(relevant_files) # repo_files -= relevant_files # retv = 0 # # # new file conflicts with existing file # conflicts = lower_set(repo_files) & lower_set(relevant_files) # # # new file conflicts with other new file # lowercase_relevant_files = lower_set(relevant_files) # for filename in set(relevant_files): # if filename.lower() in lowercase_relevant_files: # lowercase_relevant_files.remove(filename.lower()) # else: # conflicts.add(filename.lower()) # # if conflicts: # conflicting_files = [ # x for x in repo_files | relevant_files # if x.lower() in conflicts # ] # for filename in sorted(conflicting_files): # print(f'Case-insensitivity conflict found: {filename}') # retv = 1 # # return retv # # Path: pre_commit_hooks/check_case_conflict.py # def main(argv: Sequence[str] | None = None) -> int: # parser = argparse.ArgumentParser() # parser.add_argument( # 'filenames', nargs='*', # help='Filenames pre-commit believes are changed.', # ) # # args = parser.parse_args(argv) # # return find_conflicting_filenames(args.filenames) # # Path: pre_commit_hooks/check_case_conflict.py # def parents(file: str) -> Iterator[str]: # path_parts = file.split('/') # path_parts.pop() # while path_parts: # yield '/'.join(path_parts) # path_parts.pop() # # Path: pre_commit_hooks/util.py # def cmd_output(*cmd: str, retcode: int | None = 0, **kwargs: Any) -> str: # kwargs.setdefault('stdout', subprocess.PIPE) # kwargs.setdefault('stderr', subprocess.PIPE) # proc = subprocess.Popen(cmd, **kwargs) # stdout, stderr = proc.communicate() # stdout = stdout.decode() # if retcode is not None and proc.returncode != retcode: # raise CalledProcessError(cmd, retcode, proc.returncode, stdout, stderr) # return stdout # # Path: testing/util.py # def git_commit(*args, **kwargs): # cmd = ('git', 'commit', '--no-gpg-sign', '--no-verify', '--no-edit', *args) # subprocess.check_call(cmd, **kwargs) . Output only the next line.
temp_git_dir.join('F.py').write("print('hello world')")
Here is a snippet: <|code_start|> TEST_SYMLINK = 'test_symlink' TEST_SYMLINK_TARGET = '/doesnt/really/matters' TEST_FILE = 'test_file' TEST_FILE_RENAMED = f'{TEST_FILE}_renamed' @pytest.fixture def repo_with_destroyed_symlink(tmpdir): source_repo = tmpdir.join('src') os.makedirs(source_repo, exist_ok=True) test_repo = tmpdir.join('test') with source_repo.as_cwd(): subprocess.check_call(('git', 'init')) os.symlink(TEST_SYMLINK_TARGET, TEST_SYMLINK) with open(TEST_FILE, 'w') as f: print('some random content', file=f) subprocess.check_call(('git', 'add', '.')) git_commit('-m', 'initial') assert b'120000 ' in subprocess.check_output( ('git', 'cat-file', '-p', 'HEAD^{tree}'), ) subprocess.check_call( ('git', '-c', 'core.symlinks=false', 'clone', source_repo, test_repo), ) with test_repo.as_cwd(): subprocess.check_call( ('git', 'config', '--local', 'core.symlinks', 'true'), ) subprocess.check_call(('git', 'mv', TEST_FILE, TEST_FILE_RENAMED)) <|code_end|> . Write the next line using the current file imports: import os import subprocess import pytest from pre_commit_hooks.destroyed_symlinks import find_destroyed_symlinks from pre_commit_hooks.destroyed_symlinks import main from testing.util import git_commit and context from other files: # Path: pre_commit_hooks/destroyed_symlinks.py # def find_destroyed_symlinks(files: Sequence[str]) -> list[str]: # destroyed_links: list[str] = [] # if not files: # return destroyed_links # for line in zsplit( # cmd_output('git', 'status', '--porcelain=v2', '-z', '--', *files), # ): # splitted = line.split(' ') # if splitted and splitted[0] == ORDINARY_CHANGED_ENTRIES_MARKER: # # https://git-scm.com/docs/git-status#_changed_tracked_entries # ( # _, _, _, # mode_HEAD, # mode_index, # _, # hash_HEAD, # hash_index, # *path_splitted, # ) = splitted # path = ' '.join(path_splitted) # if ( # mode_HEAD == PERMS_LINK and # mode_index != PERMS_LINK and # mode_index != PERMS_NONEXIST # ): # if hash_HEAD == hash_index: # # if old and new hashes are equal, it's not needed to check # # anything more, we've found a destroyed symlink for sure # destroyed_links.append(path) # else: # # if old and new hashes are *not* equal, it doesn't mean # # that everything is OK - new file may be altered # # by something like trailing-whitespace and/or # # mixed-line-ending hooks so we need to go deeper # SIZE_CMD = ('git', 'cat-file', '-s') # size_index = int(cmd_output(*SIZE_CMD, hash_index).strip()) # size_HEAD = int(cmd_output(*SIZE_CMD, hash_HEAD).strip()) # # # in the worst case new file may have CRLF added # # so check content only if new file is bigger # # not more than 2 bytes compared to the old one # if size_index <= size_HEAD + 2: # head_content = subprocess.check_output( # ('git', 'cat-file', '-p', hash_HEAD), # ).rstrip() # index_content = subprocess.check_output( # ('git', 'cat-file', '-p', hash_index), # ).rstrip() # if head_content == index_content: # destroyed_links.append(path) # return destroyed_links # # Path: pre_commit_hooks/destroyed_symlinks.py # def main(argv: Sequence[str] | None = None) -> int: # parser = argparse.ArgumentParser() # parser.add_argument('filenames', nargs='*', help='Filenames to check.') # args = parser.parse_args(argv) # destroyed_links = find_destroyed_symlinks(files=args.filenames) # if destroyed_links: # print('Destroyed symlinks:') # for destroyed_link in destroyed_links: # print(f'- {destroyed_link}') # print('You should unstage affected files:') # print( # '\tgit reset HEAD -- {}'.format( # ' '.join(shlex.quote(link) for link in destroyed_links), # ), # ) # print( # 'And retry commit. As a long term solution ' # 'you may try to explicitly tell git that your ' # 'environment does not support symlinks:', # ) # print('\tgit config core.symlinks false') # return 1 # else: # return 0 # # Path: testing/util.py # def git_commit(*args, **kwargs): # cmd = ('git', 'commit', '--no-gpg-sign', '--no-verify', '--no-edit', *args) # subprocess.check_call(cmd, **kwargs) , which may include functions, classes, or code. Output only the next line.
assert not os.path.islink(test_repo.join(TEST_SYMLINK))
Predict the next line after this snippet: <|code_start|>from __future__ import annotations TEST_SYMLINK = 'test_symlink' TEST_SYMLINK_TARGET = '/doesnt/really/matters' TEST_FILE = 'test_file' TEST_FILE_RENAMED = f'{TEST_FILE}_renamed' @pytest.fixture def repo_with_destroyed_symlink(tmpdir): source_repo = tmpdir.join('src') os.makedirs(source_repo, exist_ok=True) test_repo = tmpdir.join('test') with source_repo.as_cwd(): subprocess.check_call(('git', 'init')) <|code_end|> using the current file's imports: import os import subprocess import pytest from pre_commit_hooks.destroyed_symlinks import find_destroyed_symlinks from pre_commit_hooks.destroyed_symlinks import main from testing.util import git_commit and any relevant context from other files: # Path: pre_commit_hooks/destroyed_symlinks.py # def find_destroyed_symlinks(files: Sequence[str]) -> list[str]: # destroyed_links: list[str] = [] # if not files: # return destroyed_links # for line in zsplit( # cmd_output('git', 'status', '--porcelain=v2', '-z', '--', *files), # ): # splitted = line.split(' ') # if splitted and splitted[0] == ORDINARY_CHANGED_ENTRIES_MARKER: # # https://git-scm.com/docs/git-status#_changed_tracked_entries # ( # _, _, _, # mode_HEAD, # mode_index, # _, # hash_HEAD, # hash_index, # *path_splitted, # ) = splitted # path = ' '.join(path_splitted) # if ( # mode_HEAD == PERMS_LINK and # mode_index != PERMS_LINK and # mode_index != PERMS_NONEXIST # ): # if hash_HEAD == hash_index: # # if old and new hashes are equal, it's not needed to check # # anything more, we've found a destroyed symlink for sure # destroyed_links.append(path) # else: # # if old and new hashes are *not* equal, it doesn't mean # # that everything is OK - new file may be altered # # by something like trailing-whitespace and/or # # mixed-line-ending hooks so we need to go deeper # SIZE_CMD = ('git', 'cat-file', '-s') # size_index = int(cmd_output(*SIZE_CMD, hash_index).strip()) # size_HEAD = int(cmd_output(*SIZE_CMD, hash_HEAD).strip()) # # # in the worst case new file may have CRLF added # # so check content only if new file is bigger # # not more than 2 bytes compared to the old one # if size_index <= size_HEAD + 2: # head_content = subprocess.check_output( # ('git', 'cat-file', '-p', hash_HEAD), # ).rstrip() # index_content = subprocess.check_output( # ('git', 'cat-file', '-p', hash_index), # ).rstrip() # if head_content == index_content: # destroyed_links.append(path) # return destroyed_links # # Path: pre_commit_hooks/destroyed_symlinks.py # def main(argv: Sequence[str] | None = None) -> int: # parser = argparse.ArgumentParser() # parser.add_argument('filenames', nargs='*', help='Filenames to check.') # args = parser.parse_args(argv) # destroyed_links = find_destroyed_symlinks(files=args.filenames) # if destroyed_links: # print('Destroyed symlinks:') # for destroyed_link in destroyed_links: # print(f'- {destroyed_link}') # print('You should unstage affected files:') # print( # '\tgit reset HEAD -- {}'.format( # ' '.join(shlex.quote(link) for link in destroyed_links), # ), # ) # print( # 'And retry commit. As a long term solution ' # 'you may try to explicitly tell git that your ' # 'environment does not support symlinks:', # ) # print('\tgit config core.symlinks false') # return 1 # else: # return 0 # # Path: testing/util.py # def git_commit(*args, **kwargs): # cmd = ('git', 'commit', '--no-gpg-sign', '--no-verify', '--no-edit', *args) # subprocess.check_call(cmd, **kwargs) . Output only the next line.
os.symlink(TEST_SYMLINK_TARGET, TEST_SYMLINK)
Continue the code snippet: <|code_start|>from __future__ import annotations TEST_SYMLINK = 'test_symlink' TEST_SYMLINK_TARGET = '/doesnt/really/matters' TEST_FILE = 'test_file' TEST_FILE_RENAMED = f'{TEST_FILE}_renamed' @pytest.fixture def repo_with_destroyed_symlink(tmpdir): source_repo = tmpdir.join('src') os.makedirs(source_repo, exist_ok=True) test_repo = tmpdir.join('test') <|code_end|> . Use current file imports: import os import subprocess import pytest from pre_commit_hooks.destroyed_symlinks import find_destroyed_symlinks from pre_commit_hooks.destroyed_symlinks import main from testing.util import git_commit and context (classes, functions, or code) from other files: # Path: pre_commit_hooks/destroyed_symlinks.py # def find_destroyed_symlinks(files: Sequence[str]) -> list[str]: # destroyed_links: list[str] = [] # if not files: # return destroyed_links # for line in zsplit( # cmd_output('git', 'status', '--porcelain=v2', '-z', '--', *files), # ): # splitted = line.split(' ') # if splitted and splitted[0] == ORDINARY_CHANGED_ENTRIES_MARKER: # # https://git-scm.com/docs/git-status#_changed_tracked_entries # ( # _, _, _, # mode_HEAD, # mode_index, # _, # hash_HEAD, # hash_index, # *path_splitted, # ) = splitted # path = ' '.join(path_splitted) # if ( # mode_HEAD == PERMS_LINK and # mode_index != PERMS_LINK and # mode_index != PERMS_NONEXIST # ): # if hash_HEAD == hash_index: # # if old and new hashes are equal, it's not needed to check # # anything more, we've found a destroyed symlink for sure # destroyed_links.append(path) # else: # # if old and new hashes are *not* equal, it doesn't mean # # that everything is OK - new file may be altered # # by something like trailing-whitespace and/or # # mixed-line-ending hooks so we need to go deeper # SIZE_CMD = ('git', 'cat-file', '-s') # size_index = int(cmd_output(*SIZE_CMD, hash_index).strip()) # size_HEAD = int(cmd_output(*SIZE_CMD, hash_HEAD).strip()) # # # in the worst case new file may have CRLF added # # so check content only if new file is bigger # # not more than 2 bytes compared to the old one # if size_index <= size_HEAD + 2: # head_content = subprocess.check_output( # ('git', 'cat-file', '-p', hash_HEAD), # ).rstrip() # index_content = subprocess.check_output( # ('git', 'cat-file', '-p', hash_index), # ).rstrip() # if head_content == index_content: # destroyed_links.append(path) # return destroyed_links # # Path: pre_commit_hooks/destroyed_symlinks.py # def main(argv: Sequence[str] | None = None) -> int: # parser = argparse.ArgumentParser() # parser.add_argument('filenames', nargs='*', help='Filenames to check.') # args = parser.parse_args(argv) # destroyed_links = find_destroyed_symlinks(files=args.filenames) # if destroyed_links: # print('Destroyed symlinks:') # for destroyed_link in destroyed_links: # print(f'- {destroyed_link}') # print('You should unstage affected files:') # print( # '\tgit reset HEAD -- {}'.format( # ' '.join(shlex.quote(link) for link in destroyed_links), # ), # ) # print( # 'And retry commit. As a long term solution ' # 'you may try to explicitly tell git that your ' # 'environment does not support symlinks:', # ) # print('\tgit config core.symlinks false') # return 1 # else: # return 0 # # Path: testing/util.py # def git_commit(*args, **kwargs): # cmd = ('git', 'commit', '--no-gpg-sign', '--no-verify', '--no-edit', *args) # subprocess.check_call(cmd, **kwargs) . Output only the next line.
with source_repo.as_cwd():
Predict the next line after this snippet: <|code_start|> '{filename}:3 Module docstring appears after code ' '(code seen on line 1).\n', ), # String literals in expressions are ok. (b'x = "foo"\n', 0, ''), ) all_tests = pytest.mark.parametrize( ('contents', 'expected', 'expected_out'), TESTS, ) @all_tests def test_unit(capsys, contents, expected, expected_out): assert check_docstring_first(contents) == expected assert capsys.readouterr()[0] == expected_out.format(filename='<unknown>') @all_tests def test_integration(tmpdir, capsys, contents, expected, expected_out): f = tmpdir.join('test.py') f.write_binary(contents) assert main([str(f)]) == expected assert capsys.readouterr()[0] == expected_out.format(filename=str(f)) def test_arbitrary_encoding(tmpdir): f = tmpdir.join('f.py') contents = '# -*- coding: cp1252\nx = "£"'.encode('cp1252') <|code_end|> using the current file's imports: import pytest from pre_commit_hooks.check_docstring_first import check_docstring_first from pre_commit_hooks.check_docstring_first import main and any relevant context from other files: # Path: pre_commit_hooks/check_docstring_first.py # def check_docstring_first(src: bytes, filename: str = '<unknown>') -> int: # """Returns nonzero if the source has what looks like a docstring that is # not at the beginning of the source. # # A string will be considered a docstring if it is a STRING token with a # col offset of 0. # """ # found_docstring_line = None # found_code_line = None # # tok_gen = tokenize_tokenize(io.BytesIO(src).readline) # for tok_type, _, (sline, scol), _, _ in tok_gen: # # Looks like a docstring! # if tok_type == tokenize.STRING and scol == 0: # if found_docstring_line is not None: # print( # f'{filename}:{sline} Multiple module docstrings ' # f'(first docstring on line {found_docstring_line}).', # ) # return 1 # elif found_code_line is not None: # print( # f'{filename}:{sline} Module docstring appears after code ' # f'(code seen on line {found_code_line}).', # ) # return 1 # else: # found_docstring_line = sline # elif tok_type not in NON_CODE_TOKENS and found_code_line is None: # found_code_line = sline # # return 0 # # Path: pre_commit_hooks/check_docstring_first.py # def main(argv: Sequence[str] | None = None) -> int: # parser = argparse.ArgumentParser() # parser.add_argument('filenames', nargs='*') # args = parser.parse_args(argv) # # retv = 0 # # for filename in args.filenames: # with open(filename, 'rb') as f: # contents = f.read() # retv |= check_docstring_first(contents, filename=filename) # # return retv . Output only the next line.
f.write_binary(contents)
Here is a snippet: <|code_start|>from __future__ import annotations @pytest.mark.parametrize( ('filename', 'expected_retval'), ( ('bad_json.notjson', 1), ('bad_json_latin1.nonjson', 1), ('ok_json.json', 0), ('duplicate_key_json.notjson', 1), ), <|code_end|> . Write the next line using the current file imports: import pytest from pre_commit_hooks.check_json import main from testing.util import get_resource_path and context from other files: # Path: pre_commit_hooks/check_json.py # def main(argv: Sequence[str] | None = None) -> int: # parser = argparse.ArgumentParser() # parser.add_argument('filenames', nargs='*', help='Filenames to check.') # args = parser.parse_args(argv) # # retval = 0 # for filename in args.filenames: # with open(filename, 'rb') as f: # try: # json.load(f, object_pairs_hook=raise_duplicate_keys) # except ValueError as exc: # print(f'{filename}: Failed to json decode ({exc})') # retval = 1 # return retval # # Path: testing/util.py # def get_resource_path(path): # return os.path.join(TESTING_DIR, 'resources', path) , which may include functions, classes, or code. Output only the next line.
)
Based on the snippet: <|code_start|>from __future__ import annotations @pytest.mark.parametrize( ('filename', 'expected_retval'), ( ('bad_json.notjson', 1), ('bad_json_latin1.nonjson', 1), ('ok_json.json', 0), ('duplicate_key_json.notjson', 1), ), ) def test_main(capsys, filename, expected_retval): ret = main([get_resource_path(filename)]) assert ret == expected_retval if expected_retval == 1: stdout, _ = capsys.readouterr() assert filename in stdout <|code_end|> , predict the immediate next line with the help of imports: import pytest from pre_commit_hooks.check_json import main from testing.util import get_resource_path and context (classes, functions, sometimes code) from other files: # Path: pre_commit_hooks/check_json.py # def main(argv: Sequence[str] | None = None) -> int: # parser = argparse.ArgumentParser() # parser.add_argument('filenames', nargs='*', help='Filenames to check.') # args = parser.parse_args(argv) # # retval = 0 # for filename in args.filenames: # with open(filename, 'rb') as f: # try: # json.load(f, object_pairs_hook=raise_duplicate_keys) # except ValueError as exc: # print(f'{filename}: Failed to json decode ({exc})') # retval = 1 # return retval # # Path: testing/util.py # def get_resource_path(path): # return os.path.join(TESTING_DIR, 'resources', path) . Output only the next line.
def test_non_utf8_file(tmpdir):