Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Predict the next line for this snippet: <|code_start|> # mixed type, such as L, GL, GF, because the backoff # involves getting just the first ORDER words ... for index, count in data.iteritems(): #gramm = index.split('/') # order == 1 still gives us a tuple for now! cut_index = index[:order] self.counts[cut_index] += count if order == 1: lexicon.add(cut_index) self.n += 1 self.v = len(lexicon) def _logprob(self, ngram): return math.log(self._prob(ngram)) def _prob(self, ngram): if self.backoff is not None: freq = self.counts[ngram] backoff_freq = self.backoff.counts[ngram[1:]] if freq == 0: return self.alpha * self.backoff._prob(ngram[1:]) else: return freq / backoff_freq else: # laplace smoothing to handle unknown unigrams return (self.counts[ngram] + 1) / (self.n + self.v) class MultiModel(dict): def __init__(self, data, order, name='', **kwargs): <|code_end|> with the help of current file imports: import math import os import os import pandas as pd import pandas as pd import os from nltk import ngrams, sent_tokenize, word_tokenize from corpkit.constants import PYTHON_VERSION, STRINGTYPE from collections import Counter from corpkit.other import load from collections import Counter, OrderedDict from corpkit.corpus import Subcorpus, File from pandas import DataFrame, Series from corpkit.other import load from corpkit.other import save and context from other files: # Path: corpkit/constants.py # PYTHON_VERSION = sys.version_info.major # # STRINGTYPE = str if PYTHON_VERSION == 3 else basestring , which may contain function names, class names, or code. Output only the next line.
if isinstance(data, STRINGTYPE):
Next line prediction: <|code_start|> """ Stores results of a corpus interrogation, before or after editing. The main attribute, :py:attr:`~corpkit.interrogation.Interrogation.results`, is a Pandas object, which can be edited or plotted. """ def __init__(self, results=None, totals=None, query=None, concordance=None): """Initialise the class""" self.results = results """pandas `DataFrame` containing counts for each subcorpus""" self.totals = totals """pandas `Series` containing summed results""" self.query = query """`dict` containing values that generated the result""" self.concordance = concordance """pandas `DataFrame` containing concordance lines, if concordance lines were requested.""" def __str__(self): if self.query.get('corpus'): prst = getattr(self.query['corpus'], 'name', self.query['corpus']) else: try: prst = self.query['interrogation'].query['corpus'].name except: prst = 'edited' st = 'Corpus interrogation: %s\n\n' % (prst) return st def __repr__(self): try: <|code_end|> . Use current file imports: (from collections import OrderedDict from corpkit.process import classname from corpkit.editor import editor from corpkit.editor import editor from corpkit.plotter import plotter from corpkit.plotter import multiplotter from corpkit.model import _make_model_from_interro from corpkit.other import save from corpkit.other import quickview from ascii_graph import Pyasciigraph from ascii_graph.colors import Gre, Yel, Red, Blu from ascii_graph.colordata import vcolor from ascii_graph.colordata import hcolor from corpkit.other import make_multi from corpkit.other import topwords from scipy.stats import entropy from corpkit.stats import shannon from corpkit.other import concprinter from corpkit.process import interrogation_from_conclines from corpkit.editor import editor from corpkit.process import makesafe from corpkit.process import makesafe from corpkit.process import is_number from corpkit.process import makesafe from corpkit.editor import editor from itertools import product from corpkit.interrogation import Interrodict, Interrogation from collections import defaultdict from corpkit.other import save from corpkit.other import topwords from corpkit.interrogation import Interrodict from corpkit.interrogation import Interrodict import pandas as pd import tabview import pydoc import math import pandas as pd import random import pydoc import pandas as pd import numpy as np import matplotlib.pyplot as plt import pandas as pd) and context including class names, function names, or small code snippets from other files: # Path: corpkit/process.py # def classname(cls): # """Create the class name str for __repr__""" # return '.'.join([cls.__class__.__module__, cls.__class__.__name__]) . Output only the next line.
return "<%s instance: %d total>" % (classname(self), self.totals.sum())
Given snippet: <|code_start|> # store kwargs and locs locs = locals().copy() locs.update(kwargs) locs.pop('kwargs', None) have_java = check_jdk() # remake corpus without bad files and folders corpus, skip_metadata, just_metadata = delete_files_and_subcorpora(corpus, skip_metadata, just_metadata) # so you can do corpus.interrogate('features/postags/wordclasses/lexicon') if search == 'features': search = 'v' query = 'any' if search in ['postags', 'wordclasses']: query = 'any' preserve_case = True show = 'p' if search == 'postags' else 'x' # use tregex if simple because it's faster # but use dependencies otherwise search = 't' if not subcorpora and not just_metadata and not skip_metadata and have_java else {'w': 'any'} if search == 'lexicon': search = 't' if not subcorpora and not just_metadata and not skip_metadata and have_java else {'w': 'any'} query = 'any' show = ['w'] <|code_end|> , continue by predicting the next line. Consider current file imports: from corpkit.constants import STRINGTYPE, PYTHON_VERSION, INPUTFUNC from time import localtime, strftime from collections import Counter from pandas import DataFrame, Series from corpkit.interrogation import Interrogation, Interrodict from corpkit.corpus import Datalist, Corpora, Corpus, File, Subcorpus from corpkit.process import (tregex_engine, get_deps, unsplitter, sanitise_dict, animator, filtermaker, fix_search, pat_format, auto_usecols, format_tregex, make_conc_lines_from_whole_mid) from corpkit.other import as_regex from corpkit.dictionaries.process_types import Wordlist from corpkit.build import check_jdk from corpkit.conll import pipeline from corpkit.process import delete_files_and_subcorpora from traitlets import TraitError from corpkit.cql import to_corpkit from time import localtime, strftime from collections import OrderedDict from corpkit.dictionaries.process_types import Wordlist from collections import OrderedDict from time import localtime, strftime from corpkit.dictionaries.word_transforms import usa_convert from corpkit.process import dictformat from corpkit.build import get_all_metadata_fields from corpkit.interrogation import Concordance from blessings import Terminal from corpkit.process import searchfixer from nltk.stem.wordnet import WordNetLemmatizer from corpkit.multiprocess import pmultiquery from collections import defaultdict from corpkit.process import gettag import codecs import signal import os import pandas as pd import re import signal import sys import string import re import traceback import sys import copy and context: # Path: corpkit/constants.py # STRINGTYPE = str if PYTHON_VERSION == 3 else basestring # # PYTHON_VERSION = sys.version_info.major # # INPUTFUNC = input if PYTHON_VERSION == 3 else raw_input which might include code, classes, or functions. Output only the next line.
if not kwargs.get('cql') and isinstance(search, STRINGTYPE) and len(search) > 3:
Given the code snippet: <|code_start|> """Say goodbye before exiting""" if not kwargs.get('printstatus', True): return thetime = strftime("%H:%M:%S", localtime()) if only_conc: finalstring = '\n\n%s: Concordancing finished! %s results.' % (thetime, format(len(conc_df), ',')) else: finalstring = '\n\n%s: Interrogation finished!' % thetime if countmode: finalstring += ' %s matches.' % format(tot, ',') else: finalstring += ' %s unique results, %s total occurrences.' % (format(numentries, ','), format(total_total, ',')) if return_it: return finalstring else: print(finalstring) def get_conc_colnames(corpus, fsi_index=False, simple_tregex_mode=False): fields = [] base = 'c f s l m r' if simple_tregex_mode: base = base.replace('f ', '') if fsi_index and not simple_tregex_mode: base = 'i ' + base <|code_end|> , generate the next line using the imports in this file: from corpkit.constants import STRINGTYPE, PYTHON_VERSION, INPUTFUNC from time import localtime, strftime from collections import Counter from pandas import DataFrame, Series from corpkit.interrogation import Interrogation, Interrodict from corpkit.corpus import Datalist, Corpora, Corpus, File, Subcorpus from corpkit.process import (tregex_engine, get_deps, unsplitter, sanitise_dict, animator, filtermaker, fix_search, pat_format, auto_usecols, format_tregex, make_conc_lines_from_whole_mid) from corpkit.other import as_regex from corpkit.dictionaries.process_types import Wordlist from corpkit.build import check_jdk from corpkit.conll import pipeline from corpkit.process import delete_files_and_subcorpora from traitlets import TraitError from corpkit.cql import to_corpkit from time import localtime, strftime from collections import OrderedDict from corpkit.dictionaries.process_types import Wordlist from collections import OrderedDict from time import localtime, strftime from corpkit.dictionaries.word_transforms import usa_convert from corpkit.process import dictformat from corpkit.build import get_all_metadata_fields from corpkit.interrogation import Concordance from blessings import Terminal from corpkit.process import searchfixer from nltk.stem.wordnet import WordNetLemmatizer from corpkit.multiprocess import pmultiquery from collections import defaultdict from corpkit.process import gettag import codecs import signal import os import pandas as pd import re import signal import sys import string import re import traceback import sys import copy and context (functions, classes, or occasionally code) from other files: # Path: corpkit/constants.py # STRINGTYPE = str if PYTHON_VERSION == 3 else basestring # # PYTHON_VERSION = sys.version_info.major # # INPUTFUNC = input if PYTHON_VERSION == 3 else raw_input . Output only the next line.
if PYTHON_VERSION == 2:
Here is a snippet: <|code_start|> # use tregex if simple because it's faster # but use dependencies otherwise search = 't' if not subcorpora and not just_metadata and not skip_metadata and have_java else {'w': 'any'} if search == 'lexicon': search = 't' if not subcorpora and not just_metadata and not skip_metadata and have_java else {'w': 'any'} query = 'any' show = ['w'] if not kwargs.get('cql') and isinstance(search, STRINGTYPE) and len(search) > 3: raise ValueError('search argument not recognised.') if regex_nonword_filter: is_a_word = re.compile(regex_nonword_filter) else: is_a_word = re.compile(r'.*') # convert cql-style queries---pop for the sake of multiprocessing cql = kwargs.pop('cql', None) if cql: search, exclude = to_corpkit(search) def signal_handler(signal, _): """ Allow pausing and restarting whn not in GUI """ if root: return signal.signal(signal.SIGINT, original_sigint) thetime = strftime("%H:%M:%S", localtime()) <|code_end|> . Write the next line using the current file imports: from corpkit.constants import STRINGTYPE, PYTHON_VERSION, INPUTFUNC from time import localtime, strftime from collections import Counter from pandas import DataFrame, Series from corpkit.interrogation import Interrogation, Interrodict from corpkit.corpus import Datalist, Corpora, Corpus, File, Subcorpus from corpkit.process import (tregex_engine, get_deps, unsplitter, sanitise_dict, animator, filtermaker, fix_search, pat_format, auto_usecols, format_tregex, make_conc_lines_from_whole_mid) from corpkit.other import as_regex from corpkit.dictionaries.process_types import Wordlist from corpkit.build import check_jdk from corpkit.conll import pipeline from corpkit.process import delete_files_and_subcorpora from traitlets import TraitError from corpkit.cql import to_corpkit from time import localtime, strftime from collections import OrderedDict from corpkit.dictionaries.process_types import Wordlist from collections import OrderedDict from time import localtime, strftime from corpkit.dictionaries.word_transforms import usa_convert from corpkit.process import dictformat from corpkit.build import get_all_metadata_fields from corpkit.interrogation import Concordance from blessings import Terminal from corpkit.process import searchfixer from nltk.stem.wordnet import WordNetLemmatizer from corpkit.multiprocess import pmultiquery from collections import defaultdict from corpkit.process import gettag import codecs import signal import os import pandas as pd import re import signal import sys import string import re import traceback import sys import copy and context from other files: # Path: corpkit/constants.py # STRINGTYPE = str if PYTHON_VERSION == 3 else basestring # # PYTHON_VERSION = sys.version_info.major # # INPUTFUNC = input if PYTHON_VERSION == 3 else raw_input , which may include functions, classes, or code. Output only the next line.
INPUTFUNC('\n\n%s: Paused. Press any key to resume, or ctrl+c to quit.\n' % thetime)
Predict the next line for this snippet: <|code_start|> if word_in_ref == 0: logaE1 = 0 else: logaE1 = math.log(word_in_ref/E1) if word_in_target == 0: logaE2 = 0 else: logaE2 = math.log(word_in_target/E2) score = float(2* ((word_in_ref*logaE1)+(word_in_target*logaE2))) if neg: score = -score return score def perc_diff_measure(word_in_ref, word_in_target, ref_sum, target_sum): """calculate using perc diff measure""" norm_target = float(word_in_target) / target_sum norm_ref = float(word_in_ref) / ref_sum # Gabrielatos and Marchi (2012) do it this way! if norm_ref == 0: norm_ref = 0.00000000000000000000000001 return ((norm_target - norm_ref) * 100.0) / norm_ref def set_threshold(threshold): """define a threshold""" if threshold is False: return 0 if threshold is True: threshold = 'm' <|code_end|> with the help of current file imports: from corpkit.constants import STRINGTYPE, PYTHON_VERSION from pandas import DataFrame, Series from collections import Counter from corpkit.interrogation import Interrogation from corpkit.other import load import math and context from other files: # Path: corpkit/constants.py # STRINGTYPE = str if PYTHON_VERSION == 3 else basestring # # PYTHON_VERSION = sys.version_info.major , which may contain function names, class names, or code. Output only the next line.
if isinstance(threshold, STRINGTYPE):
Given the code snippet: <|code_start|>from __future__ import print_function """ In here are functions used internally by corpkit, but also might be called by the user from time to time """ def quickview(results, n=25): """ View top n results as painlessly as possible. :param results: Interrogation data :type results: :class:``corpkit.interrogation.Interrogation`` :param n: Show top *n* results :type n: int :returns: None """ # handle dictionaries too: dictpath = 'dictionaries' savedpath = 'saved_interrogations' # too lazy to code this properly for every possible data type: if n == 'all': n = 9999 dtype = corpkit.interrogation.Interrogation <|code_end|> , generate the next line using the imports in this file: from corpkit.constants import STRINGTYPE, PYTHON_VERSION, INPUTFUNC from corpkit.interrogation import Interrogation from corpkit.other import load from corpkit.other import load from time import localtime, strftime from corpkit.process import makesafe, sanitise_dict from corpkit.interrogation import Interrogation from corpkit.corpus import Corpus, Datalist from types import ModuleType, FunctionType, BuiltinMethodType, BuiltinFunctionType from corpkit.other import load from time import strftime, localtime from time import localtime, strftime from other import load from process import makesafe from interrogation import Interrodict from corpkit.constants import transshow, transobjs from corpkit.interrogation import Interrodict, Interrogation from corpkit.interrogation import Interrogation, Interrodict import corpkit import pandas as pd import numpy as np import os import corpkit import corpkit import pandas as pd import os import os import cPickle as pickle import pickle as pickle import os import corpkit import cPickle as pickle import pickle as pickle import os import glob import os import corpkit import corpkit import os import shutil import stat import platform import os import os import corpkit import pandas as pd import corpkit import re import numpy as np import pandas as pd import corpkit import pandas as pd import numpy as np import corpkit import pandas as pd and context (functions, classes, or occasionally code) from other files: # Path: corpkit/constants.py # STRINGTYPE = str if PYTHON_VERSION == 3 else basestring # # PYTHON_VERSION = sys.version_info.major # # INPUTFUNC = input if PYTHON_VERSION == 3 else raw_input . Output only the next line.
if isinstance(results, STRINGTYPE):
Predict the next line after this snippet: <|code_start|> firstpart = '' firstpart = os.path.basename(firstpart) if firstpart: return firstpart + '-' + savename else: return savename savename = make_filename(interrogation, savename) # delete unpicklable parts of query if hasattr(interrogation, 'query') and isinstance(interrogation.query, dict): iq = interrogation.query if iq: interrogation.query = {k: v for k, v in iq.items() if not isinstance(v, ModuleType) \ and not isinstance(v, FunctionType) \ and not isinstance(v, BuiltinFunctionType) \ and not isinstance(v, BuiltinMethodType)} else: iq = {} if savedir and not '/' in savename: if not os.path.exists(savedir): os.makedirs(savedir) fullpath = os.path.join(savedir, savename) else: fullpath = savename while os.path.isfile(fullpath): <|code_end|> using the current file's imports: from corpkit.constants import STRINGTYPE, PYTHON_VERSION, INPUTFUNC from corpkit.interrogation import Interrogation from corpkit.other import load from corpkit.other import load from time import localtime, strftime from corpkit.process import makesafe, sanitise_dict from corpkit.interrogation import Interrogation from corpkit.corpus import Corpus, Datalist from types import ModuleType, FunctionType, BuiltinMethodType, BuiltinFunctionType from corpkit.other import load from time import strftime, localtime from time import localtime, strftime from other import load from process import makesafe from interrogation import Interrodict from corpkit.constants import transshow, transobjs from corpkit.interrogation import Interrodict, Interrogation from corpkit.interrogation import Interrogation, Interrodict import corpkit import pandas as pd import numpy as np import os import corpkit import corpkit import pandas as pd import os import os import cPickle as pickle import pickle as pickle import os import corpkit import cPickle as pickle import pickle as pickle import os import glob import os import corpkit import corpkit import os import shutil import stat import platform import os import os import corpkit import pandas as pd import corpkit import re import numpy as np import pandas as pd import corpkit import pandas as pd import numpy as np import corpkit import pandas as pd and any relevant context from other files: # Path: corpkit/constants.py # STRINGTYPE = str if PYTHON_VERSION == 3 else basestring # # PYTHON_VERSION = sys.version_info.major # # INPUTFUNC = input if PYTHON_VERSION == 3 else raw_input . Output only the next line.
selection = INPUTFUNC(("\nSave error: %s already exists in %s.\n\n" \
Here is a snippet: <|code_start|> else: oldd[tokens[1]] = parse_pattern(tokens[-1]) setattr(objs, tokens[0], oldd) # delete the entire filter dict elif tokens[-1] in ['none', 'None', 'off', 'default']: setattr(objs, attr, False) print("Reset %s filter." % attr) return # if not in dict, add it metfeat = tokens[1] crit = tokens[-1] if crit.startswith('tag'): setattr(objs, attr, {'tags': parse_pattern(crit)}) else: if isinstance(getattr(objs, attr, False), dict): d = getattr(objs, attr) d[metfeat] = parse_pattern(crit) setattr(objs, attr, d) else: setattr(objs, attr, {metfeat: parse_pattern(crit)}) print("Current %s filter: %s" % (attr, getattr(objs, attr))) return if not check_in_project(): print("Must be in project to set corpus.") return if not tokens: # todo: pick first one if only one show_this(['corpora']) <|code_end|> . Write the next line using the current file imports: from corpkit.constants import STRINGTYPE, PYTHON_VERSION, INPUTFUNC from corpkit import * from corpkit.constants import transshow, transobjs from corpkit.completer import Completer from corpkit.dictionaries.roles import roles from corpkit.dictionaries.wordlists import wordlists from corpkit.dictionaries.process_types import processes from corpkit.dictionaries.verblist import allverbs from collections import defaultdict from corpkit.constants import OPENER from IPython import embed from IPython.terminal.embed import InteractiveShellEmbed from colorama import Fore, Back, Style, init from blessings import Terminal from corpkit.corpus import Corpus from corpkit.other import load from corpkit.corpus import Corpus, Corpora from corpkit.constants import transshow, transobjs from corpkit.dictionaries import roles, processes, wordlists from corpkit.interrogation import Concordance from corpkit.interrogation import Concordance from corpkit.interrogation import Interrogation, Concordance from corpkit.interrogation import Concordance from corpkit.interrogation import Concordance from corpkit.corpus import Corpus from corpkit.interrogation import Interrogation, Concordance from corpkit.other import load from corpkit.other import load_all_results from corpkit.other import new_project from corpkit.annotate import annotator from corpkit.interrogation import Concordance from corpkit.annotate import annotator from colorama import Fore, Back, Style, init from docker import Client from corpkit.interrogation import Concordance from corpkit.interrogation import Concordance from corpkit.process import makesafe import os import traceback import pandas as pd import gnureadline as readline import readline import atexit import corpkit import warnings import gnureadline as readline import readline as readline import gnureadline as readline import readline as readline import os import os import subprocess import os import subprocess import os import pydoc import tabview import os import readline import pydoc import pydoc import tabview import pandas as pd import os import numpy as np import matplotlib.pyplot as plt import shutil import os import subprocess import shlex import os import os import shlex import os import sys import sys import sys import sys import pip import importlib import traceback import os and context from other files: # Path: corpkit/constants.py # STRINGTYPE = str if PYTHON_VERSION == 3 else basestring # # PYTHON_VERSION = sys.version_info.major # # INPUTFUNC = input if PYTHON_VERSION == 3 else raw_input # # Path: corpkit/constants.py # PYTHON_VERSION = sys.version_info.major # STRINGTYPE = str if PYTHON_VERSION == 3 else basestring # INPUTFUNC = input if PYTHON_VERSION == 3 else raw_input # OPENER = open if PYTHON_VERSION == 3 else codecs.open # LETTERS = sorted(_letters + _adjacent) # CONLL_COLUMNS = ['i', 'w', 'l', 'p', 'e', 'v', 'g', 'f', 'd', 'c'] # MAX_SPEAKERNAME_SIZE = 40 # REPEAT_PARSE_ATTEMPTS = 3 # CORENLP_VERSION = '3.7.0' # CORENLP_URL = 'http://nlp.stanford.edu/software/stanford-corenlp-full-2016-10-31.zip' # MAX_METADATA_FIELDS = 99 # MAX_METADATA_VALUES = 99 # # Path: corpkit/completer.py # class Completer(object): # """ # Tab completion for interpreter # """ # # def __init__(self, words): # self.words = words # self.prefix = None # # def complete(self, prefix, index): # """ # Add paths etc to this # """ # if prefix != self.prefix: # # we have a new prefix! # # find all words that start with this prefix # self.matching_words = [ # w for w in self.words if w.startswith(prefix) # ] # self.prefix = prefix # try: # return self.matching_words[index] # except IndexError: # return None , which may include functions, classes, or code. Output only the next line.
selected = INPUTFUNC('Pick a corpus by name or number: ')
Here is a snippet: <|code_start|> continue if search_related[i+1] == 'postags': search = 'postags' continue if search_related[i+1] == 'wordclasses': search = 'wordclasses' continue k = search_related[i+1] if k == 'cql': cqlmode = True aquery = next((i for i in search_related[i+2:] \ if i not in ['matching']), False) if aquery: search = aquery break k = process_long_key(k) v = search_related[i+3].strip("'") v = parse_pattern(v) if token == 'not': exclude[k] = v else: search[k] = v return search, exclude, searchmode, cqlmode def process_long_key(srch): """ turn governor-lemma into 'gl', etc. """ transobjs = {v.lower(): k.replace(' ', '-') for k, v in transobjs.items()} <|code_end|> . Write the next line using the current file imports: from corpkit.constants import STRINGTYPE, PYTHON_VERSION, INPUTFUNC from corpkit import * from corpkit.constants import transshow, transobjs from corpkit.completer import Completer from corpkit.dictionaries.roles import roles from corpkit.dictionaries.wordlists import wordlists from corpkit.dictionaries.process_types import processes from corpkit.dictionaries.verblist import allverbs from collections import defaultdict from corpkit.constants import OPENER from IPython import embed from IPython.terminal.embed import InteractiveShellEmbed from colorama import Fore, Back, Style, init from blessings import Terminal from corpkit.corpus import Corpus from corpkit.other import load from corpkit.corpus import Corpus, Corpora from corpkit.constants import transshow, transobjs from corpkit.dictionaries import roles, processes, wordlists from corpkit.interrogation import Concordance from corpkit.interrogation import Concordance from corpkit.interrogation import Interrogation, Concordance from corpkit.interrogation import Concordance from corpkit.interrogation import Concordance from corpkit.corpus import Corpus from corpkit.interrogation import Interrogation, Concordance from corpkit.other import load from corpkit.other import load_all_results from corpkit.other import new_project from corpkit.annotate import annotator from corpkit.interrogation import Concordance from corpkit.annotate import annotator from colorama import Fore, Back, Style, init from docker import Client from corpkit.interrogation import Concordance from corpkit.interrogation import Concordance from corpkit.process import makesafe import os import traceback import pandas as pd import gnureadline as readline import readline import atexit import corpkit import warnings import gnureadline as readline import readline as readline import gnureadline as readline import readline as readline import os import os import subprocess import os import subprocess import os import pydoc import tabview import os import readline import pydoc import pydoc import tabview import pandas as pd import os import numpy as np import matplotlib.pyplot as plt import shutil import os import subprocess import shlex import os import os import shlex import os import sys import sys import sys import sys import pip import importlib import traceback import os and context from other files: # Path: corpkit/constants.py # STRINGTYPE = str if PYTHON_VERSION == 3 else basestring # # PYTHON_VERSION = sys.version_info.major # # INPUTFUNC = input if PYTHON_VERSION == 3 else raw_input # # Path: corpkit/constants.py # PYTHON_VERSION = sys.version_info.major # STRINGTYPE = str if PYTHON_VERSION == 3 else basestring # INPUTFUNC = input if PYTHON_VERSION == 3 else raw_input # OPENER = open if PYTHON_VERSION == 3 else codecs.open # LETTERS = sorted(_letters + _adjacent) # CONLL_COLUMNS = ['i', 'w', 'l', 'p', 'e', 'v', 'g', 'f', 'd', 'c'] # MAX_SPEAKERNAME_SIZE = 40 # REPEAT_PARSE_ATTEMPTS = 3 # CORENLP_VERSION = '3.7.0' # CORENLP_URL = 'http://nlp.stanford.edu/software/stanford-corenlp-full-2016-10-31.zip' # MAX_METADATA_FIELDS = 99 # MAX_METADATA_VALUES = 99 # # Path: corpkit/completer.py # class Completer(object): # """ # Tab completion for interpreter # """ # # def __init__(self, words): # self.words = words # self.prefix = None # # def complete(self, prefix, index): # """ # Add paths etc to this # """ # if prefix != self.prefix: # # we have a new prefix! # # find all words that start with this prefix # self.matching_words = [ # w for w in self.words if w.startswith(prefix) # ] # self.prefix = prefix # try: # return self.matching_words[index] # except IndexError: # return None , which may include functions, classes, or code. Output only the next line.
transshow = {v.lower(): k.replace(' ', '-') for k, v in transshow.items()}
Continue the code snippet: <|code_start|> search = 'features' continue if search_related[i+1] == 'postags': search = 'postags' continue if search_related[i+1] == 'wordclasses': search = 'wordclasses' continue k = search_related[i+1] if k == 'cql': cqlmode = True aquery = next((i for i in search_related[i+2:] \ if i not in ['matching']), False) if aquery: search = aquery break k = process_long_key(k) v = search_related[i+3].strip("'") v = parse_pattern(v) if token == 'not': exclude[k] = v else: search[k] = v return search, exclude, searchmode, cqlmode def process_long_key(srch): """ turn governor-lemma into 'gl', etc. """ <|code_end|> . Use current file imports: from corpkit.constants import STRINGTYPE, PYTHON_VERSION, INPUTFUNC from corpkit import * from corpkit.constants import transshow, transobjs from corpkit.completer import Completer from corpkit.dictionaries.roles import roles from corpkit.dictionaries.wordlists import wordlists from corpkit.dictionaries.process_types import processes from corpkit.dictionaries.verblist import allverbs from collections import defaultdict from corpkit.constants import OPENER from IPython import embed from IPython.terminal.embed import InteractiveShellEmbed from colorama import Fore, Back, Style, init from blessings import Terminal from corpkit.corpus import Corpus from corpkit.other import load from corpkit.corpus import Corpus, Corpora from corpkit.constants import transshow, transobjs from corpkit.dictionaries import roles, processes, wordlists from corpkit.interrogation import Concordance from corpkit.interrogation import Concordance from corpkit.interrogation import Interrogation, Concordance from corpkit.interrogation import Concordance from corpkit.interrogation import Concordance from corpkit.corpus import Corpus from corpkit.interrogation import Interrogation, Concordance from corpkit.other import load from corpkit.other import load_all_results from corpkit.other import new_project from corpkit.annotate import annotator from corpkit.interrogation import Concordance from corpkit.annotate import annotator from colorama import Fore, Back, Style, init from docker import Client from corpkit.interrogation import Concordance from corpkit.interrogation import Concordance from corpkit.process import makesafe import os import traceback import pandas as pd import gnureadline as readline import readline import atexit import corpkit import warnings import gnureadline as readline import readline as readline import gnureadline as readline import readline as readline import os import os import subprocess import os import subprocess import os import pydoc import tabview import os import readline import pydoc import pydoc import tabview import pandas as pd import os import numpy as np import matplotlib.pyplot as plt import shutil import os import subprocess import shlex import os import os import shlex import os import sys import sys import sys import sys import pip import importlib import traceback import os and context (classes, functions, or code) from other files: # Path: corpkit/constants.py # STRINGTYPE = str if PYTHON_VERSION == 3 else basestring # # PYTHON_VERSION = sys.version_info.major # # INPUTFUNC = input if PYTHON_VERSION == 3 else raw_input # # Path: corpkit/constants.py # PYTHON_VERSION = sys.version_info.major # STRINGTYPE = str if PYTHON_VERSION == 3 else basestring # INPUTFUNC = input if PYTHON_VERSION == 3 else raw_input # OPENER = open if PYTHON_VERSION == 3 else codecs.open # LETTERS = sorted(_letters + _adjacent) # CONLL_COLUMNS = ['i', 'w', 'l', 'p', 'e', 'v', 'g', 'f', 'd', 'c'] # MAX_SPEAKERNAME_SIZE = 40 # REPEAT_PARSE_ATTEMPTS = 3 # CORENLP_VERSION = '3.7.0' # CORENLP_URL = 'http://nlp.stanford.edu/software/stanford-corenlp-full-2016-10-31.zip' # MAX_METADATA_FIELDS = 99 # MAX_METADATA_VALUES = 99 # # Path: corpkit/completer.py # class Completer(object): # """ # Tab completion for interpreter # """ # # def __init__(self, words): # self.words = words # self.prefix = None # # def complete(self, prefix, index): # """ # Add paths etc to this # """ # if prefix != self.prefix: # # we have a new prefix! # # find all words that start with this prefix # self.matching_words = [ # w for w in self.words if w.startswith(prefix) # ] # self.prefix = prefix # try: # return self.matching_words[index] # except IndexError: # return None . Output only the next line.
transobjs = {v.lower(): k.replace(' ', '-') for k, v in transobjs.items()}
Next line prediction: <|code_start|> " +-----------------+--------------------------------------------------------------+--------------------------------------------------------------------------------------------+ \n"\ "\nMore information:\n\nYou can access more specific help by entering corpkit, then by doing 'help <command>', or by visiting\n" \ "http://corpkit.readthedocs.io/en/latest\n\n" \ "For help on viewing results, hit '?' when in the result viewing mode. For concordances, hit 'h'.\n\n(Hit 'q' to exit help).\n\n" try: except ImportError: warnings.simplefilter(action="ignore", category=UserWarning) # pandas display setup, though this is rarely used when LESS # and tabview are available size = pd.util.terminal.get_terminal_size() pd.set_option('display.max_rows', 0) pd.set_option('display.max_columns', 0) pd.set_option('display.float_format', lambda x: '{:,.3f}'.format(x)) # allow ctrl-r, etc readline.parse_and_bind('set editing-mode vi') # command completion poss = ['testing', 'search', 'concordance'] try: except ImportError: <|code_end|> . Use current file imports: (from corpkit.constants import STRINGTYPE, PYTHON_VERSION, INPUTFUNC from corpkit import * from corpkit.constants import transshow, transobjs from corpkit.completer import Completer from corpkit.dictionaries.roles import roles from corpkit.dictionaries.wordlists import wordlists from corpkit.dictionaries.process_types import processes from corpkit.dictionaries.verblist import allverbs from collections import defaultdict from corpkit.constants import OPENER from IPython import embed from IPython.terminal.embed import InteractiveShellEmbed from colorama import Fore, Back, Style, init from blessings import Terminal from corpkit.corpus import Corpus from corpkit.other import load from corpkit.corpus import Corpus, Corpora from corpkit.constants import transshow, transobjs from corpkit.dictionaries import roles, processes, wordlists from corpkit.interrogation import Concordance from corpkit.interrogation import Concordance from corpkit.interrogation import Interrogation, Concordance from corpkit.interrogation import Concordance from corpkit.interrogation import Concordance from corpkit.corpus import Corpus from corpkit.interrogation import Interrogation, Concordance from corpkit.other import load from corpkit.other import load_all_results from corpkit.other import new_project from corpkit.annotate import annotator from corpkit.interrogation import Concordance from corpkit.annotate import annotator from colorama import Fore, Back, Style, init from docker import Client from corpkit.interrogation import Concordance from corpkit.interrogation import Concordance from corpkit.process import makesafe import os import traceback import pandas as pd import gnureadline as readline import readline import atexit import corpkit import warnings import gnureadline as readline import readline as readline import gnureadline as readline import readline as readline import os import os import subprocess import os import subprocess import os import pydoc import tabview import os import readline import pydoc import pydoc import tabview import pandas as pd import os import numpy as np import matplotlib.pyplot as plt import shutil import os import subprocess import shlex import os import os import shlex import os import sys import sys import sys import sys import pip import importlib import traceback import os) and context including class names, function names, or small code snippets from other files: # Path: corpkit/constants.py # STRINGTYPE = str if PYTHON_VERSION == 3 else basestring # # PYTHON_VERSION = sys.version_info.major # # INPUTFUNC = input if PYTHON_VERSION == 3 else raw_input # # Path: corpkit/constants.py # PYTHON_VERSION = sys.version_info.major # STRINGTYPE = str if PYTHON_VERSION == 3 else basestring # INPUTFUNC = input if PYTHON_VERSION == 3 else raw_input # OPENER = open if PYTHON_VERSION == 3 else codecs.open # LETTERS = sorted(_letters + _adjacent) # CONLL_COLUMNS = ['i', 'w', 'l', 'p', 'e', 'v', 'g', 'f', 'd', 'c'] # MAX_SPEAKERNAME_SIZE = 40 # REPEAT_PARSE_ATTEMPTS = 3 # CORENLP_VERSION = '3.7.0' # CORENLP_URL = 'http://nlp.stanford.edu/software/stanford-corenlp-full-2016-10-31.zip' # MAX_METADATA_FIELDS = 99 # MAX_METADATA_VALUES = 99 # # Path: corpkit/completer.py # class Completer(object): # """ # Tab completion for interpreter # """ # # def __init__(self, words): # self.words = words # self.prefix = None # # def complete(self, prefix, index): # """ # Add paths etc to this # """ # if prefix != self.prefix: # # we have a new prefix! # # find all words that start with this prefix # self.matching_words = [ # w for w in self.words if w.startswith(prefix) # ] # self.prefix = prefix # try: # return self.matching_words[index] # except IndexError: # return None . Output only the next line.
completer = Completer(poss)
Given the following code snippet before the placeholder: <|code_start|>from __future__ import print_function log = logging def safe_import(path): module = path.split('.') g = __import__(module[0], fromlist=['*']) s = [module[0]] for i in module[1:]: mod = g if hasattr(mod, i): g = getattr(mod, i) else: s.append(i) g = __import__('.'.join(s), fromlist=['*']) return mod, g def import_mod_attr(path): """ Import string format module, e.g. 'uliweb.orm' or an object return module object and object """ <|code_end|> , predict the next line using imports from the current file: from ._compat import string_types from fnmatch import fnmatch from uliweb.i18n.lazystr import LazyString import os import re import logging import inspect import datetime import decimal import pkg_resources as pkg import shutil import shutil import hashlib import md5 and context including class names, function names, and sometimes code from other files: # Path: parm/_compat.py # PY3 = sys.version_info[0] == 3 # PY2 = sys.version_info[0] == 2 # PY26 = sys.version_info[0:2] == (2, 6) # PYPY = hasattr(sys, 'pypy_translation_info') # def reraise(tp, value, tb=None): # def u(s, encoding='utf8'): # def b(s): # def implements_iterator(cls): # def python_2_unicode_compatible(cls): # def u(s, encoding='utf8'): # def b(s, encoding='utf8'): # def exec_(code, globs=None, locs=None): # def next(it): # def with_metaclass(meta, *bases): # def __new__(cls, name, this_bases, d): # def import_(module, objects=None, via=None): # class metaclass(meta): . Output only the next line.
if isinstance(path, string_types):
Given the following code snippet before the placeholder: <|code_start|> _v = default if v in _vars: _v = _vars[v] elif v in _env: _v = _env[v] return _v return defined e = {} if isinstance(self.env, Context): new_e = self.env.to_dict() else: new_e = self.env e.update(new_e) e.update(self.vars) out = Out() e['out'] = out e['Out'] = Out e['xml'] = out.xml e['_vars'] = self.vars e['defined'] = f(self.vars, self.env) e['_env'] = e e.update(self.exec_env) if isinstance(code, string_types): if self.compile: code = self.compile(code, filename, 'exec', e) else: code = compile(code, filename, 'exec') <|code_end|> , predict the next line using imports from the current file: from ._compat import exec_, u, string_types, open import re import os import io import cgi and context including class names, function names, and sometimes code from other files: # Path: parm/_compat.py # PY3 = sys.version_info[0] == 3 # PY2 = sys.version_info[0] == 2 # PY26 = sys.version_info[0:2] == (2, 6) # PYPY = hasattr(sys, 'pypy_translation_info') # def reraise(tp, value, tb=None): # def u(s, encoding='utf8'): # def b(s): # def implements_iterator(cls): # def python_2_unicode_compatible(cls): # def u(s, encoding='utf8'): # def b(s, encoding='utf8'): # def exec_(code, globs=None, locs=None): # def next(it): # def with_metaclass(meta, *bases): # def __new__(cls, name, this_bases, d): # def import_(module, objects=None, via=None): # class metaclass(meta): . Output only the next line.
exec_(code, e)
Predict the next line for this snippet: <|code_start|> def __repr__(self): return self.__str__() class BaseBlockNode(Node): def __init__(self, name='', content=None): self.nodes = [] self.name = name self.content = content self.block = 1 def add(self, node): self.nodes.append(node) def end(self): pass def __repr__(self): s = ['{{BaseBlockNode %s}}' % self.name] for x in self.nodes: s.append(repr(x)) s.append('{{end}}') return ''.join(s) def __str__(self): return self.render() def render(self): s = [] for x in self.nodes: <|code_end|> with the help of current file imports: from ._compat import exec_, u, string_types, open import re import os import io import cgi and context from other files: # Path: parm/_compat.py # PY3 = sys.version_info[0] == 3 # PY2 = sys.version_info[0] == 2 # PY26 = sys.version_info[0:2] == (2, 6) # PYPY = hasattr(sys, 'pypy_translation_info') # def reraise(tp, value, tb=None): # def u(s, encoding='utf8'): # def b(s): # def implements_iterator(cls): # def python_2_unicode_compatible(cls): # def u(s, encoding='utf8'): # def b(s, encoding='utf8'): # def exec_(code, globs=None, locs=None): # def next(it): # def with_metaclass(meta, *bases): # def __new__(cls, name, this_bases, d): # def import_(module, objects=None, via=None): # class metaclass(meta): , which may contain function names, class names, or code. Output only the next line.
s.append(u(str(x)))
Here is a snippet: <|code_start|> return self._run(code, filename or 'template') def _run(self, code, filename): def f(_vars, _env): def defined(v, default=None): _v = default if v in _vars: _v = _vars[v] elif v in _env: _v = _env[v] return _v return defined e = {} if isinstance(self.env, Context): new_e = self.env.to_dict() else: new_e = self.env e.update(new_e) e.update(self.vars) out = Out() e['out'] = out e['Out'] = Out e['xml'] = out.xml e['_vars'] = self.vars e['defined'] = f(self.vars, self.env) e['_env'] = e e.update(self.exec_env) <|code_end|> . Write the next line using the current file imports: from ._compat import exec_, u, string_types, open import re import os import io import cgi and context from other files: # Path: parm/_compat.py # PY3 = sys.version_info[0] == 3 # PY2 = sys.version_info[0] == 2 # PY26 = sys.version_info[0:2] == (2, 6) # PYPY = hasattr(sys, 'pypy_translation_info') # def reraise(tp, value, tb=None): # def u(s, encoding='utf8'): # def b(s): # def implements_iterator(cls): # def python_2_unicode_compatible(cls): # def u(s, encoding='utf8'): # def b(s, encoding='utf8'): # def exec_(code, globs=None, locs=None): # def next(it): # def with_metaclass(meta, *bases): # def __new__(cls, name, this_bases, d): # def import_(module, objects=None, via=None): # class metaclass(meta): , which may include functions, classes, or code. Output only the next line.
if isinstance(code, string_types):
Continue the code snippet: <|code_start|> return True return False def _parse_text(self, content, var): try: text = u(str(eval(var, self.env.to_dict(), self.vars))) except: if self.skip_error: text = '' else: raise if text: t = Template(text, self.vars, self.env, self.dirs) t.parse() t.add_root(self) content.merge(t.content) def _parse_include(self, content, value): self.env.push() try: args, kwargs = self._get_parameters(value) filename = args[0] self.env.update(kwargs) fname = get_templatefile(filename, self.dirs, skip=self.filename, skip_original=self.original_filename) if not fname: raise TemplateException("Can't find the template %s" % filename) self.depend_files.append(fname) <|code_end|> . Use current file imports: from ._compat import exec_, u, string_types, open import re import os import io import cgi and context (classes, functions, or code) from other files: # Path: parm/_compat.py # PY3 = sys.version_info[0] == 3 # PY2 = sys.version_info[0] == 2 # PY26 = sys.version_info[0:2] == (2, 6) # PYPY = hasattr(sys, 'pypy_translation_info') # def reraise(tp, value, tb=None): # def u(s, encoding='utf8'): # def b(s): # def implements_iterator(cls): # def python_2_unicode_compatible(cls): # def u(s, encoding='utf8'): # def b(s, encoding='utf8'): # def exec_(code, globs=None, locs=None): # def next(it): # def with_metaclass(meta, *bases): # def __new__(cls, name, this_bases, d): # def import_(module, objects=None, via=None): # class metaclass(meta): . Output only the next line.
f = open(fname, 'r')
Given snippet: <|code_start|> log.error("File %s can't be found, will be skipped" % fname) continue def make_title(x): return '<li><a href="%s">%s</a></li>' % (x['link'], x['title']) _fname, _ext = os.path.splitext(fname) last = 1 title = _fname for x in hs: level = x['level'] #fetch title, so an article should be one h1 subject if level == 1: title = x['title'] if level > depth: continue if level == last: #same s.append(make_title(x)) elif level == last-1: #reindent s.append('</ul>\n') s.append(make_title(x)) last -= 1 elif level == last+1: #indent s.append('<ul>\n') s.append(make_title(x)) last += 1 else: pass <|code_end|> , continue by predicting the next line. Consider current file imports: from ._compat import range, open, u from .utils import log from .utils import json_dumps from .utils import json_dumps from .utils import json_dumps import re import os and context: # Path: parm/_compat.py # PY3 = sys.version_info[0] == 3 # PY2 = sys.version_info[0] == 2 # PY26 = sys.version_info[0:2] == (2, 6) # PYPY = hasattr(sys, 'pypy_translation_info') # def reraise(tp, value, tb=None): # def u(s, encoding='utf8'): # def b(s): # def implements_iterator(cls): # def python_2_unicode_compatible(cls): # def u(s, encoding='utf8'): # def b(s, encoding='utf8'): # def exec_(code, globs=None, locs=None): # def next(it): # def with_metaclass(meta, *bases): # def __new__(cls, name, this_bases, d): # def import_(module, objects=None, via=None): # class metaclass(meta): # # Path: parm/utils.py # def safe_import(path): # def import_mod_attr(path): # def import_attr(func): # def myimport(module): # def resource_filename(module, path): # def resource_listdir(module, path): # def resource_isdir(module, path): # def extract_file(module, path, dist, verbose=False, replace=True): # def extract_dirs(mod, path, dst, verbose=False, exclude=None, exclude_ext=None, recursion=True, replace=True): # def match(f, patterns): # def walk_dirs(path, include=None, include_ext=None, exclude=None, # exclude_ext=None, recursion=True, file_only=False): # def copy_dir(src, dst, verbose=False, check=False, processor=None): # def _md5(filename): # def copy_dir_with_check(dirs, dst, verbose=False, check=True, processor=None): # def encode_basestring(s): # def replace(match): # def encode_unicode(s): # def simple_value(v): # def __init__(self, encoding='utf-8', unicode=False, default=None): # def iterencode(self, obj, key=False): # def encode(self, obj): # def json_dumps(obj, unicode=False, **kwargs): # class MyPkg(object): # class JSONEncoder(object): # ESCAPE = re.compile(r'[\x00-\x1f\\"\b\f\n\r\t]') # ESCAPE_DCT = { # '\\': '\\\\', # '"': '\\"', # '\b': '\\b', # '\f': '\\f', # '\n': '\\n', # '\r': '\\r', # '\t': '\\t', # } which might include code, classes, or functions. Output only the next line.
for i in range(last, 1, -1):
Predict the next line after this snippet: <|code_start|> e = '' else: b, e = [y.rstrip() for y in v] if b.isdigit(): b = int(b) else: pattern = True b = b or 1 if e.isdigit(): e = int(e) else: pattern = True e = e or -1 if len(v) == 1: lineno.append(b) else: lineno.append((b, e)) s = [] first = '```' lang = kw.pop('language', '') if lang: first += lang+',' x = [] for k, v in kw.items(): x.append('%s=%s' % (k, v)) if x: first += ','.join(x) s.append(first) <|code_end|> using the current file's imports: from ._compat import range, open, u from .utils import log from .utils import json_dumps from .utils import json_dumps from .utils import json_dumps import re import os and any relevant context from other files: # Path: parm/_compat.py # PY3 = sys.version_info[0] == 3 # PY2 = sys.version_info[0] == 2 # PY26 = sys.version_info[0:2] == (2, 6) # PYPY = hasattr(sys, 'pypy_translation_info') # def reraise(tp, value, tb=None): # def u(s, encoding='utf8'): # def b(s): # def implements_iterator(cls): # def python_2_unicode_compatible(cls): # def u(s, encoding='utf8'): # def b(s, encoding='utf8'): # def exec_(code, globs=None, locs=None): # def next(it): # def with_metaclass(meta, *bases): # def __new__(cls, name, this_bases, d): # def import_(module, objects=None, via=None): # class metaclass(meta): # # Path: parm/utils.py # def safe_import(path): # def import_mod_attr(path): # def import_attr(func): # def myimport(module): # def resource_filename(module, path): # def resource_listdir(module, path): # def resource_isdir(module, path): # def extract_file(module, path, dist, verbose=False, replace=True): # def extract_dirs(mod, path, dst, verbose=False, exclude=None, exclude_ext=None, recursion=True, replace=True): # def match(f, patterns): # def walk_dirs(path, include=None, include_ext=None, exclude=None, # exclude_ext=None, recursion=True, file_only=False): # def copy_dir(src, dst, verbose=False, check=False, processor=None): # def _md5(filename): # def copy_dir_with_check(dirs, dst, verbose=False, check=True, processor=None): # def encode_basestring(s): # def replace(match): # def encode_unicode(s): # def simple_value(v): # def __init__(self, encoding='utf-8', unicode=False, default=None): # def iterencode(self, obj, key=False): # def encode(self, obj): # def json_dumps(obj, unicode=False, **kwargs): # class MyPkg(object): # class JSONEncoder(object): # ESCAPE = re.compile(r'[\x00-\x1f\\"\b\f\n\r\t]') # ESCAPE_DCT = { # '\\': '\\\\', # '"': '\\"', # '\b': '\\b', # '\f': '\\f', # '\n': '\\n', # '\r': '\\r', # '\t': '\\t', # } . Output only the next line.
with open(filename, 'r') as f:
Continue the code snippet: <|code_start|> key : value {% endcode-comment %} """ if 'new' in block: txt = [] data = {} txt.append('<script type="text/code-comment">') d = {} for line in block['body'].splitlines(): if line.strip(): k, v = line.split(':', 1) k = k.strip() if '=' in v: title, v = v.split('=', 1) title = title.strip() else: title = k v = visitor.parse_text(v.strip(), 'article') d[k] = {'title':title, 'content':v} if len(block['kwargs']) == 1 and list(block['kwargs'].keys())[0] != 'target': key = list(block['kwargs'].keys())[0] else: key = block['kwargs'].get('target', '') if key in data: data[key] = data[key].update(d) else: data[key] = d <|code_end|> . Use current file imports: from ._compat import range, open, u from .utils import log from .utils import json_dumps from .utils import json_dumps from .utils import json_dumps import re import os and context (classes, functions, or code) from other files: # Path: parm/_compat.py # PY3 = sys.version_info[0] == 3 # PY2 = sys.version_info[0] == 2 # PY26 = sys.version_info[0:2] == (2, 6) # PYPY = hasattr(sys, 'pypy_translation_info') # def reraise(tp, value, tb=None): # def u(s, encoding='utf8'): # def b(s): # def implements_iterator(cls): # def python_2_unicode_compatible(cls): # def u(s, encoding='utf8'): # def b(s, encoding='utf8'): # def exec_(code, globs=None, locs=None): # def next(it): # def with_metaclass(meta, *bases): # def __new__(cls, name, this_bases, d): # def import_(module, objects=None, via=None): # class metaclass(meta): # # Path: parm/utils.py # def safe_import(path): # def import_mod_attr(path): # def import_attr(func): # def myimport(module): # def resource_filename(module, path): # def resource_listdir(module, path): # def resource_isdir(module, path): # def extract_file(module, path, dist, verbose=False, replace=True): # def extract_dirs(mod, path, dst, verbose=False, exclude=None, exclude_ext=None, recursion=True, replace=True): # def match(f, patterns): # def walk_dirs(path, include=None, include_ext=None, exclude=None, # exclude_ext=None, recursion=True, file_only=False): # def copy_dir(src, dst, verbose=False, check=False, processor=None): # def _md5(filename): # def copy_dir_with_check(dirs, dst, verbose=False, check=True, processor=None): # def encode_basestring(s): # def replace(match): # def encode_unicode(s): # def simple_value(v): # def __init__(self, encoding='utf-8', unicode=False, default=None): # def iterencode(self, obj, key=False): # def encode(self, obj): # def json_dumps(obj, unicode=False, **kwargs): # class MyPkg(object): # class JSONEncoder(object): # ESCAPE = re.compile(r'[\x00-\x1f\\"\b\f\n\r\t]') # ESCAPE_DCT = { # '\\': '\\\\', # '"': '\\"', # '\b': '\\b', # '\f': '\\f', # '\n': '\\n', # '\r': '\\r', # '\t': '\\t', # } . Output only the next line.
txt.append(u(json_dumps(data)))
Continue the code snippet: <|code_start|> {% code %} code {% endcode %} """ return block['body'] def toc(visitor, block, headers=None, relations=None): """ Format: {% toc max_depth=2 %} file1.md file2.md {% endtoc %} """ s = [] s.append('<div class="toc">\n') depth = int(block['kwargs'].get('max_depth', '1')) if 'class' in block['kwargs']: s.append('<ul class=%s>\n' % block['kwargs']['class']) else: s.append('<ul>\n') prev = {'prev':{}, 'next':{}, 'current':{}} for fname in block['body'].splitlines(): hs = headers.get(fname, []) if not hs: <|code_end|> . Use current file imports: from ._compat import range, open, u from .utils import log from .utils import json_dumps from .utils import json_dumps from .utils import json_dumps import re import os and context (classes, functions, or code) from other files: # Path: parm/_compat.py # PY3 = sys.version_info[0] == 3 # PY2 = sys.version_info[0] == 2 # PY26 = sys.version_info[0:2] == (2, 6) # PYPY = hasattr(sys, 'pypy_translation_info') # def reraise(tp, value, tb=None): # def u(s, encoding='utf8'): # def b(s): # def implements_iterator(cls): # def python_2_unicode_compatible(cls): # def u(s, encoding='utf8'): # def b(s, encoding='utf8'): # def exec_(code, globs=None, locs=None): # def next(it): # def with_metaclass(meta, *bases): # def __new__(cls, name, this_bases, d): # def import_(module, objects=None, via=None): # class metaclass(meta): # # Path: parm/utils.py # def safe_import(path): # def import_mod_attr(path): # def import_attr(func): # def myimport(module): # def resource_filename(module, path): # def resource_listdir(module, path): # def resource_isdir(module, path): # def extract_file(module, path, dist, verbose=False, replace=True): # def extract_dirs(mod, path, dst, verbose=False, exclude=None, exclude_ext=None, recursion=True, replace=True): # def match(f, patterns): # def walk_dirs(path, include=None, include_ext=None, exclude=None, # exclude_ext=None, recursion=True, file_only=False): # def copy_dir(src, dst, verbose=False, check=False, processor=None): # def _md5(filename): # def copy_dir_with_check(dirs, dst, verbose=False, check=True, processor=None): # def encode_basestring(s): # def replace(match): # def encode_unicode(s): # def simple_value(v): # def __init__(self, encoding='utf-8', unicode=False, default=None): # def iterencode(self, obj, key=False): # def encode(self, obj): # def json_dumps(obj, unicode=False, **kwargs): # class MyPkg(object): # class JSONEncoder(object): # ESCAPE = re.compile(r'[\x00-\x1f\\"\b\f\n\r\t]') # ESCAPE_DCT = { # '\\': '\\\\', # '"': '\\"', # '\b': '\\b', # '\f': '\\f', # '\n': '\\n', # '\r': '\\r', # '\t': '\\t', # } . Output only the next line.
log.error("File %s can't be found, will be skipped" % fname)
Next line prediction: <|code_start|> so that ManagementUtility can handle them before searching for user commands. """ pass class CommandError(Exception): """ Exception class indicating a problem while executing a management command. If this exception is raised during the execution of a management command, it will be caught and turned into a nicely-printed error message to the appropriate output stream (i.e., stderr); as a result, raising this exception (with a sensible description of the error) is the preferred way to indicate that something has gone wrong in the execution of a command. """ pass def get_answer(message, answers='Yn', default='Y', quit=''): """ Get an answer from stdin, the answers should be 'Y/n' etc. If you don't want the user can quit in the loop, then quit should be None. """ if quit and quit not in answers: answers = answers + quit message = message + '(' + '/'.join(answers) + ')[' + default + ']:' <|code_end|> . Use current file imports: (from ._compat import input, with_metaclass, string_types from optparse import make_option, OptionParser, IndentedHelpFormatter from .commands import execute_command_line import sys, os import logging import inspect import traceback import shlex) and context including class names, function names, or small code snippets from other files: # Path: parm/_compat.py # PY3 = sys.version_info[0] == 3 # PY2 = sys.version_info[0] == 2 # PY26 = sys.version_info[0:2] == (2, 6) # PYPY = hasattr(sys, 'pypy_translation_info') # def reraise(tp, value, tb=None): # def u(s, encoding='utf8'): # def b(s): # def implements_iterator(cls): # def python_2_unicode_compatible(cls): # def u(s, encoding='utf8'): # def b(s, encoding='utf8'): # def exec_(code, globs=None, locs=None): # def next(it): # def with_metaclass(meta, *bases): # def __new__(cls, name, this_bases, d): # def import_(module, objects=None, via=None): # class metaclass(meta): . Output only the next line.
ans = input(message).strip().upper()
Using the snippet: <|code_start|> if not str(e).startswith('No module named'): traceback.print_exc() continue find_mod_commands(mod) collect_commands() return __commands__ def register_command(kclass): global __commands__ __commands__[kclass.name] = kclass def call(prog_name, version, modules=None, args=None): modules = modules or [] if isinstance(args, string_types): args = shlex.split(args) execute_command_line(args or sys.argv, get_commands(modules), prog_name, version) class CommandMetaclass(type): def __init__(cls, name, bases, dct): option_list = list(dct.get('option_list', [])) for c in bases: if hasattr(c, 'option_list') and isinstance(c.option_list, list): option_list.extend(c.option_list) cls.option_list = option_list <|code_end|> , determine the next line of code. You have imports: from ._compat import input, with_metaclass, string_types from optparse import make_option, OptionParser, IndentedHelpFormatter from .commands import execute_command_line import sys, os import logging import inspect import traceback import shlex and context (class names, function names, or code) available: # Path: parm/_compat.py # PY3 = sys.version_info[0] == 3 # PY2 = sys.version_info[0] == 2 # PY26 = sys.version_info[0:2] == (2, 6) # PYPY = hasattr(sys, 'pypy_translation_info') # def reraise(tp, value, tb=None): # def u(s, encoding='utf8'): # def b(s): # def implements_iterator(cls): # def python_2_unicode_compatible(cls): # def u(s, encoding='utf8'): # def b(s, encoding='utf8'): # def exec_(code, globs=None, locs=None): # def next(it): # def with_metaclass(meta, *bases): # def __new__(cls, name, this_bases, d): # def import_(module, objects=None, via=None): # class metaclass(meta): . Output only the next line.
class Command(with_metaclass(CommandMetaclass)):
Predict the next line after this snippet: <|code_start|> issubclass(c, Command) and c is not Command and c is not CommandManager) def find_mod_commands(mod): for name in dir(mod): c = getattr(mod, name) if check(c): register_command(c) def collect_commands(): for m in modules: try: mod = __import__(m, fromlist=['*']) except ImportError as e: if not str(e).startswith('No module named'): traceback.print_exc() continue find_mod_commands(mod) collect_commands() return __commands__ def register_command(kclass): global __commands__ __commands__[kclass.name] = kclass def call(prog_name, version, modules=None, args=None): modules = modules or [] <|code_end|> using the current file's imports: from ._compat import input, with_metaclass, string_types from optparse import make_option, OptionParser, IndentedHelpFormatter from .commands import execute_command_line import sys, os import logging import inspect import traceback import shlex and any relevant context from other files: # Path: parm/_compat.py # PY3 = sys.version_info[0] == 3 # PY2 = sys.version_info[0] == 2 # PY26 = sys.version_info[0:2] == (2, 6) # PYPY = hasattr(sys, 'pypy_translation_info') # def reraise(tp, value, tb=None): # def u(s, encoding='utf8'): # def b(s): # def implements_iterator(cls): # def python_2_unicode_compatible(cls): # def u(s, encoding='utf8'): # def b(s, encoding='utf8'): # def exec_(code, globs=None, locs=None): # def next(it): # def with_metaclass(meta, *bases): # def __new__(cls, name, this_bases, d): # def import_(module, objects=None, via=None): # class metaclass(meta): . Output only the next line.
if isinstance(args, string_types):
Based on the snippet: <|code_start|>#!/usr/bin/env python3 """ Test loading cifar100. """ # setup name = 'cifar100' task = 'classification' data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data') verbose = True # Run tester <|code_end|> , predict the immediate next line with the help of imports: import os from dbcollection.utils.test import TestBaseDB and context (classes, functions, sometimes code) from other files: # Path: dbcollection/utils/test.py # class TestBaseDB: # """ Test Class for loading datasets. # # Parameters # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool, optional # Be verbose. # # Attributes # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool # Be verbose. # # """ # # def __init__(self, name, task, data_dir, verbose=True): # """Initialize class.""" # assert name, "Must insert input arg: name" # assert task, "Must insert input arg: task" # assert data_dir, "Must insert input arg: data_dir" # # self.name = name # self.task = task # self.data_dir = data_dir # self.verbose = verbose # # def delete_cache(self): # """Delete all cache data + dir""" # print('\n==> dbcollection: config_cache()') # dbc.cache(delete_cache=True) # # def list_datasets(self): # """Print dbcollection info""" # print('\n==> dbcollection: info()') # dbc.info() # # def print_info(self, loader): # """Print information about the dataset to the screen # # Parameters # ---------- # loader : DataLoader # Data loader object of a dataset. # """ # print('\n######### info #########') # print('Dataset: ' + loader.db_name) # print('Task: ' + loader.task) # print('Data path: ' + loader.data_dir) # print('Metadata cache path: ' + loader.hdf5_filepath) # # def load(self): # """Return a data loader object for a dataset. # # Returns # ------- # DataLoader # A data loader object of a dataset. # """ # print('\n==> dbcollection: load()') # return dbc.load(name=self.name, # task=self.task, # data_dir=self.data_dir, # verbose=self.verbose) # # def download(self, extract_data=True): # """Download a dataset to disk. # # Parameters # ---------- # extract_data : bool # Flag signaling to extract data to disk (if True). # """ # print('\n==> dbcollection: download()') # dbc.download(name=self.name, # data_dir=self.data_dir, # extract_data=extract_data, # verbose=self.verbose) # # def process(self): # """Process dataset""" # print('\n==> dbcollection: process()') # dbc.process(name=self.name, # task=self.task, # verbose=self.verbose) # # def run(self, mode): # """Run the test script. # # Parameters # ---------- # mode : str # Task name to execute. # # Raises # ------ # Exception # If an invalid mode was inserted. # """ # assert mode, 'Must insert input arg: mode' # # # delete all cache data + dir # self.delete_cache() # # if mode is 'load': # # download/setup dataset # loader = self.load() # # # print data from the loader # self.print_info(loader) # # elif mode is 'download': # # download dataset # self.download() # # elif mode is 'process': # # download dataset # self.download(False) # # # process dataset task # self.process() # # else: # raise Exception('Invalid mode:', mode) # # # print data from the loader # self.list_datasets() # # # delete all cache data + dir before terminating # self.delete_cache() . Output only the next line.
tester = TestBaseDB(name, task, data_dir, verbose)
Next line prediction: <|code_start|>#!/usr/bin/env python3 """ Test loading Leeds Sports Pose (extended). """ # setup name = 'leeds_sports_pose_extended' task = 'keypoints' data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data') verbose = True # Run tester <|code_end|> . Use current file imports: (import os from dbcollection.utils.test import TestBaseDB) and context including class names, function names, or small code snippets from other files: # Path: dbcollection/utils/test.py # class TestBaseDB: # """ Test Class for loading datasets. # # Parameters # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool, optional # Be verbose. # # Attributes # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool # Be verbose. # # """ # # def __init__(self, name, task, data_dir, verbose=True): # """Initialize class.""" # assert name, "Must insert input arg: name" # assert task, "Must insert input arg: task" # assert data_dir, "Must insert input arg: data_dir" # # self.name = name # self.task = task # self.data_dir = data_dir # self.verbose = verbose # # def delete_cache(self): # """Delete all cache data + dir""" # print('\n==> dbcollection: config_cache()') # dbc.cache(delete_cache=True) # # def list_datasets(self): # """Print dbcollection info""" # print('\n==> dbcollection: info()') # dbc.info() # # def print_info(self, loader): # """Print information about the dataset to the screen # # Parameters # ---------- # loader : DataLoader # Data loader object of a dataset. # """ # print('\n######### info #########') # print('Dataset: ' + loader.db_name) # print('Task: ' + loader.task) # print('Data path: ' + loader.data_dir) # print('Metadata cache path: ' + loader.hdf5_filepath) # # def load(self): # """Return a data loader object for a dataset. # # Returns # ------- # DataLoader # A data loader object of a dataset. # """ # print('\n==> dbcollection: load()') # return dbc.load(name=self.name, # task=self.task, # data_dir=self.data_dir, # verbose=self.verbose) # # def download(self, extract_data=True): # """Download a dataset to disk. # # Parameters # ---------- # extract_data : bool # Flag signaling to extract data to disk (if True). # """ # print('\n==> dbcollection: download()') # dbc.download(name=self.name, # data_dir=self.data_dir, # extract_data=extract_data, # verbose=self.verbose) # # def process(self): # """Process dataset""" # print('\n==> dbcollection: process()') # dbc.process(name=self.name, # task=self.task, # verbose=self.verbose) # # def run(self, mode): # """Run the test script. # # Parameters # ---------- # mode : str # Task name to execute. # # Raises # ------ # Exception # If an invalid mode was inserted. # """ # assert mode, 'Must insert input arg: mode' # # # delete all cache data + dir # self.delete_cache() # # if mode is 'load': # # download/setup dataset # loader = self.load() # # # print data from the loader # self.print_info(loader) # # elif mode is 'download': # # download dataset # self.download() # # elif mode is 'process': # # download dataset # self.download(False) # # # process dataset task # self.process() # # else: # raise Exception('Invalid mode:', mode) # # # print data from the loader # self.list_datasets() # # # delete all cache data + dir before terminating # self.delete_cache() . Output only the next line.
tester = TestBaseDB(name, task, data_dir, verbose)
Continue the code snippet: <|code_start|>#!/usr/bin/env python """ Test loading ucf101. """ # setup name = 'ucf_101' task = 'recognition' data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data') verbose = True # Run tester <|code_end|> . Use current file imports: import os from dbcollection.utils.test import TestBaseDB and context (classes, functions, or code) from other files: # Path: dbcollection/utils/test.py # class TestBaseDB: # """ Test Class for loading datasets. # # Parameters # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool, optional # Be verbose. # # Attributes # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool # Be verbose. # # """ # # def __init__(self, name, task, data_dir, verbose=True): # """Initialize class.""" # assert name, "Must insert input arg: name" # assert task, "Must insert input arg: task" # assert data_dir, "Must insert input arg: data_dir" # # self.name = name # self.task = task # self.data_dir = data_dir # self.verbose = verbose # # def delete_cache(self): # """Delete all cache data + dir""" # print('\n==> dbcollection: config_cache()') # dbc.cache(delete_cache=True) # # def list_datasets(self): # """Print dbcollection info""" # print('\n==> dbcollection: info()') # dbc.info() # # def print_info(self, loader): # """Print information about the dataset to the screen # # Parameters # ---------- # loader : DataLoader # Data loader object of a dataset. # """ # print('\n######### info #########') # print('Dataset: ' + loader.db_name) # print('Task: ' + loader.task) # print('Data path: ' + loader.data_dir) # print('Metadata cache path: ' + loader.hdf5_filepath) # # def load(self): # """Return a data loader object for a dataset. # # Returns # ------- # DataLoader # A data loader object of a dataset. # """ # print('\n==> dbcollection: load()') # return dbc.load(name=self.name, # task=self.task, # data_dir=self.data_dir, # verbose=self.verbose) # # def download(self, extract_data=True): # """Download a dataset to disk. # # Parameters # ---------- # extract_data : bool # Flag signaling to extract data to disk (if True). # """ # print('\n==> dbcollection: download()') # dbc.download(name=self.name, # data_dir=self.data_dir, # extract_data=extract_data, # verbose=self.verbose) # # def process(self): # """Process dataset""" # print('\n==> dbcollection: process()') # dbc.process(name=self.name, # task=self.task, # verbose=self.verbose) # # def run(self, mode): # """Run the test script. # # Parameters # ---------- # mode : str # Task name to execute. # # Raises # ------ # Exception # If an invalid mode was inserted. # """ # assert mode, 'Must insert input arg: mode' # # # delete all cache data + dir # self.delete_cache() # # if mode is 'load': # # download/setup dataset # loader = self.load() # # # print data from the loader # self.print_info(loader) # # elif mode is 'download': # # download dataset # self.download() # # elif mode is 'process': # # download dataset # self.download(False) # # # process dataset task # self.process() # # else: # raise Exception('Invalid mode:', mode) # # # print data from the loader # self.list_datasets() # # # delete all cache data + dir before terminating # self.delete_cache() . Output only the next line.
tester = TestBaseDB(name, task, data_dir, verbose)
Continue the code snippet: <|code_start|>#!/usr/bin/env python3 """ Test loading MPII Human Pose. """ # setup name = 'mpii_pose' task = 'keypoints' data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data') verbose = True # Run tester <|code_end|> . Use current file imports: import os from dbcollection.utils.test import TestBaseDB and context (classes, functions, or code) from other files: # Path: dbcollection/utils/test.py # class TestBaseDB: # """ Test Class for loading datasets. # # Parameters # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool, optional # Be verbose. # # Attributes # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool # Be verbose. # # """ # # def __init__(self, name, task, data_dir, verbose=True): # """Initialize class.""" # assert name, "Must insert input arg: name" # assert task, "Must insert input arg: task" # assert data_dir, "Must insert input arg: data_dir" # # self.name = name # self.task = task # self.data_dir = data_dir # self.verbose = verbose # # def delete_cache(self): # """Delete all cache data + dir""" # print('\n==> dbcollection: config_cache()') # dbc.cache(delete_cache=True) # # def list_datasets(self): # """Print dbcollection info""" # print('\n==> dbcollection: info()') # dbc.info() # # def print_info(self, loader): # """Print information about the dataset to the screen # # Parameters # ---------- # loader : DataLoader # Data loader object of a dataset. # """ # print('\n######### info #########') # print('Dataset: ' + loader.db_name) # print('Task: ' + loader.task) # print('Data path: ' + loader.data_dir) # print('Metadata cache path: ' + loader.hdf5_filepath) # # def load(self): # """Return a data loader object for a dataset. # # Returns # ------- # DataLoader # A data loader object of a dataset. # """ # print('\n==> dbcollection: load()') # return dbc.load(name=self.name, # task=self.task, # data_dir=self.data_dir, # verbose=self.verbose) # # def download(self, extract_data=True): # """Download a dataset to disk. # # Parameters # ---------- # extract_data : bool # Flag signaling to extract data to disk (if True). # """ # print('\n==> dbcollection: download()') # dbc.download(name=self.name, # data_dir=self.data_dir, # extract_data=extract_data, # verbose=self.verbose) # # def process(self): # """Process dataset""" # print('\n==> dbcollection: process()') # dbc.process(name=self.name, # task=self.task, # verbose=self.verbose) # # def run(self, mode): # """Run the test script. # # Parameters # ---------- # mode : str # Task name to execute. # # Raises # ------ # Exception # If an invalid mode was inserted. # """ # assert mode, 'Must insert input arg: mode' # # # delete all cache data + dir # self.delete_cache() # # if mode is 'load': # # download/setup dataset # loader = self.load() # # # print data from the loader # self.print_info(loader) # # elif mode is 'download': # # download dataset # self.download() # # elif mode is 'process': # # download dataset # self.download(False) # # # process dataset task # self.process() # # else: # raise Exception('Invalid mode:', mode) # # # print data from the loader # self.list_datasets() # # # delete all cache data + dir before terminating # self.delete_cache() . Output only the next line.
tester = TestBaseDB(name, task, data_dir, verbose)
Predict the next line after this snippet: <|code_start|>""" Test dbcollection/utils/pad.py. """ @pytest.mark.parametrize("sample, output, fill_value", [ ([[5, 1, 3], [9, 17, 324]], [[5, 1, 3], [9, 17, 324]], -1), ([[1, 1, 0], [1, 0]], [[1, 1, 0], [1, 0, -1]], -1), ([[1, 1, 0], [1, 0]], [[1, 1, 0], [1, 0, 0]], 0), ([[9, 99, 999, 9999], [], [1, 2, 10]], [[9, 99, 999, 9999], [3, 3, 3, 3], [1, 2, 10, 3]], 3), ]) def test_pad_list(sample, output, fill_value): <|code_end|> using the current file's imports: import pytest from dbcollection.utils.pad import pad_list, unpad_list, squeeze_list, unsqueeze_list and any relevant context from other files: # Path: dbcollection/utils/pad.py # def pad_list(listA, val=-1, length=None): # """Pad list of lists with 'val' such that all lists have the same length. # # Parameters # ---------- # listA : list # List of lists of different sizes. # val : number, optional # Value to pad the lists. # length : number, optional # Total length of the list. # # Returns # ------- # list # A list of lists with the same same. # # Examples # -------- # Pad an uneven list of lists with a value. # # >>> from dbcollection.utils.pad import pad_list # >>> pad_list([[0,1,2,3],[45,6],[7,8],[9]]) # pad with -1 (default) # [[0, 1, 2, 3], [4, 5, 6, -1], [7, 8, -1, -1], [9-1, -1, -1]] # >>> pad_list([[1,2],[3,4]]) # does nothing # [[1, 2], [3, 4]] # >>> pad_list([[],[1],[3,4,5]], 0) # pad lists with 0 # [[0, 0, 0], [1, 0, 0], [3, 4, 5]] # >>> pad_list([[],[1],[3,4,5]], 0, 6) # pad lists with 0 of size 6 # [[0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0], [3, 4, 5, 0, 0, 0]] # # """ # # pad list with zeros in order to have all lists of the same size # assert isinstance(listA, list), 'Input must be a list. Got {}, expected {}' \ # .format(type(listA), type(list)) # # # get size of the biggest list # if length: # max_size = length # else: # max_size = len(max(listA, key=len)) # # # pad all lists with the a padding value # return [l + [val] * int(max_size - len(l)) for l in listA] # # def unpad_list(listA, val=-1): # """Unpad list of lists with which has values equal to 'val'. # # Parameters # ---------- # listA : list # List of lists of equal sizes. # val : number, optional # Value to unpad the lists. # # Returns # ------- # list # A list of lists without the padding values. # # Examples # -------- # Remove the padding values of a list of lists. # # >>> from dbcollection.utils.pad import unpad_list # >>> unpad_list([[1,2,3,-1,-1],[5,6,-1,-1,-1]]) # [[1, 2, 3], [5, 6]] # >>> unpad_list([[5,0,-1],[1,2,3,4,5]], 5) # [[0, -1], [1, 2, 3, 4]] # # """ # # pad list with zeros in order to have all lists of the same size # assert isinstance(listA, list), 'Input must be a list. Got {}, expected {}' \ # .format(type(listA), type(list)) # # if isinstance(listA[0], list): # return [list(filter(lambda x: x != val, l)) for i, l in enumerate(listA)] # else: # return list(filter(lambda x: x != val, listA)) # # def squeeze_list(listA, val=-1): # """ Compact a list of lists into a single list. # # Squeezes (spaghettify) a list of lists into a single list. # The lists are concatenated into a single one, and to separate # them it is used a separating value to mark the split location # when unsqueezing the list. # # Parameters # ---------- # listA : list # List of lists. # val : number, optional # Value to separate the lists. # # Returns # ------- # list # A list with all lists concatenated into one. # # Examples # -------- # Compact a list of lists into a single list. # # >>> from dbcollection.utils.pad import squeeze_list # >>> squeeze_list([[1,2], [3], [4,5,6]], -1) # [1, 2, -1, 3, -1, 4, 5, 6] # # """ # concatA = [l + [val] for l in listA] # out = [li for l in concatA for li in l] # return out[:-1] # # def unsqueeze_list(listA, val=-1): # """ Unpacks a list into a list of lists. # # Returns a list of lists by splitting the input list # into 'N' lists when encounters an element equal to # 'val'. Empty lists resulting of trailing values at the # end of the list are discarded. # # Source: https://stackoverflow.com/questions/4322705/split-a-list-into-nested-lists-on-a-value # # Parameters # ---------- # listA : list # A list. # val : int/float, optional # Value to separate the lists. # # Returns # ------- # list # A list of lists. # # Examples # -------- # Unpack a list into a list of lists. # # >>> from dbcollection.utils.pad import unsqueeze_list # >>> unsqueeze_list([1, 2, -1, 3, -1, 4, 5, 6], -1) # [[1, 2], [3], [4, 5, 6]] # # """ # return [list(g) for k, g in itertools.groupby(listA, lambda x:x in (val, )) if not k] . Output only the next line.
assert(output == pad_list(sample, fill_value))
Given snippet: <|code_start|>#!/usr/bin/env python3 """ Test loading Pascal VOC 2012. """ # setup name = 'pascal_voc_2012' task = 'detection' data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data') verbose = True # Run tester <|code_end|> , continue by predicting the next line. Consider current file imports: import os from dbcollection.utils.test import TestBaseDB and context: # Path: dbcollection/utils/test.py # class TestBaseDB: # """ Test Class for loading datasets. # # Parameters # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool, optional # Be verbose. # # Attributes # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool # Be verbose. # # """ # # def __init__(self, name, task, data_dir, verbose=True): # """Initialize class.""" # assert name, "Must insert input arg: name" # assert task, "Must insert input arg: task" # assert data_dir, "Must insert input arg: data_dir" # # self.name = name # self.task = task # self.data_dir = data_dir # self.verbose = verbose # # def delete_cache(self): # """Delete all cache data + dir""" # print('\n==> dbcollection: config_cache()') # dbc.cache(delete_cache=True) # # def list_datasets(self): # """Print dbcollection info""" # print('\n==> dbcollection: info()') # dbc.info() # # def print_info(self, loader): # """Print information about the dataset to the screen # # Parameters # ---------- # loader : DataLoader # Data loader object of a dataset. # """ # print('\n######### info #########') # print('Dataset: ' + loader.db_name) # print('Task: ' + loader.task) # print('Data path: ' + loader.data_dir) # print('Metadata cache path: ' + loader.hdf5_filepath) # # def load(self): # """Return a data loader object for a dataset. # # Returns # ------- # DataLoader # A data loader object of a dataset. # """ # print('\n==> dbcollection: load()') # return dbc.load(name=self.name, # task=self.task, # data_dir=self.data_dir, # verbose=self.verbose) # # def download(self, extract_data=True): # """Download a dataset to disk. # # Parameters # ---------- # extract_data : bool # Flag signaling to extract data to disk (if True). # """ # print('\n==> dbcollection: download()') # dbc.download(name=self.name, # data_dir=self.data_dir, # extract_data=extract_data, # verbose=self.verbose) # # def process(self): # """Process dataset""" # print('\n==> dbcollection: process()') # dbc.process(name=self.name, # task=self.task, # verbose=self.verbose) # # def run(self, mode): # """Run the test script. # # Parameters # ---------- # mode : str # Task name to execute. # # Raises # ------ # Exception # If an invalid mode was inserted. # """ # assert mode, 'Must insert input arg: mode' # # # delete all cache data + dir # self.delete_cache() # # if mode is 'load': # # download/setup dataset # loader = self.load() # # # print data from the loader # self.print_info(loader) # # elif mode is 'download': # # download dataset # self.download() # # elif mode is 'process': # # download dataset # self.download(False) # # # process dataset task # self.process() # # else: # raise Exception('Invalid mode:', mode) # # # print data from the loader # self.list_datasets() # # # delete all cache data + dir before terminating # self.delete_cache() which might include code, classes, or functions. Output only the next line.
tester = TestBaseDB(name, task, data_dir, verbose)
Given snippet: <|code_start|>""" Test dbcollection core API: remove. """ @pytest.fixture() def mocks_init_class(mocker): <|code_end|> , continue by predicting the next line. Consider current file imports: import pytest from dbcollection.core.api.remove import remove, RemoveAPI and context: # Path: dbcollection/core/api/remove.py # def remove(name, task='', delete_data=False, verbose=True): # """Remove/delete a dataset and/or task from the cache. # # Removes the dataset's information registry from the dbcollection.json cache file. # The dataset's data files remain in disk if 'delete_data' is not enabled. # If you intended to remove the data files as well, the 'delete_data' input arg # must be set to 'True' in order to also remove the data files. # # Moreover, if the intended action is to remove a task of the dataset from the cache # registry, this can be achieved by specifying the task name to be deleted. This # effectively removes only that task entry for the dataset. Note that deleting a task # results in removing the associated HDF5 metadata file from disk. # # Parameters # ---------- # name : str # Name of the dataset to delete. # task : str, optional # Name of the task to delete. # delete_data : bool, optional # Delete all data files from disk for this dataset if True. # verbose : bool, optional # Displays text information (if true). # # Examples # -------- # Remove a dataset from the list. # # >>> import dbcollection as dbc # >>> # add a dataset # >>> dbc.add('new_db', 'new_task', 'new/path/db', 'newdb.h5', ['new_category']) # >>> dbc.query('new_db') # {'new_db': {'tasks': {'new_task': 'newdb.h5'}, 'data_dir': 'new/path/db', # 'keywords': ['new_category']}} # >>> dbc.remove('new_db') # remove the dataset # Removed 'new_db' dataset: cache=True, disk=False # >>> dbc.query('new_db') # check if the dataset info was removed (retrieves an empty dict) # {} # # """ # assert name, 'Must input a valid dataset name.' # # db_remover = RemoveAPI(name=name, # task=task, # delete_data=delete_data, # verbose=verbose) # # db_remover.run() # # class RemoveAPI(object): # """Dataset remove API class. # # This class contains methods to remove # a dataset registry from cache. Also, it # can remove the dataset's files from disk # if needed. # # Parameters # ---------- # name : str # Name of the dataset to delete. # task : str, optional # Name of the task to delete. # delete_data : bool # Delete all data files from disk for this dataset if True. # # Attributes # ---------- # name : str # Name of the dataset to delete. # task : str # Name of the task to delete. # delete_data : bool # Delete all data files from disk for this dataset if True. # cache_manager : CacheManager # Cache manager object. # # """ # # def __init__(self, name, task, delete_data, verbose): # """Initialize class.""" # assert isinstance(name, str), 'Must input a valid dataset name.' # assert isinstance(task, str), 'Must input a valid task name.' # assert isinstance(delete_data, bool), "Must input a valid boolean for delete_data." # assert isinstance(verbose, bool), "Must input a valid boolean for verbose." # # self.name = name # self.task = task # self.delete_data = delete_data # self.verbose = verbose # self.cache_manager = self.get_cache_manager() # # def get_cache_manager(self): # return CacheManager() # # def run(self): # """Main method.""" # self.remove_dataset() # # if self.verbose: # self.print_msg_registry_removal() # # def remove_dataset(self): # """Removes the dataset from cache (and disk if selected).""" # if self.exists_dataset(): # self.remove_registry_from_cache() # else: # raise Exception('Dataset \'{}\' does not exist in the cache.'.format(self.name)) # # def exists_dataset(self): # """Return True if a dataset name exists in the cache.""" # return self.cache_manager.dataset.exists(self.name) # # def remove_registry_from_cache(self): # """Remove the dataset or task from cache.""" # if any(self.task): # self.remove_task_registry() # else: # self.remove_dataset_registry() # # def remove_dataset_registry(self): # """Removes the dataset registry from cache.""" # if self.delete_data: # self.remove_dataset_data_files_from_disk() # self.remove_dataset_entry_from_cache() # # def remove_dataset_data_files_from_disk(self): # """Removes the directory containing the data files from disk.""" # data_dir = self.get_dataset_data_dir() # shutil.rmtree(data_dir) # # def get_dataset_data_dir(self): # dataset_metadata = self.cache_manager.dataset.get(self.name) # return dataset_metadata["data_dir"] # # def remove_dataset_entry_from_cache(self): # """Removes the dataset registry from cache.""" # self.cache_manager.dataset.delete(self.name) # # def remove_task_registry(self): # """Remove the task registry for this dataset from cache.""" # self.cache_manager.task.delete(self.name, self.task) # # def print_msg_registry_removal(self): # """Prints to screen the success message.""" # if any(self.task): # print('Removed the task \'{}\' from the \'{}\' dataset: cache=True' # .format(self.task, self.name)) # else: # print('Removed \'{}\' dataset: cache=True, disk={}' # .format(self.name, self.delete_data)) which might include code, classes, or functions. Output only the next line.
mock_cache = mocker.patch.object(RemoveAPI, "get_cache_manager", return_value=True)
Given the following code snippet before the placeholder: <|code_start|> Name of the dataset. data_dir : str Directory path to store the downloaded data. save_data_dir : str Data files save dir path. save_cache_dir : str Cache save dir path. extract_data : bool Flag to extract data (if True). verbose : bool Flag to display text information (if true). cache_manager : CacheManager Cache manager object. """ def __init__(self, name, data_dir, extract_data, verbose): """Initialize class.""" assert isinstance(name, str), 'Must input a valid dataset name.' assert isinstance(data_dir, str), 'Must input a valid directory.' assert isinstance(extract_data, bool), "Must input a valid boolean for extract_data." assert isinstance(verbose, bool), "Must input a valid boolean for verbose." self.name = name self.data_dir = data_dir self.extract_data = extract_data self.verbose = verbose self.cache_manager = self.get_cache_manager() def get_cache_manager(self): <|code_end|> , predict the next line using imports from the current file: import os from dbcollection.core.manager import CacheManager from .metadata import MetadataConstructor and context including class names, function names, and sometimes code from other files: # Path: dbcollection/core/manager.py # class CacheManager: # """Manage dbcollection configurations and stores them inside a cache file stored in disk. # # Attributes # ---------- # cache_filename : str # Cache file path + name. # cache_dir : str # Default directory to store all dataset's metadata files. # download_dir : str # Default save dir path for downloaded data. # data : dict # Cache contents. # # """ # # def __init__(self): # """Initializes the class.""" # self.manager = CacheDataManager() # self.info = CacheManagerInfo(self.manager) # self.dataset = CacheManagerDataset(self.manager) # self.task = CacheManagerTask(self.manager) # self.category = CacheManagerCategory(self.manager) # # def info_cache(self): # """Prints the information of the cache.""" # self.info.info() # self.dataset.info() # self.category.info() # # Path: dbcollection/core/api/metadata.py # class MetadataConstructor(object): # """Manages a dataset's metadata and constructor states. # # Parameters # ---------- # name : str # Name of the dataset. # # Attributes # ---------- # name : str # Name of the dataset. # dataset_manager : dict # Metadata retrieved from the available datasets database. # # """ # # def __init__(self, name): # """Initialize class.""" # assert name, "Must input a valid dataset name." # self.name = name # self.metadata_datasets = self.get_metadata_datasets() # self.dataset_manager = self.get_dataset_metadata_from_database(name) # # def get_metadata_datasets(self): # return fetch_list_datasets() # # def get_dataset_metadata_from_database(self, name): # """Returns the metadata and constructor class generator for a dataset.""" # try: # return self.metadata_datasets[name] # except KeyError: # raise KeyError("Dataset '{}' does not exist in the database.".format(name)) # # def get_default_task(self): # """Returns the default task for the dataset.""" # return self.dataset_manager["default_task"] # # def parse_task_name(self, task): # """Parse the input task string.""" # assert isinstance(task, str), "Must input a string as a valid task name." # if task == '': # task_parsed = self.get_default_task() # elif task == 'default': # task_parsed = self.get_default_task() # else: # task_parsed = task # return task_parsed # # def get_tasks(self): # """Returns the available tasks of the dataset.""" # return self.dataset_manager["tasks"] # # def get_keywords(self, task): # """Get the keywords for a task of a dataset.""" # pass # # def get_constructor(self): # """Returns the constructor class to generate the dataset's metadata.""" # return self.dataset_manager["constructor"] . Output only the next line.
return CacheManager()
Here is a snippet: <|code_start|> def run(self): """Main method.""" if not self.exists_dataset_in_cache(): if self.verbose: print('==> Download {} data to disk...'.format(self.name)) self.download_dataset() if self.verbose: print('==> Dataset download complete.') self.update_cache() if self.verbose: print('==> Updating the cache manager') def exists_dataset_in_cache(self): return self.cache_manager.dataset.exists(self.name) def download_dataset(self): """Download the dataset to disk.""" data_dir = self.get_download_data_dir() cache_dir = self.get_download_cache_dir() self.download_dataset_files(data_dir, cache_dir) def get_dataset_constructor(self): db_metadata = self.get_dataset_metadata_obj(self.name) constructor = db_metadata.get_constructor() return constructor def get_dataset_metadata_obj(self, name): <|code_end|> . Write the next line using the current file imports: import os from dbcollection.core.manager import CacheManager from .metadata import MetadataConstructor and context from other files: # Path: dbcollection/core/manager.py # class CacheManager: # """Manage dbcollection configurations and stores them inside a cache file stored in disk. # # Attributes # ---------- # cache_filename : str # Cache file path + name. # cache_dir : str # Default directory to store all dataset's metadata files. # download_dir : str # Default save dir path for downloaded data. # data : dict # Cache contents. # # """ # # def __init__(self): # """Initializes the class.""" # self.manager = CacheDataManager() # self.info = CacheManagerInfo(self.manager) # self.dataset = CacheManagerDataset(self.manager) # self.task = CacheManagerTask(self.manager) # self.category = CacheManagerCategory(self.manager) # # def info_cache(self): # """Prints the information of the cache.""" # self.info.info() # self.dataset.info() # self.category.info() # # Path: dbcollection/core/api/metadata.py # class MetadataConstructor(object): # """Manages a dataset's metadata and constructor states. # # Parameters # ---------- # name : str # Name of the dataset. # # Attributes # ---------- # name : str # Name of the dataset. # dataset_manager : dict # Metadata retrieved from the available datasets database. # # """ # # def __init__(self, name): # """Initialize class.""" # assert name, "Must input a valid dataset name." # self.name = name # self.metadata_datasets = self.get_metadata_datasets() # self.dataset_manager = self.get_dataset_metadata_from_database(name) # # def get_metadata_datasets(self): # return fetch_list_datasets() # # def get_dataset_metadata_from_database(self, name): # """Returns the metadata and constructor class generator for a dataset.""" # try: # return self.metadata_datasets[name] # except KeyError: # raise KeyError("Dataset '{}' does not exist in the database.".format(name)) # # def get_default_task(self): # """Returns the default task for the dataset.""" # return self.dataset_manager["default_task"] # # def parse_task_name(self, task): # """Parse the input task string.""" # assert isinstance(task, str), "Must input a string as a valid task name." # if task == '': # task_parsed = self.get_default_task() # elif task == 'default': # task_parsed = self.get_default_task() # else: # task_parsed = task # return task_parsed # # def get_tasks(self): # """Returns the available tasks of the dataset.""" # return self.dataset_manager["tasks"] # # def get_keywords(self, task): # """Get the keywords for a task of a dataset.""" # pass # # def get_constructor(self): # """Returns the constructor class to generate the dataset's metadata.""" # return self.dataset_manager["constructor"] , which may include functions, classes, or code. Output only the next line.
return MetadataConstructor(name)
Using the snippet: <|code_start|>#!/usr/bin/env python3 """ Test loading ucf101. """ # setup name = 'ucf101' task = 'recognition' data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data') verbose = True # Run tester <|code_end|> , determine the next line of code. You have imports: import os from dbcollection.utils.test import TestBaseDB and context (class names, function names, or code) available: # Path: dbcollection/utils/test.py # class TestBaseDB: # """ Test Class for loading datasets. # # Parameters # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool, optional # Be verbose. # # Attributes # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool # Be verbose. # # """ # # def __init__(self, name, task, data_dir, verbose=True): # """Initialize class.""" # assert name, "Must insert input arg: name" # assert task, "Must insert input arg: task" # assert data_dir, "Must insert input arg: data_dir" # # self.name = name # self.task = task # self.data_dir = data_dir # self.verbose = verbose # # def delete_cache(self): # """Delete all cache data + dir""" # print('\n==> dbcollection: config_cache()') # dbc.cache(delete_cache=True) # # def list_datasets(self): # """Print dbcollection info""" # print('\n==> dbcollection: info()') # dbc.info() # # def print_info(self, loader): # """Print information about the dataset to the screen # # Parameters # ---------- # loader : DataLoader # Data loader object of a dataset. # """ # print('\n######### info #########') # print('Dataset: ' + loader.db_name) # print('Task: ' + loader.task) # print('Data path: ' + loader.data_dir) # print('Metadata cache path: ' + loader.hdf5_filepath) # # def load(self): # """Return a data loader object for a dataset. # # Returns # ------- # DataLoader # A data loader object of a dataset. # """ # print('\n==> dbcollection: load()') # return dbc.load(name=self.name, # task=self.task, # data_dir=self.data_dir, # verbose=self.verbose) # # def download(self, extract_data=True): # """Download a dataset to disk. # # Parameters # ---------- # extract_data : bool # Flag signaling to extract data to disk (if True). # """ # print('\n==> dbcollection: download()') # dbc.download(name=self.name, # data_dir=self.data_dir, # extract_data=extract_data, # verbose=self.verbose) # # def process(self): # """Process dataset""" # print('\n==> dbcollection: process()') # dbc.process(name=self.name, # task=self.task, # verbose=self.verbose) # # def run(self, mode): # """Run the test script. # # Parameters # ---------- # mode : str # Task name to execute. # # Raises # ------ # Exception # If an invalid mode was inserted. # """ # assert mode, 'Must insert input arg: mode' # # # delete all cache data + dir # self.delete_cache() # # if mode is 'load': # # download/setup dataset # loader = self.load() # # # print data from the loader # self.print_info(loader) # # elif mode is 'download': # # download dataset # self.download() # # elif mode is 'process': # # download dataset # self.download(False) # # # process dataset task # self.process() # # else: # raise Exception('Invalid mode:', mode) # # # print data from the loader # self.list_datasets() # # # delete all cache data + dir before terminating # self.delete_cache() . Output only the next line.
tester = TestBaseDB(name, task, data_dir, verbose)
Continue the code snippet: <|code_start|> delete_data : bool Delete all data files from disk for this dataset if True. Attributes ---------- name : str Name of the dataset to delete. task : str Name of the task to delete. delete_data : bool Delete all data files from disk for this dataset if True. cache_manager : CacheManager Cache manager object. """ def __init__(self, name, task, delete_data, verbose): """Initialize class.""" assert isinstance(name, str), 'Must input a valid dataset name.' assert isinstance(task, str), 'Must input a valid task name.' assert isinstance(delete_data, bool), "Must input a valid boolean for delete_data." assert isinstance(verbose, bool), "Must input a valid boolean for verbose." self.name = name self.task = task self.delete_data = delete_data self.verbose = verbose self.cache_manager = self.get_cache_manager() def get_cache_manager(self): <|code_end|> . Use current file imports: import shutil from dbcollection.core.manager import CacheManager and context (classes, functions, or code) from other files: # Path: dbcollection/core/manager.py # class CacheManager: # """Manage dbcollection configurations and stores them inside a cache file stored in disk. # # Attributes # ---------- # cache_filename : str # Cache file path + name. # cache_dir : str # Default directory to store all dataset's metadata files. # download_dir : str # Default save dir path for downloaded data. # data : dict # Cache contents. # # """ # # def __init__(self): # """Initializes the class.""" # self.manager = CacheDataManager() # self.info = CacheManagerInfo(self.manager) # self.dataset = CacheManagerDataset(self.manager) # self.task = CacheManagerTask(self.manager) # self.category = CacheManagerCategory(self.manager) # # def info_cache(self): # """Prints the information of the cache.""" # self.info.info() # self.dataset.info() # self.category.info() . Output only the next line.
return CacheManager()
Given the code snippet: <|code_start|>#!/usr/bin/env python """ Test processing coco. """ # setup name = 'coco' task = 'detection' data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data') verbose = True # Run tester <|code_end|> , generate the next line using the imports in this file: import os from dbcollection.utils.test import TestBaseDB and context (functions, classes, or occasionally code) from other files: # Path: dbcollection/utils/test.py # class TestBaseDB: # """ Test Class for loading datasets. # # Parameters # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool, optional # Be verbose. # # Attributes # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool # Be verbose. # # """ # # def __init__(self, name, task, data_dir, verbose=True): # """Initialize class.""" # assert name, "Must insert input arg: name" # assert task, "Must insert input arg: task" # assert data_dir, "Must insert input arg: data_dir" # # self.name = name # self.task = task # self.data_dir = data_dir # self.verbose = verbose # # def delete_cache(self): # """Delete all cache data + dir""" # print('\n==> dbcollection: config_cache()') # dbc.cache(delete_cache=True) # # def list_datasets(self): # """Print dbcollection info""" # print('\n==> dbcollection: info()') # dbc.info() # # def print_info(self, loader): # """Print information about the dataset to the screen # # Parameters # ---------- # loader : DataLoader # Data loader object of a dataset. # """ # print('\n######### info #########') # print('Dataset: ' + loader.db_name) # print('Task: ' + loader.task) # print('Data path: ' + loader.data_dir) # print('Metadata cache path: ' + loader.hdf5_filepath) # # def load(self): # """Return a data loader object for a dataset. # # Returns # ------- # DataLoader # A data loader object of a dataset. # """ # print('\n==> dbcollection: load()') # return dbc.load(name=self.name, # task=self.task, # data_dir=self.data_dir, # verbose=self.verbose) # # def download(self, extract_data=True): # """Download a dataset to disk. # # Parameters # ---------- # extract_data : bool # Flag signaling to extract data to disk (if True). # """ # print('\n==> dbcollection: download()') # dbc.download(name=self.name, # data_dir=self.data_dir, # extract_data=extract_data, # verbose=self.verbose) # # def process(self): # """Process dataset""" # print('\n==> dbcollection: process()') # dbc.process(name=self.name, # task=self.task, # verbose=self.verbose) # # def run(self, mode): # """Run the test script. # # Parameters # ---------- # mode : str # Task name to execute. # # Raises # ------ # Exception # If an invalid mode was inserted. # """ # assert mode, 'Must insert input arg: mode' # # # delete all cache data + dir # self.delete_cache() # # if mode is 'load': # # download/setup dataset # loader = self.load() # # # print data from the loader # self.print_info(loader) # # elif mode is 'download': # # download dataset # self.download() # # elif mode is 'process': # # download dataset # self.download(False) # # # process dataset task # self.process() # # else: # raise Exception('Invalid mode:', mode) # # # print data from the loader # self.list_datasets() # # # delete all cache data + dir before terminating # self.delete_cache() . Output only the next line.
tester = TestBaseDB(name, task, data_dir, verbose)
Given snippet: <|code_start|>#!/usr/bin/env python3 """ Test loading cifar100. """ # setup name = 'cifar100' task = 'classification' data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data') verbose = True # Run tester <|code_end|> , continue by predicting the next line. Consider current file imports: import os from dbcollection.utils.test import TestBaseDB and context: # Path: dbcollection/utils/test.py # class TestBaseDB: # """ Test Class for loading datasets. # # Parameters # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool, optional # Be verbose. # # Attributes # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool # Be verbose. # # """ # # def __init__(self, name, task, data_dir, verbose=True): # """Initialize class.""" # assert name, "Must insert input arg: name" # assert task, "Must insert input arg: task" # assert data_dir, "Must insert input arg: data_dir" # # self.name = name # self.task = task # self.data_dir = data_dir # self.verbose = verbose # # def delete_cache(self): # """Delete all cache data + dir""" # print('\n==> dbcollection: config_cache()') # dbc.cache(delete_cache=True) # # def list_datasets(self): # """Print dbcollection info""" # print('\n==> dbcollection: info()') # dbc.info() # # def print_info(self, loader): # """Print information about the dataset to the screen # # Parameters # ---------- # loader : DataLoader # Data loader object of a dataset. # """ # print('\n######### info #########') # print('Dataset: ' + loader.db_name) # print('Task: ' + loader.task) # print('Data path: ' + loader.data_dir) # print('Metadata cache path: ' + loader.hdf5_filepath) # # def load(self): # """Return a data loader object for a dataset. # # Returns # ------- # DataLoader # A data loader object of a dataset. # """ # print('\n==> dbcollection: load()') # return dbc.load(name=self.name, # task=self.task, # data_dir=self.data_dir, # verbose=self.verbose) # # def download(self, extract_data=True): # """Download a dataset to disk. # # Parameters # ---------- # extract_data : bool # Flag signaling to extract data to disk (if True). # """ # print('\n==> dbcollection: download()') # dbc.download(name=self.name, # data_dir=self.data_dir, # extract_data=extract_data, # verbose=self.verbose) # # def process(self): # """Process dataset""" # print('\n==> dbcollection: process()') # dbc.process(name=self.name, # task=self.task, # verbose=self.verbose) # # def run(self, mode): # """Run the test script. # # Parameters # ---------- # mode : str # Task name to execute. # # Raises # ------ # Exception # If an invalid mode was inserted. # """ # assert mode, 'Must insert input arg: mode' # # # delete all cache data + dir # self.delete_cache() # # if mode is 'load': # # download/setup dataset # loader = self.load() # # # print data from the loader # self.print_info(loader) # # elif mode is 'download': # # download dataset # self.download() # # elif mode is 'process': # # download dataset # self.download(False) # # # process dataset task # self.process() # # else: # raise Exception('Invalid mode:', mode) # # # print data from the loader # self.list_datasets() # # # delete all cache data + dir before terminating # self.delete_cache() which might include code, classes, or functions. Output only the next line.
tester = TestBaseDB(name, task, data_dir, verbose)
Given snippet: <|code_start|>#!/usr/bin/env python3 """ Test loading INRIA Pedestrian. """ # setup name = 'inria_pedestrian' task = 'detection' data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data') verbose = True # Run tester <|code_end|> , continue by predicting the next line. Consider current file imports: import os from dbcollection.utils.test import TestBaseDB and context: # Path: dbcollection/utils/test.py # class TestBaseDB: # """ Test Class for loading datasets. # # Parameters # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool, optional # Be verbose. # # Attributes # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool # Be verbose. # # """ # # def __init__(self, name, task, data_dir, verbose=True): # """Initialize class.""" # assert name, "Must insert input arg: name" # assert task, "Must insert input arg: task" # assert data_dir, "Must insert input arg: data_dir" # # self.name = name # self.task = task # self.data_dir = data_dir # self.verbose = verbose # # def delete_cache(self): # """Delete all cache data + dir""" # print('\n==> dbcollection: config_cache()') # dbc.cache(delete_cache=True) # # def list_datasets(self): # """Print dbcollection info""" # print('\n==> dbcollection: info()') # dbc.info() # # def print_info(self, loader): # """Print information about the dataset to the screen # # Parameters # ---------- # loader : DataLoader # Data loader object of a dataset. # """ # print('\n######### info #########') # print('Dataset: ' + loader.db_name) # print('Task: ' + loader.task) # print('Data path: ' + loader.data_dir) # print('Metadata cache path: ' + loader.hdf5_filepath) # # def load(self): # """Return a data loader object for a dataset. # # Returns # ------- # DataLoader # A data loader object of a dataset. # """ # print('\n==> dbcollection: load()') # return dbc.load(name=self.name, # task=self.task, # data_dir=self.data_dir, # verbose=self.verbose) # # def download(self, extract_data=True): # """Download a dataset to disk. # # Parameters # ---------- # extract_data : bool # Flag signaling to extract data to disk (if True). # """ # print('\n==> dbcollection: download()') # dbc.download(name=self.name, # data_dir=self.data_dir, # extract_data=extract_data, # verbose=self.verbose) # # def process(self): # """Process dataset""" # print('\n==> dbcollection: process()') # dbc.process(name=self.name, # task=self.task, # verbose=self.verbose) # # def run(self, mode): # """Run the test script. # # Parameters # ---------- # mode : str # Task name to execute. # # Raises # ------ # Exception # If an invalid mode was inserted. # """ # assert mode, 'Must insert input arg: mode' # # # delete all cache data + dir # self.delete_cache() # # if mode is 'load': # # download/setup dataset # loader = self.load() # # # print data from the loader # self.print_info(loader) # # elif mode is 'download': # # download dataset # self.download() # # elif mode is 'process': # # download dataset # self.download(False) # # # process dataset task # self.process() # # else: # raise Exception('Invalid mode:', mode) # # # print data from the loader # self.list_datasets() # # # delete all cache data + dir before terminating # self.delete_cache() which might include code, classes, or functions. Output only the next line.
tester = TestBaseDB(name, task, data_dir, verbose)
Continue the code snippet: <|code_start|>#!/usr/bin/env python3 """ Test loading Leeds Sports Pose. """ # setup name = 'leeds_sports_pose' task = 'keypoints' data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data') verbose = True # Run tester <|code_end|> . Use current file imports: import os from dbcollection.utils.test import TestBaseDB and context (classes, functions, or code) from other files: # Path: dbcollection/utils/test.py # class TestBaseDB: # """ Test Class for loading datasets. # # Parameters # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool, optional # Be verbose. # # Attributes # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool # Be verbose. # # """ # # def __init__(self, name, task, data_dir, verbose=True): # """Initialize class.""" # assert name, "Must insert input arg: name" # assert task, "Must insert input arg: task" # assert data_dir, "Must insert input arg: data_dir" # # self.name = name # self.task = task # self.data_dir = data_dir # self.verbose = verbose # # def delete_cache(self): # """Delete all cache data + dir""" # print('\n==> dbcollection: config_cache()') # dbc.cache(delete_cache=True) # # def list_datasets(self): # """Print dbcollection info""" # print('\n==> dbcollection: info()') # dbc.info() # # def print_info(self, loader): # """Print information about the dataset to the screen # # Parameters # ---------- # loader : DataLoader # Data loader object of a dataset. # """ # print('\n######### info #########') # print('Dataset: ' + loader.db_name) # print('Task: ' + loader.task) # print('Data path: ' + loader.data_dir) # print('Metadata cache path: ' + loader.hdf5_filepath) # # def load(self): # """Return a data loader object for a dataset. # # Returns # ------- # DataLoader # A data loader object of a dataset. # """ # print('\n==> dbcollection: load()') # return dbc.load(name=self.name, # task=self.task, # data_dir=self.data_dir, # verbose=self.verbose) # # def download(self, extract_data=True): # """Download a dataset to disk. # # Parameters # ---------- # extract_data : bool # Flag signaling to extract data to disk (if True). # """ # print('\n==> dbcollection: download()') # dbc.download(name=self.name, # data_dir=self.data_dir, # extract_data=extract_data, # verbose=self.verbose) # # def process(self): # """Process dataset""" # print('\n==> dbcollection: process()') # dbc.process(name=self.name, # task=self.task, # verbose=self.verbose) # # def run(self, mode): # """Run the test script. # # Parameters # ---------- # mode : str # Task name to execute. # # Raises # ------ # Exception # If an invalid mode was inserted. # """ # assert mode, 'Must insert input arg: mode' # # # delete all cache data + dir # self.delete_cache() # # if mode is 'load': # # download/setup dataset # loader = self.load() # # # print data from the loader # self.print_info(loader) # # elif mode is 'download': # # download dataset # self.download() # # elif mode is 'process': # # download dataset # self.download(False) # # # process dataset task # self.process() # # else: # raise Exception('Invalid mode:', mode) # # # print data from the loader # self.list_datasets() # # # delete all cache data + dir before terminating # self.delete_cache() . Output only the next line.
tester = TestBaseDB(name, task, data_dir, verbose)
Based on the snippet: <|code_start|>#!/usr/bin/env python3 """ Test loading coco. """ # setup name = 'coco' task = 'keypoints_2016' data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data') verbose = True # Run tester <|code_end|> , predict the immediate next line with the help of imports: import os from dbcollection.utils.test import TestBaseDB and context (classes, functions, sometimes code) from other files: # Path: dbcollection/utils/test.py # class TestBaseDB: # """ Test Class for loading datasets. # # Parameters # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool, optional # Be verbose. # # Attributes # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool # Be verbose. # # """ # # def __init__(self, name, task, data_dir, verbose=True): # """Initialize class.""" # assert name, "Must insert input arg: name" # assert task, "Must insert input arg: task" # assert data_dir, "Must insert input arg: data_dir" # # self.name = name # self.task = task # self.data_dir = data_dir # self.verbose = verbose # # def delete_cache(self): # """Delete all cache data + dir""" # print('\n==> dbcollection: config_cache()') # dbc.cache(delete_cache=True) # # def list_datasets(self): # """Print dbcollection info""" # print('\n==> dbcollection: info()') # dbc.info() # # def print_info(self, loader): # """Print information about the dataset to the screen # # Parameters # ---------- # loader : DataLoader # Data loader object of a dataset. # """ # print('\n######### info #########') # print('Dataset: ' + loader.db_name) # print('Task: ' + loader.task) # print('Data path: ' + loader.data_dir) # print('Metadata cache path: ' + loader.hdf5_filepath) # # def load(self): # """Return a data loader object for a dataset. # # Returns # ------- # DataLoader # A data loader object of a dataset. # """ # print('\n==> dbcollection: load()') # return dbc.load(name=self.name, # task=self.task, # data_dir=self.data_dir, # verbose=self.verbose) # # def download(self, extract_data=True): # """Download a dataset to disk. # # Parameters # ---------- # extract_data : bool # Flag signaling to extract data to disk (if True). # """ # print('\n==> dbcollection: download()') # dbc.download(name=self.name, # data_dir=self.data_dir, # extract_data=extract_data, # verbose=self.verbose) # # def process(self): # """Process dataset""" # print('\n==> dbcollection: process()') # dbc.process(name=self.name, # task=self.task, # verbose=self.verbose) # # def run(self, mode): # """Run the test script. # # Parameters # ---------- # mode : str # Task name to execute. # # Raises # ------ # Exception # If an invalid mode was inserted. # """ # assert mode, 'Must insert input arg: mode' # # # delete all cache data + dir # self.delete_cache() # # if mode is 'load': # # download/setup dataset # loader = self.load() # # # print data from the loader # self.print_info(loader) # # elif mode is 'download': # # download dataset # self.download() # # elif mode is 'process': # # download dataset # self.download(False) # # # process dataset task # self.process() # # else: # raise Exception('Invalid mode:', mode) # # # print data from the loader # self.list_datasets() # # # delete all cache data + dir before terminating # self.delete_cache() . Output only the next line.
tester = TestBaseDB(name, task, data_dir, verbose)
Continue the code snippet: <|code_start|>#!/usr/bin/env python3 """ Test loading Caltech Pedestrian. """ # setup name = 'caltech_pedestrian' task = 'detection' data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data') verbose = True # Run tester <|code_end|> . Use current file imports: import os from dbcollection.utils.test import TestBaseDB and context (classes, functions, or code) from other files: # Path: dbcollection/utils/test.py # class TestBaseDB: # """ Test Class for loading datasets. # # Parameters # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool, optional # Be verbose. # # Attributes # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool # Be verbose. # # """ # # def __init__(self, name, task, data_dir, verbose=True): # """Initialize class.""" # assert name, "Must insert input arg: name" # assert task, "Must insert input arg: task" # assert data_dir, "Must insert input arg: data_dir" # # self.name = name # self.task = task # self.data_dir = data_dir # self.verbose = verbose # # def delete_cache(self): # """Delete all cache data + dir""" # print('\n==> dbcollection: config_cache()') # dbc.cache(delete_cache=True) # # def list_datasets(self): # """Print dbcollection info""" # print('\n==> dbcollection: info()') # dbc.info() # # def print_info(self, loader): # """Print information about the dataset to the screen # # Parameters # ---------- # loader : DataLoader # Data loader object of a dataset. # """ # print('\n######### info #########') # print('Dataset: ' + loader.db_name) # print('Task: ' + loader.task) # print('Data path: ' + loader.data_dir) # print('Metadata cache path: ' + loader.hdf5_filepath) # # def load(self): # """Return a data loader object for a dataset. # # Returns # ------- # DataLoader # A data loader object of a dataset. # """ # print('\n==> dbcollection: load()') # return dbc.load(name=self.name, # task=self.task, # data_dir=self.data_dir, # verbose=self.verbose) # # def download(self, extract_data=True): # """Download a dataset to disk. # # Parameters # ---------- # extract_data : bool # Flag signaling to extract data to disk (if True). # """ # print('\n==> dbcollection: download()') # dbc.download(name=self.name, # data_dir=self.data_dir, # extract_data=extract_data, # verbose=self.verbose) # # def process(self): # """Process dataset""" # print('\n==> dbcollection: process()') # dbc.process(name=self.name, # task=self.task, # verbose=self.verbose) # # def run(self, mode): # """Run the test script. # # Parameters # ---------- # mode : str # Task name to execute. # # Raises # ------ # Exception # If an invalid mode was inserted. # """ # assert mode, 'Must insert input arg: mode' # # # delete all cache data + dir # self.delete_cache() # # if mode is 'load': # # download/setup dataset # loader = self.load() # # # print data from the loader # self.print_info(loader) # # elif mode is 'download': # # download dataset # self.download() # # elif mode is 'process': # # download dataset # self.download(False) # # # process dataset task # self.process() # # else: # raise Exception('Invalid mode:', mode) # # # print data from the loader # self.list_datasets() # # # delete all cache data + dir before terminating # self.delete_cache() . Output only the next line.
tester = TestBaseDB(name, task, data_dir, verbose)
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python3 """ Test loading mnist. """ # setup name = 'mnist' task = 'classification' data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data') verbose = True # Run tester <|code_end|> with the help of current file imports: import os from dbcollection.utils.test import TestBaseDB and context from other files: # Path: dbcollection/utils/test.py # class TestBaseDB: # """ Test Class for loading datasets. # # Parameters # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool, optional # Be verbose. # # Attributes # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool # Be verbose. # # """ # # def __init__(self, name, task, data_dir, verbose=True): # """Initialize class.""" # assert name, "Must insert input arg: name" # assert task, "Must insert input arg: task" # assert data_dir, "Must insert input arg: data_dir" # # self.name = name # self.task = task # self.data_dir = data_dir # self.verbose = verbose # # def delete_cache(self): # """Delete all cache data + dir""" # print('\n==> dbcollection: config_cache()') # dbc.cache(delete_cache=True) # # def list_datasets(self): # """Print dbcollection info""" # print('\n==> dbcollection: info()') # dbc.info() # # def print_info(self, loader): # """Print information about the dataset to the screen # # Parameters # ---------- # loader : DataLoader # Data loader object of a dataset. # """ # print('\n######### info #########') # print('Dataset: ' + loader.db_name) # print('Task: ' + loader.task) # print('Data path: ' + loader.data_dir) # print('Metadata cache path: ' + loader.hdf5_filepath) # # def load(self): # """Return a data loader object for a dataset. # # Returns # ------- # DataLoader # A data loader object of a dataset. # """ # print('\n==> dbcollection: load()') # return dbc.load(name=self.name, # task=self.task, # data_dir=self.data_dir, # verbose=self.verbose) # # def download(self, extract_data=True): # """Download a dataset to disk. # # Parameters # ---------- # extract_data : bool # Flag signaling to extract data to disk (if True). # """ # print('\n==> dbcollection: download()') # dbc.download(name=self.name, # data_dir=self.data_dir, # extract_data=extract_data, # verbose=self.verbose) # # def process(self): # """Process dataset""" # print('\n==> dbcollection: process()') # dbc.process(name=self.name, # task=self.task, # verbose=self.verbose) # # def run(self, mode): # """Run the test script. # # Parameters # ---------- # mode : str # Task name to execute. # # Raises # ------ # Exception # If an invalid mode was inserted. # """ # assert mode, 'Must insert input arg: mode' # # # delete all cache data + dir # self.delete_cache() # # if mode is 'load': # # download/setup dataset # loader = self.load() # # # print data from the loader # self.print_info(loader) # # elif mode is 'download': # # download dataset # self.download() # # elif mode is 'process': # # download dataset # self.download(False) # # # process dataset task # self.process() # # else: # raise Exception('Invalid mode:', mode) # # # print data from the loader # self.list_datasets() # # # delete all cache data + dir before terminating # self.delete_cache() , which may contain function names, class names, or code. Output only the next line.
tester = TestBaseDB(name, task, data_dir, verbose)
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python3 """ Test loading Imagenet ilsvrc2012. """ # setup name = 'ilsvrc2012' task = 'classification' data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data') verbose = True # Run tester <|code_end|> with the help of current file imports: import os from dbcollection.utils.test import TestBaseDB and context from other files: # Path: dbcollection/utils/test.py # class TestBaseDB: # """ Test Class for loading datasets. # # Parameters # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool, optional # Be verbose. # # Attributes # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool # Be verbose. # # """ # # def __init__(self, name, task, data_dir, verbose=True): # """Initialize class.""" # assert name, "Must insert input arg: name" # assert task, "Must insert input arg: task" # assert data_dir, "Must insert input arg: data_dir" # # self.name = name # self.task = task # self.data_dir = data_dir # self.verbose = verbose # # def delete_cache(self): # """Delete all cache data + dir""" # print('\n==> dbcollection: config_cache()') # dbc.cache(delete_cache=True) # # def list_datasets(self): # """Print dbcollection info""" # print('\n==> dbcollection: info()') # dbc.info() # # def print_info(self, loader): # """Print information about the dataset to the screen # # Parameters # ---------- # loader : DataLoader # Data loader object of a dataset. # """ # print('\n######### info #########') # print('Dataset: ' + loader.db_name) # print('Task: ' + loader.task) # print('Data path: ' + loader.data_dir) # print('Metadata cache path: ' + loader.hdf5_filepath) # # def load(self): # """Return a data loader object for a dataset. # # Returns # ------- # DataLoader # A data loader object of a dataset. # """ # print('\n==> dbcollection: load()') # return dbc.load(name=self.name, # task=self.task, # data_dir=self.data_dir, # verbose=self.verbose) # # def download(self, extract_data=True): # """Download a dataset to disk. # # Parameters # ---------- # extract_data : bool # Flag signaling to extract data to disk (if True). # """ # print('\n==> dbcollection: download()') # dbc.download(name=self.name, # data_dir=self.data_dir, # extract_data=extract_data, # verbose=self.verbose) # # def process(self): # """Process dataset""" # print('\n==> dbcollection: process()') # dbc.process(name=self.name, # task=self.task, # verbose=self.verbose) # # def run(self, mode): # """Run the test script. # # Parameters # ---------- # mode : str # Task name to execute. # # Raises # ------ # Exception # If an invalid mode was inserted. # """ # assert mode, 'Must insert input arg: mode' # # # delete all cache data + dir # self.delete_cache() # # if mode is 'load': # # download/setup dataset # loader = self.load() # # # print data from the loader # self.print_info(loader) # # elif mode is 'download': # # download dataset # self.download() # # elif mode is 'process': # # download dataset # self.download(False) # # # process dataset task # self.process() # # else: # raise Exception('Invalid mode:', mode) # # # print data from the loader # self.list_datasets() # # # delete all cache data + dir before terminating # self.delete_cache() , which may contain function names, class names, or code. Output only the next line.
tester = TestBaseDB(name, task, data_dir, verbose)
Next line prediction: <|code_start|>#!/usr/bin/env python3 """ Test loading flic. """ # setup name = 'flic' task = 'keypoints' data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data') verbose = True # Run tester <|code_end|> . Use current file imports: (import os from dbcollection.utils.test import TestBaseDB) and context including class names, function names, or small code snippets from other files: # Path: dbcollection/utils/test.py # class TestBaseDB: # """ Test Class for loading datasets. # # Parameters # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool, optional # Be verbose. # # Attributes # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool # Be verbose. # # """ # # def __init__(self, name, task, data_dir, verbose=True): # """Initialize class.""" # assert name, "Must insert input arg: name" # assert task, "Must insert input arg: task" # assert data_dir, "Must insert input arg: data_dir" # # self.name = name # self.task = task # self.data_dir = data_dir # self.verbose = verbose # # def delete_cache(self): # """Delete all cache data + dir""" # print('\n==> dbcollection: config_cache()') # dbc.cache(delete_cache=True) # # def list_datasets(self): # """Print dbcollection info""" # print('\n==> dbcollection: info()') # dbc.info() # # def print_info(self, loader): # """Print information about the dataset to the screen # # Parameters # ---------- # loader : DataLoader # Data loader object of a dataset. # """ # print('\n######### info #########') # print('Dataset: ' + loader.db_name) # print('Task: ' + loader.task) # print('Data path: ' + loader.data_dir) # print('Metadata cache path: ' + loader.hdf5_filepath) # # def load(self): # """Return a data loader object for a dataset. # # Returns # ------- # DataLoader # A data loader object of a dataset. # """ # print('\n==> dbcollection: load()') # return dbc.load(name=self.name, # task=self.task, # data_dir=self.data_dir, # verbose=self.verbose) # # def download(self, extract_data=True): # """Download a dataset to disk. # # Parameters # ---------- # extract_data : bool # Flag signaling to extract data to disk (if True). # """ # print('\n==> dbcollection: download()') # dbc.download(name=self.name, # data_dir=self.data_dir, # extract_data=extract_data, # verbose=self.verbose) # # def process(self): # """Process dataset""" # print('\n==> dbcollection: process()') # dbc.process(name=self.name, # task=self.task, # verbose=self.verbose) # # def run(self, mode): # """Run the test script. # # Parameters # ---------- # mode : str # Task name to execute. # # Raises # ------ # Exception # If an invalid mode was inserted. # """ # assert mode, 'Must insert input arg: mode' # # # delete all cache data + dir # self.delete_cache() # # if mode is 'load': # # download/setup dataset # loader = self.load() # # # print data from the loader # self.print_info(loader) # # elif mode is 'download': # # download dataset # self.download() # # elif mode is 'process': # # download dataset # self.download(False) # # # process dataset task # self.process() # # else: # raise Exception('Invalid mode:', mode) # # # print data from the loader # self.list_datasets() # # # delete all cache data + dir before terminating # self.delete_cache() . Output only the next line.
tester = TestBaseDB(name, task, data_dir, verbose)
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python3 """ Test loading cifar10. """ # setup name = 'cifar10' task = 'classification' data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data') verbose = True # Run tester <|code_end|> using the current file's imports: import os from dbcollection.utils.test import TestBaseDB and any relevant context from other files: # Path: dbcollection/utils/test.py # class TestBaseDB: # """ Test Class for loading datasets. # # Parameters # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool, optional # Be verbose. # # Attributes # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool # Be verbose. # # """ # # def __init__(self, name, task, data_dir, verbose=True): # """Initialize class.""" # assert name, "Must insert input arg: name" # assert task, "Must insert input arg: task" # assert data_dir, "Must insert input arg: data_dir" # # self.name = name # self.task = task # self.data_dir = data_dir # self.verbose = verbose # # def delete_cache(self): # """Delete all cache data + dir""" # print('\n==> dbcollection: config_cache()') # dbc.cache(delete_cache=True) # # def list_datasets(self): # """Print dbcollection info""" # print('\n==> dbcollection: info()') # dbc.info() # # def print_info(self, loader): # """Print information about the dataset to the screen # # Parameters # ---------- # loader : DataLoader # Data loader object of a dataset. # """ # print('\n######### info #########') # print('Dataset: ' + loader.db_name) # print('Task: ' + loader.task) # print('Data path: ' + loader.data_dir) # print('Metadata cache path: ' + loader.hdf5_filepath) # # def load(self): # """Return a data loader object for a dataset. # # Returns # ------- # DataLoader # A data loader object of a dataset. # """ # print('\n==> dbcollection: load()') # return dbc.load(name=self.name, # task=self.task, # data_dir=self.data_dir, # verbose=self.verbose) # # def download(self, extract_data=True): # """Download a dataset to disk. # # Parameters # ---------- # extract_data : bool # Flag signaling to extract data to disk (if True). # """ # print('\n==> dbcollection: download()') # dbc.download(name=self.name, # data_dir=self.data_dir, # extract_data=extract_data, # verbose=self.verbose) # # def process(self): # """Process dataset""" # print('\n==> dbcollection: process()') # dbc.process(name=self.name, # task=self.task, # verbose=self.verbose) # # def run(self, mode): # """Run the test script. # # Parameters # ---------- # mode : str # Task name to execute. # # Raises # ------ # Exception # If an invalid mode was inserted. # """ # assert mode, 'Must insert input arg: mode' # # # delete all cache data + dir # self.delete_cache() # # if mode is 'load': # # download/setup dataset # loader = self.load() # # # print data from the loader # self.print_info(loader) # # elif mode is 'download': # # download dataset # self.download() # # elif mode is 'process': # # download dataset # self.download(False) # # # process dataset task # self.process() # # else: # raise Exception('Invalid mode:', mode) # # # print data from the loader # self.list_datasets() # # # delete all cache data + dir before terminating # self.delete_cache() . Output only the next line.
tester = TestBaseDB(name, task, data_dir, verbose)
Next line prediction: <|code_start|> Name of the dataset. task : str Name of the task to process. verbose : bool Displays text information (if true). extract_data : bool Flag to extract data (if True). cache_manager : CacheManager Cache manager object. Raises ------ KeyError If a task does not exist for a dataset. """ def __init__(self, name, task, verbose): """Initialize class.""" assert isinstance(name, str), 'Must input a valid dataset name.' assert isinstance(task, str), 'Must input a valid task name.' assert isinstance(verbose, bool), "Must input a valid boolean for verbose." self.name = name self.task = task self.verbose = verbose self.extract_data = False self.cache_manager = self.get_cache_manager() def get_cache_manager(self): <|code_end|> . Use current file imports: (import os from dbcollection.core.manager import CacheManager from .metadata import MetadataConstructor) and context including class names, function names, or small code snippets from other files: # Path: dbcollection/core/manager.py # class CacheManager: # """Manage dbcollection configurations and stores them inside a cache file stored in disk. # # Attributes # ---------- # cache_filename : str # Cache file path + name. # cache_dir : str # Default directory to store all dataset's metadata files. # download_dir : str # Default save dir path for downloaded data. # data : dict # Cache contents. # # """ # # def __init__(self): # """Initializes the class.""" # self.manager = CacheDataManager() # self.info = CacheManagerInfo(self.manager) # self.dataset = CacheManagerDataset(self.manager) # self.task = CacheManagerTask(self.manager) # self.category = CacheManagerCategory(self.manager) # # def info_cache(self): # """Prints the information of the cache.""" # self.info.info() # self.dataset.info() # self.category.info() # # Path: dbcollection/core/api/metadata.py # class MetadataConstructor(object): # """Manages a dataset's metadata and constructor states. # # Parameters # ---------- # name : str # Name of the dataset. # # Attributes # ---------- # name : str # Name of the dataset. # dataset_manager : dict # Metadata retrieved from the available datasets database. # # """ # # def __init__(self, name): # """Initialize class.""" # assert name, "Must input a valid dataset name." # self.name = name # self.metadata_datasets = self.get_metadata_datasets() # self.dataset_manager = self.get_dataset_metadata_from_database(name) # # def get_metadata_datasets(self): # return fetch_list_datasets() # # def get_dataset_metadata_from_database(self, name): # """Returns the metadata and constructor class generator for a dataset.""" # try: # return self.metadata_datasets[name] # except KeyError: # raise KeyError("Dataset '{}' does not exist in the database.".format(name)) # # def get_default_task(self): # """Returns the default task for the dataset.""" # return self.dataset_manager["default_task"] # # def parse_task_name(self, task): # """Parse the input task string.""" # assert isinstance(task, str), "Must input a string as a valid task name." # if task == '': # task_parsed = self.get_default_task() # elif task == 'default': # task_parsed = self.get_default_task() # else: # task_parsed = task # return task_parsed # # def get_tasks(self): # """Returns the available tasks of the dataset.""" # return self.dataset_manager["tasks"] # # def get_keywords(self, task): # """Get the keywords for a task of a dataset.""" # pass # # def get_constructor(self): # """Returns the constructor class to generate the dataset's metadata.""" # return self.dataset_manager["constructor"] . Output only the next line.
return CacheManager()
Continue the code snippet: <|code_start|> def set_dirs_processed_metadata(self): cache_dir = self.get_dataset_cache_dir_path() self.create_dir(cache_dir) def get_dataset_cache_dir_path(self): cache_dir = self.get_cache_dir_path_from_cache() return os.path.join(cache_dir, self.name) def get_cache_dir_path_from_cache(self): return self.cache_manager.info.cache_dir def create_dir(self, path): """Create a directory in the disk.""" if not os.path.exists(path): os.makedirs(path) def process_dataset(self): """Process the dataset's metadata.""" data_dir = self.get_dataset_data_dir_path() cache_dir = self.get_dataset_cache_dir_path() task = self.parse_task_name(self.task) self.check_if_task_exists_in_database(task) return self.process_dataset_metadata(data_dir, cache_dir, task) def get_dataset_constructor(self): db_metadata = self.get_dataset_metadata_obj(self.name) constructor = db_metadata.get_constructor() return constructor def get_dataset_metadata_obj(self, name): <|code_end|> . Use current file imports: import os from dbcollection.core.manager import CacheManager from .metadata import MetadataConstructor and context (classes, functions, or code) from other files: # Path: dbcollection/core/manager.py # class CacheManager: # """Manage dbcollection configurations and stores them inside a cache file stored in disk. # # Attributes # ---------- # cache_filename : str # Cache file path + name. # cache_dir : str # Default directory to store all dataset's metadata files. # download_dir : str # Default save dir path for downloaded data. # data : dict # Cache contents. # # """ # # def __init__(self): # """Initializes the class.""" # self.manager = CacheDataManager() # self.info = CacheManagerInfo(self.manager) # self.dataset = CacheManagerDataset(self.manager) # self.task = CacheManagerTask(self.manager) # self.category = CacheManagerCategory(self.manager) # # def info_cache(self): # """Prints the information of the cache.""" # self.info.info() # self.dataset.info() # self.category.info() # # Path: dbcollection/core/api/metadata.py # class MetadataConstructor(object): # """Manages a dataset's metadata and constructor states. # # Parameters # ---------- # name : str # Name of the dataset. # # Attributes # ---------- # name : str # Name of the dataset. # dataset_manager : dict # Metadata retrieved from the available datasets database. # # """ # # def __init__(self, name): # """Initialize class.""" # assert name, "Must input a valid dataset name." # self.name = name # self.metadata_datasets = self.get_metadata_datasets() # self.dataset_manager = self.get_dataset_metadata_from_database(name) # # def get_metadata_datasets(self): # return fetch_list_datasets() # # def get_dataset_metadata_from_database(self, name): # """Returns the metadata and constructor class generator for a dataset.""" # try: # return self.metadata_datasets[name] # except KeyError: # raise KeyError("Dataset '{}' does not exist in the database.".format(name)) # # def get_default_task(self): # """Returns the default task for the dataset.""" # return self.dataset_manager["default_task"] # # def parse_task_name(self, task): # """Parse the input task string.""" # assert isinstance(task, str), "Must input a string as a valid task name." # if task == '': # task_parsed = self.get_default_task() # elif task == 'default': # task_parsed = self.get_default_task() # else: # task_parsed = task # return task_parsed # # def get_tasks(self): # """Returns the available tasks of the dataset.""" # return self.dataset_manager["tasks"] # # def get_keywords(self, task): # """Get the keywords for a task of a dataset.""" # pass # # def get_constructor(self): # """Returns the constructor class to generate the dataset's metadata.""" # return self.dataset_manager["constructor"] . Output only the next line.
return MetadataConstructor(name)
Continue the code snippet: <|code_start|>#!/usr/bin/env python3 """ Test loading cifar10. """ # setup name = 'cifar10' task = 'classification' data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data') verbose = True # Run tester <|code_end|> . Use current file imports: import os from dbcollection.utils.test import TestBaseDB and context (classes, functions, or code) from other files: # Path: dbcollection/utils/test.py # class TestBaseDB: # """ Test Class for loading datasets. # # Parameters # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool, optional # Be verbose. # # Attributes # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool # Be verbose. # # """ # # def __init__(self, name, task, data_dir, verbose=True): # """Initialize class.""" # assert name, "Must insert input arg: name" # assert task, "Must insert input arg: task" # assert data_dir, "Must insert input arg: data_dir" # # self.name = name # self.task = task # self.data_dir = data_dir # self.verbose = verbose # # def delete_cache(self): # """Delete all cache data + dir""" # print('\n==> dbcollection: config_cache()') # dbc.cache(delete_cache=True) # # def list_datasets(self): # """Print dbcollection info""" # print('\n==> dbcollection: info()') # dbc.info() # # def print_info(self, loader): # """Print information about the dataset to the screen # # Parameters # ---------- # loader : DataLoader # Data loader object of a dataset. # """ # print('\n######### info #########') # print('Dataset: ' + loader.db_name) # print('Task: ' + loader.task) # print('Data path: ' + loader.data_dir) # print('Metadata cache path: ' + loader.hdf5_filepath) # # def load(self): # """Return a data loader object for a dataset. # # Returns # ------- # DataLoader # A data loader object of a dataset. # """ # print('\n==> dbcollection: load()') # return dbc.load(name=self.name, # task=self.task, # data_dir=self.data_dir, # verbose=self.verbose) # # def download(self, extract_data=True): # """Download a dataset to disk. # # Parameters # ---------- # extract_data : bool # Flag signaling to extract data to disk (if True). # """ # print('\n==> dbcollection: download()') # dbc.download(name=self.name, # data_dir=self.data_dir, # extract_data=extract_data, # verbose=self.verbose) # # def process(self): # """Process dataset""" # print('\n==> dbcollection: process()') # dbc.process(name=self.name, # task=self.task, # verbose=self.verbose) # # def run(self, mode): # """Run the test script. # # Parameters # ---------- # mode : str # Task name to execute. # # Raises # ------ # Exception # If an invalid mode was inserted. # """ # assert mode, 'Must insert input arg: mode' # # # delete all cache data + dir # self.delete_cache() # # if mode is 'load': # # download/setup dataset # loader = self.load() # # # print data from the loader # self.print_info(loader) # # elif mode is 'download': # # download dataset # self.download() # # elif mode is 'process': # # download dataset # self.download(False) # # # process dataset task # self.process() # # else: # raise Exception('Invalid mode:', mode) # # # print data from the loader # self.list_datasets() # # # delete all cache data + dir before terminating # self.delete_cache() . Output only the next line.
tester = TestBaseDB(name, task, data_dir, verbose)
Predict the next line for this snippet: <|code_start|>""" Test dataset's urls download status. """ TIMEOUT_SECONDS = 3 @pytest.mark.parametrize("dataset_name, urls", get_list_urls_dataset()) @pytest.mark.slow def test_check_urls_are_valid(dataset_name, urls): for url in urls: response = requests.head(url) # try without redirect enabled if response.status_code == 200: status = True else: if response.status_code == 301: <|code_end|> with the help of current file imports: import requests import pytest from dbcollection.utils.test import check_url_redirect from dbcollection.core.api.metadata import get_list_urls_dataset and context from other files: # Path: dbcollection/utils/test.py # def check_url_redirect(url, timeout_seconds=3): # try: # with Timeout(timeout_seconds): # response = requests.get(url) # return response.status_code == 200 # except Timeout.Timeout: # return True # # Path: dbcollection/core/api/metadata.py # def get_list_urls_dataset(): # available_datasets = fetch_list_datasets() # dataset_urls = [] # for name in available_datasets: # urls = available_datasets[name]['urls'] # url_list = get_urls_list(urls) # dataset_urls.append((name, url_list)) # return dataset_urls , which may contain function names, class names, or code. Output only the next line.
status = check_url_redirect(url, TIMEOUT_SECONDS) # try with redirect enabled
Next line prediction: <|code_start|>#!/usr/bin/env python """ Test loading ucf sports. """ # setup name = 'ucf_sports' task = 'recognition' data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data') verbose = True # Run tester <|code_end|> . Use current file imports: (import os from dbcollection.utils.test import TestBaseDB) and context including class names, function names, or small code snippets from other files: # Path: dbcollection/utils/test.py # class TestBaseDB: # """ Test Class for loading datasets. # # Parameters # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool, optional # Be verbose. # # Attributes # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool # Be verbose. # # """ # # def __init__(self, name, task, data_dir, verbose=True): # """Initialize class.""" # assert name, "Must insert input arg: name" # assert task, "Must insert input arg: task" # assert data_dir, "Must insert input arg: data_dir" # # self.name = name # self.task = task # self.data_dir = data_dir # self.verbose = verbose # # def delete_cache(self): # """Delete all cache data + dir""" # print('\n==> dbcollection: config_cache()') # dbc.cache(delete_cache=True) # # def list_datasets(self): # """Print dbcollection info""" # print('\n==> dbcollection: info()') # dbc.info() # # def print_info(self, loader): # """Print information about the dataset to the screen # # Parameters # ---------- # loader : DataLoader # Data loader object of a dataset. # """ # print('\n######### info #########') # print('Dataset: ' + loader.db_name) # print('Task: ' + loader.task) # print('Data path: ' + loader.data_dir) # print('Metadata cache path: ' + loader.hdf5_filepath) # # def load(self): # """Return a data loader object for a dataset. # # Returns # ------- # DataLoader # A data loader object of a dataset. # """ # print('\n==> dbcollection: load()') # return dbc.load(name=self.name, # task=self.task, # data_dir=self.data_dir, # verbose=self.verbose) # # def download(self, extract_data=True): # """Download a dataset to disk. # # Parameters # ---------- # extract_data : bool # Flag signaling to extract data to disk (if True). # """ # print('\n==> dbcollection: download()') # dbc.download(name=self.name, # data_dir=self.data_dir, # extract_data=extract_data, # verbose=self.verbose) # # def process(self): # """Process dataset""" # print('\n==> dbcollection: process()') # dbc.process(name=self.name, # task=self.task, # verbose=self.verbose) # # def run(self, mode): # """Run the test script. # # Parameters # ---------- # mode : str # Task name to execute. # # Raises # ------ # Exception # If an invalid mode was inserted. # """ # assert mode, 'Must insert input arg: mode' # # # delete all cache data + dir # self.delete_cache() # # if mode is 'load': # # download/setup dataset # loader = self.load() # # # print data from the loader # self.print_info(loader) # # elif mode is 'download': # # download dataset # self.download() # # elif mode is 'process': # # download dataset # self.download(False) # # # process dataset task # self.process() # # else: # raise Exception('Invalid mode:', mode) # # # print data from the loader # self.list_datasets() # # # delete all cache data + dir before terminating # self.delete_cache() . Output only the next line.
tester = TestBaseDB(name, task, data_dir, verbose)
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python3 """ Test loading coco. """ # setup name = 'coco' task = 'detection_2015' data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data') verbose = True # Run tester <|code_end|> with the help of current file imports: import os from dbcollection.utils.test import TestBaseDB and context from other files: # Path: dbcollection/utils/test.py # class TestBaseDB: # """ Test Class for loading datasets. # # Parameters # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool, optional # Be verbose. # # Attributes # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool # Be verbose. # # """ # # def __init__(self, name, task, data_dir, verbose=True): # """Initialize class.""" # assert name, "Must insert input arg: name" # assert task, "Must insert input arg: task" # assert data_dir, "Must insert input arg: data_dir" # # self.name = name # self.task = task # self.data_dir = data_dir # self.verbose = verbose # # def delete_cache(self): # """Delete all cache data + dir""" # print('\n==> dbcollection: config_cache()') # dbc.cache(delete_cache=True) # # def list_datasets(self): # """Print dbcollection info""" # print('\n==> dbcollection: info()') # dbc.info() # # def print_info(self, loader): # """Print information about the dataset to the screen # # Parameters # ---------- # loader : DataLoader # Data loader object of a dataset. # """ # print('\n######### info #########') # print('Dataset: ' + loader.db_name) # print('Task: ' + loader.task) # print('Data path: ' + loader.data_dir) # print('Metadata cache path: ' + loader.hdf5_filepath) # # def load(self): # """Return a data loader object for a dataset. # # Returns # ------- # DataLoader # A data loader object of a dataset. # """ # print('\n==> dbcollection: load()') # return dbc.load(name=self.name, # task=self.task, # data_dir=self.data_dir, # verbose=self.verbose) # # def download(self, extract_data=True): # """Download a dataset to disk. # # Parameters # ---------- # extract_data : bool # Flag signaling to extract data to disk (if True). # """ # print('\n==> dbcollection: download()') # dbc.download(name=self.name, # data_dir=self.data_dir, # extract_data=extract_data, # verbose=self.verbose) # # def process(self): # """Process dataset""" # print('\n==> dbcollection: process()') # dbc.process(name=self.name, # task=self.task, # verbose=self.verbose) # # def run(self, mode): # """Run the test script. # # Parameters # ---------- # mode : str # Task name to execute. # # Raises # ------ # Exception # If an invalid mode was inserted. # """ # assert mode, 'Must insert input arg: mode' # # # delete all cache data + dir # self.delete_cache() # # if mode is 'load': # # download/setup dataset # loader = self.load() # # # print data from the loader # self.print_info(loader) # # elif mode is 'download': # # download dataset # self.download() # # elif mode is 'process': # # download dataset # self.download(False) # # # process dataset task # self.process() # # else: # raise Exception('Invalid mode:', mode) # # # print data from the loader # self.list_datasets() # # # delete all cache data + dir before terminating # self.delete_cache() , which may contain function names, class names, or code. Output only the next line.
tester = TestBaseDB(name, task, data_dir, verbose)
Using the snippet: <|code_start|>#!/usr/bin/env python3 """ Test loading Caltech Pedestrian. """ # setup name = 'caltech_pedestrian' task = 'detection' data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data') verbose = True # Run tester <|code_end|> , determine the next line of code. You have imports: import os from dbcollection.utils.test import TestBaseDB and context (class names, function names, or code) available: # Path: dbcollection/utils/test.py # class TestBaseDB: # """ Test Class for loading datasets. # # Parameters # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool, optional # Be verbose. # # Attributes # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool # Be verbose. # # """ # # def __init__(self, name, task, data_dir, verbose=True): # """Initialize class.""" # assert name, "Must insert input arg: name" # assert task, "Must insert input arg: task" # assert data_dir, "Must insert input arg: data_dir" # # self.name = name # self.task = task # self.data_dir = data_dir # self.verbose = verbose # # def delete_cache(self): # """Delete all cache data + dir""" # print('\n==> dbcollection: config_cache()') # dbc.cache(delete_cache=True) # # def list_datasets(self): # """Print dbcollection info""" # print('\n==> dbcollection: info()') # dbc.info() # # def print_info(self, loader): # """Print information about the dataset to the screen # # Parameters # ---------- # loader : DataLoader # Data loader object of a dataset. # """ # print('\n######### info #########') # print('Dataset: ' + loader.db_name) # print('Task: ' + loader.task) # print('Data path: ' + loader.data_dir) # print('Metadata cache path: ' + loader.hdf5_filepath) # # def load(self): # """Return a data loader object for a dataset. # # Returns # ------- # DataLoader # A data loader object of a dataset. # """ # print('\n==> dbcollection: load()') # return dbc.load(name=self.name, # task=self.task, # data_dir=self.data_dir, # verbose=self.verbose) # # def download(self, extract_data=True): # """Download a dataset to disk. # # Parameters # ---------- # extract_data : bool # Flag signaling to extract data to disk (if True). # """ # print('\n==> dbcollection: download()') # dbc.download(name=self.name, # data_dir=self.data_dir, # extract_data=extract_data, # verbose=self.verbose) # # def process(self): # """Process dataset""" # print('\n==> dbcollection: process()') # dbc.process(name=self.name, # task=self.task, # verbose=self.verbose) # # def run(self, mode): # """Run the test script. # # Parameters # ---------- # mode : str # Task name to execute. # # Raises # ------ # Exception # If an invalid mode was inserted. # """ # assert mode, 'Must insert input arg: mode' # # # delete all cache data + dir # self.delete_cache() # # if mode is 'load': # # download/setup dataset # loader = self.load() # # # print data from the loader # self.print_info(loader) # # elif mode is 'download': # # download dataset # self.download() # # elif mode is 'process': # # download dataset # self.download(False) # # # process dataset task # self.process() # # else: # raise Exception('Invalid mode:', mode) # # # print data from the loader # self.list_datasets() # # # delete all cache data + dir before terminating # self.delete_cache() . Output only the next line.
tester = TestBaseDB(name, task, data_dir, verbose)
Here is a snippet: <|code_start|>#!/usr/bin/env python """ Test downloading coco. """ # setup name = 'coco' data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data2') verbose = True # Run tester <|code_end|> . Write the next line using the current file imports: import os from dbcollection.utils.test import TestBaseDB and context from other files: # Path: dbcollection/utils/test.py # class TestBaseDB: # """ Test Class for loading datasets. # # Parameters # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool, optional # Be verbose. # # Attributes # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool # Be verbose. # # """ # # def __init__(self, name, task, data_dir, verbose=True): # """Initialize class.""" # assert name, "Must insert input arg: name" # assert task, "Must insert input arg: task" # assert data_dir, "Must insert input arg: data_dir" # # self.name = name # self.task = task # self.data_dir = data_dir # self.verbose = verbose # # def delete_cache(self): # """Delete all cache data + dir""" # print('\n==> dbcollection: config_cache()') # dbc.cache(delete_cache=True) # # def list_datasets(self): # """Print dbcollection info""" # print('\n==> dbcollection: info()') # dbc.info() # # def print_info(self, loader): # """Print information about the dataset to the screen # # Parameters # ---------- # loader : DataLoader # Data loader object of a dataset. # """ # print('\n######### info #########') # print('Dataset: ' + loader.db_name) # print('Task: ' + loader.task) # print('Data path: ' + loader.data_dir) # print('Metadata cache path: ' + loader.hdf5_filepath) # # def load(self): # """Return a data loader object for a dataset. # # Returns # ------- # DataLoader # A data loader object of a dataset. # """ # print('\n==> dbcollection: load()') # return dbc.load(name=self.name, # task=self.task, # data_dir=self.data_dir, # verbose=self.verbose) # # def download(self, extract_data=True): # """Download a dataset to disk. # # Parameters # ---------- # extract_data : bool # Flag signaling to extract data to disk (if True). # """ # print('\n==> dbcollection: download()') # dbc.download(name=self.name, # data_dir=self.data_dir, # extract_data=extract_data, # verbose=self.verbose) # # def process(self): # """Process dataset""" # print('\n==> dbcollection: process()') # dbc.process(name=self.name, # task=self.task, # verbose=self.verbose) # # def run(self, mode): # """Run the test script. # # Parameters # ---------- # mode : str # Task name to execute. # # Raises # ------ # Exception # If an invalid mode was inserted. # """ # assert mode, 'Must insert input arg: mode' # # # delete all cache data + dir # self.delete_cache() # # if mode is 'load': # # download/setup dataset # loader = self.load() # # # print data from the loader # self.print_info(loader) # # elif mode is 'download': # # download dataset # self.download() # # elif mode is 'process': # # download dataset # self.download(False) # # # process dataset task # self.process() # # else: # raise Exception('Invalid mode:', mode) # # # print data from the loader # self.list_datasets() # # # delete all cache data + dir before terminating # self.delete_cache() , which may include functions, classes, or code. Output only the next line.
tester = TestBaseDB(name, 'no_task', data_dir, verbose)
Given the code snippet: <|code_start|>#!/usr/bin/env python """ Test loading ucf sports. """ # setup name = 'ucf_sports' task = 'recognition' data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data') verbose = True # Run tester <|code_end|> , generate the next line using the imports in this file: import os from dbcollection.utils.test import TestBaseDB and context (functions, classes, or occasionally code) from other files: # Path: dbcollection/utils/test.py # class TestBaseDB: # """ Test Class for loading datasets. # # Parameters # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool, optional # Be verbose. # # Attributes # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool # Be verbose. # # """ # # def __init__(self, name, task, data_dir, verbose=True): # """Initialize class.""" # assert name, "Must insert input arg: name" # assert task, "Must insert input arg: task" # assert data_dir, "Must insert input arg: data_dir" # # self.name = name # self.task = task # self.data_dir = data_dir # self.verbose = verbose # # def delete_cache(self): # """Delete all cache data + dir""" # print('\n==> dbcollection: config_cache()') # dbc.cache(delete_cache=True) # # def list_datasets(self): # """Print dbcollection info""" # print('\n==> dbcollection: info()') # dbc.info() # # def print_info(self, loader): # """Print information about the dataset to the screen # # Parameters # ---------- # loader : DataLoader # Data loader object of a dataset. # """ # print('\n######### info #########') # print('Dataset: ' + loader.db_name) # print('Task: ' + loader.task) # print('Data path: ' + loader.data_dir) # print('Metadata cache path: ' + loader.hdf5_filepath) # # def load(self): # """Return a data loader object for a dataset. # # Returns # ------- # DataLoader # A data loader object of a dataset. # """ # print('\n==> dbcollection: load()') # return dbc.load(name=self.name, # task=self.task, # data_dir=self.data_dir, # verbose=self.verbose) # # def download(self, extract_data=True): # """Download a dataset to disk. # # Parameters # ---------- # extract_data : bool # Flag signaling to extract data to disk (if True). # """ # print('\n==> dbcollection: download()') # dbc.download(name=self.name, # data_dir=self.data_dir, # extract_data=extract_data, # verbose=self.verbose) # # def process(self): # """Process dataset""" # print('\n==> dbcollection: process()') # dbc.process(name=self.name, # task=self.task, # verbose=self.verbose) # # def run(self, mode): # """Run the test script. # # Parameters # ---------- # mode : str # Task name to execute. # # Raises # ------ # Exception # If an invalid mode was inserted. # """ # assert mode, 'Must insert input arg: mode' # # # delete all cache data + dir # self.delete_cache() # # if mode is 'load': # # download/setup dataset # loader = self.load() # # # print data from the loader # self.print_info(loader) # # elif mode is 'download': # # download dataset # self.download() # # elif mode is 'process': # # download dataset # self.download(False) # # # process dataset task # self.process() # # else: # raise Exception('Invalid mode:', mode) # # # print data from the loader # self.list_datasets() # # # delete all cache data + dir before terminating # self.delete_cache() . Output only the next line.
tester = TestBaseDB(name, task, data_dir, verbose)
Given the code snippet: <|code_start|> Tuple of keyword strings to categorize the dataset. verbose : bool Displays text information. force_overwrite : bool Forces the overwrite of data in cache cache_manager : CacheManager Cache manager object. """ def __init__(self, name, task, data_dir, hdf5_filename, categories, verbose, force_overwrite): """Initialize class.""" assert isinstance(name, str), "Must input a valid name." assert isinstance(task, str), "Must input a valid task." assert isinstance(data_dir, str), "Must input a valid data_dir." assert isinstance(hdf5_filename, str), "Must input a valid file_path." assert isinstance(categories, tuple), "Must input a valid list(tuple) of categories." assert isinstance(verbose, bool), "Must input a valid boolean for verbose." assert isinstance(force_overwrite, bool), "Must input a valid boolean for force_overwrite." self.name = name self.task = task self.data_dir = data_dir self.hdf5_filename = hdf5_filename self.categories = categories self.verbose = verbose self.force_overwrite = force_overwrite self.cache_manager = self.get_cache_manager() def get_cache_manager(self): <|code_end|> , generate the next line using the imports in this file: from dbcollection.core.manager import CacheManager and context (functions, classes, or occasionally code) from other files: # Path: dbcollection/core/manager.py # class CacheManager: # """Manage dbcollection configurations and stores them inside a cache file stored in disk. # # Attributes # ---------- # cache_filename : str # Cache file path + name. # cache_dir : str # Default directory to store all dataset's metadata files. # download_dir : str # Default save dir path for downloaded data. # data : dict # Cache contents. # # """ # # def __init__(self): # """Initializes the class.""" # self.manager = CacheDataManager() # self.info = CacheManagerInfo(self.manager) # self.dataset = CacheManagerDataset(self.manager) # self.task = CacheManagerTask(self.manager) # self.category = CacheManagerCategory(self.manager) # # def info_cache(self): # """Prints the information of the cache.""" # self.info.info() # self.dataset.info() # self.category.info() . Output only the next line.
return CacheManager()
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python3 """ Test loading Pascal VOC 2007. """ # setup name = 'pascal_voc_2007' task = 'detection' data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data') verbose = True # Run tester <|code_end|> using the current file's imports: import os from dbcollection.utils.test import TestBaseDB and any relevant context from other files: # Path: dbcollection/utils/test.py # class TestBaseDB: # """ Test Class for loading datasets. # # Parameters # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool, optional # Be verbose. # # Attributes # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool # Be verbose. # # """ # # def __init__(self, name, task, data_dir, verbose=True): # """Initialize class.""" # assert name, "Must insert input arg: name" # assert task, "Must insert input arg: task" # assert data_dir, "Must insert input arg: data_dir" # # self.name = name # self.task = task # self.data_dir = data_dir # self.verbose = verbose # # def delete_cache(self): # """Delete all cache data + dir""" # print('\n==> dbcollection: config_cache()') # dbc.cache(delete_cache=True) # # def list_datasets(self): # """Print dbcollection info""" # print('\n==> dbcollection: info()') # dbc.info() # # def print_info(self, loader): # """Print information about the dataset to the screen # # Parameters # ---------- # loader : DataLoader # Data loader object of a dataset. # """ # print('\n######### info #########') # print('Dataset: ' + loader.db_name) # print('Task: ' + loader.task) # print('Data path: ' + loader.data_dir) # print('Metadata cache path: ' + loader.hdf5_filepath) # # def load(self): # """Return a data loader object for a dataset. # # Returns # ------- # DataLoader # A data loader object of a dataset. # """ # print('\n==> dbcollection: load()') # return dbc.load(name=self.name, # task=self.task, # data_dir=self.data_dir, # verbose=self.verbose) # # def download(self, extract_data=True): # """Download a dataset to disk. # # Parameters # ---------- # extract_data : bool # Flag signaling to extract data to disk (if True). # """ # print('\n==> dbcollection: download()') # dbc.download(name=self.name, # data_dir=self.data_dir, # extract_data=extract_data, # verbose=self.verbose) # # def process(self): # """Process dataset""" # print('\n==> dbcollection: process()') # dbc.process(name=self.name, # task=self.task, # verbose=self.verbose) # # def run(self, mode): # """Run the test script. # # Parameters # ---------- # mode : str # Task name to execute. # # Raises # ------ # Exception # If an invalid mode was inserted. # """ # assert mode, 'Must insert input arg: mode' # # # delete all cache data + dir # self.delete_cache() # # if mode is 'load': # # download/setup dataset # loader = self.load() # # # print data from the loader # self.print_info(loader) # # elif mode is 'download': # # download dataset # self.download() # # elif mode is 'process': # # download dataset # self.download(False) # # # process dataset task # self.process() # # else: # raise Exception('Invalid mode:', mode) # # # print data from the loader # self.list_datasets() # # # delete all cache data + dir before terminating # self.delete_cache() . Output only the next line.
tester = TestBaseDB(name, task, data_dir, verbose)
Here is a snippet: <|code_start|>#!/usr/bin/env python3 """ Test loading Imagenet ilsvrc2012. """ # setup name = 'ilsvrc2012' task = 'classification' data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data') verbose = True # Run tester <|code_end|> . Write the next line using the current file imports: import os from dbcollection.utils.test import TestBaseDB and context from other files: # Path: dbcollection/utils/test.py # class TestBaseDB: # """ Test Class for loading datasets. # # Parameters # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool, optional # Be verbose. # # Attributes # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool # Be verbose. # # """ # # def __init__(self, name, task, data_dir, verbose=True): # """Initialize class.""" # assert name, "Must insert input arg: name" # assert task, "Must insert input arg: task" # assert data_dir, "Must insert input arg: data_dir" # # self.name = name # self.task = task # self.data_dir = data_dir # self.verbose = verbose # # def delete_cache(self): # """Delete all cache data + dir""" # print('\n==> dbcollection: config_cache()') # dbc.cache(delete_cache=True) # # def list_datasets(self): # """Print dbcollection info""" # print('\n==> dbcollection: info()') # dbc.info() # # def print_info(self, loader): # """Print information about the dataset to the screen # # Parameters # ---------- # loader : DataLoader # Data loader object of a dataset. # """ # print('\n######### info #########') # print('Dataset: ' + loader.db_name) # print('Task: ' + loader.task) # print('Data path: ' + loader.data_dir) # print('Metadata cache path: ' + loader.hdf5_filepath) # # def load(self): # """Return a data loader object for a dataset. # # Returns # ------- # DataLoader # A data loader object of a dataset. # """ # print('\n==> dbcollection: load()') # return dbc.load(name=self.name, # task=self.task, # data_dir=self.data_dir, # verbose=self.verbose) # # def download(self, extract_data=True): # """Download a dataset to disk. # # Parameters # ---------- # extract_data : bool # Flag signaling to extract data to disk (if True). # """ # print('\n==> dbcollection: download()') # dbc.download(name=self.name, # data_dir=self.data_dir, # extract_data=extract_data, # verbose=self.verbose) # # def process(self): # """Process dataset""" # print('\n==> dbcollection: process()') # dbc.process(name=self.name, # task=self.task, # verbose=self.verbose) # # def run(self, mode): # """Run the test script. # # Parameters # ---------- # mode : str # Task name to execute. # # Raises # ------ # Exception # If an invalid mode was inserted. # """ # assert mode, 'Must insert input arg: mode' # # # delete all cache data + dir # self.delete_cache() # # if mode is 'load': # # download/setup dataset # loader = self.load() # # # print data from the loader # self.print_info(loader) # # elif mode is 'download': # # download dataset # self.download() # # elif mode is 'process': # # download dataset # self.download(False) # # # process dataset task # self.process() # # else: # raise Exception('Invalid mode:', mode) # # # print data from the loader # self.list_datasets() # # # delete all cache data + dir before terminating # self.delete_cache() , which may include functions, classes, or code. Output only the next line.
tester = TestBaseDB(name, task, data_dir, verbose)
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python3 """ Test loading coco. """ # setup name = 'coco' task = 'caption_2015' data_dir = os.path.join(os.path.expanduser("~"), 'tmp', 'download_data') verbose = True # Run tester <|code_end|> , predict the next line using imports from the current file: import os from dbcollection.utils.test import TestBaseDB and context including class names, function names, and sometimes code from other files: # Path: dbcollection/utils/test.py # class TestBaseDB: # """ Test Class for loading datasets. # # Parameters # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool, optional # Be verbose. # # Attributes # ---------- # name : str # Name of the dataset. # task : str # Name of the task. # data_dir : str # Path of the dataset's data directory on disk. # verbose : bool # Be verbose. # # """ # # def __init__(self, name, task, data_dir, verbose=True): # """Initialize class.""" # assert name, "Must insert input arg: name" # assert task, "Must insert input arg: task" # assert data_dir, "Must insert input arg: data_dir" # # self.name = name # self.task = task # self.data_dir = data_dir # self.verbose = verbose # # def delete_cache(self): # """Delete all cache data + dir""" # print('\n==> dbcollection: config_cache()') # dbc.cache(delete_cache=True) # # def list_datasets(self): # """Print dbcollection info""" # print('\n==> dbcollection: info()') # dbc.info() # # def print_info(self, loader): # """Print information about the dataset to the screen # # Parameters # ---------- # loader : DataLoader # Data loader object of a dataset. # """ # print('\n######### info #########') # print('Dataset: ' + loader.db_name) # print('Task: ' + loader.task) # print('Data path: ' + loader.data_dir) # print('Metadata cache path: ' + loader.hdf5_filepath) # # def load(self): # """Return a data loader object for a dataset. # # Returns # ------- # DataLoader # A data loader object of a dataset. # """ # print('\n==> dbcollection: load()') # return dbc.load(name=self.name, # task=self.task, # data_dir=self.data_dir, # verbose=self.verbose) # # def download(self, extract_data=True): # """Download a dataset to disk. # # Parameters # ---------- # extract_data : bool # Flag signaling to extract data to disk (if True). # """ # print('\n==> dbcollection: download()') # dbc.download(name=self.name, # data_dir=self.data_dir, # extract_data=extract_data, # verbose=self.verbose) # # def process(self): # """Process dataset""" # print('\n==> dbcollection: process()') # dbc.process(name=self.name, # task=self.task, # verbose=self.verbose) # # def run(self, mode): # """Run the test script. # # Parameters # ---------- # mode : str # Task name to execute. # # Raises # ------ # Exception # If an invalid mode was inserted. # """ # assert mode, 'Must insert input arg: mode' # # # delete all cache data + dir # self.delete_cache() # # if mode is 'load': # # download/setup dataset # loader = self.load() # # # print data from the loader # self.print_info(loader) # # elif mode is 'download': # # download dataset # self.download() # # elif mode is 'process': # # download dataset # self.download(False) # # # process dataset task # self.process() # # else: # raise Exception('Invalid mode:', mode) # # # print data from the loader # self.list_datasets() # # # delete all cache data + dir before terminating # self.delete_cache() . Output only the next line.
tester = TestBaseDB(name, task, data_dir, verbose)
Continue the code snippet: <|code_start|>""" Test the HDF5 metadata manager class. """ @pytest.fixture() def test_data(): return { "filename": '/path/to/filename.h5' } @pytest.fixture() def mock_hdf5manager(mocker, test_data): <|code_end|> . Use current file imports: import os import numpy as np import pytest from dbcollection.utils.hdf5 import HDF5Manager and context (classes, functions, or code) from other files: # Path: dbcollection/utils/hdf5.py # class HDF5Manager(object): # """HDF5 metadata file manager. # # Parameters # ---------- # filename : str # File name + path of the HDF5 file. # # Arguments # --------- # filename : str # File name + path of the HDF5 file. # # """ # def __init__(self, filename): # assert filename, "Must insert a valid file name." # self.filename = filename # self.file = self.open_file(filename) # # def open_file(self, filename): # """Opens/creates an HDF5 file in disk.""" # assert filename # return h5py.File(filename, 'w', libver='latest') # # def close(self): # self.file.close() # # def exists_group(self, group): # """Checks if a group exists in the file.""" # assert group, "Must input a valid group name." # return group in self.file # # def create_group(self, name): # """Creates a group in the file.""" # assert name, "Must input a name for the group." # return self.file.create_group(name) # # def add_field_to_group(self, group, field, data, dtype=None, fillvalue=-1, chunks=True, # compression="gzip", compression_opts=4): # """Writes the data of a field into an HDF5 file. # # Parameters # ---------- # group : str # Name of the group. # field : str # Name of the field (h5 dataset). # data : np.ndarray # Data array. # dtype : np.dtype, optional # Data type. # chunks : bool, optional # Stores the data as chunks if True. # compression : str, optional # Compression algorithm type. # compression_opts : int, optional # Compression option (range: [1,10]) # fillvalue : int/float, optional # Value to pad the data array. # # Returns # ------- # h5py._hl.dataset.Dataset # Object handler of the created HDF5 dataset. # # """ # assert group, "Must input a valid group name." # assert field, "Must input a valid field name." # assert isinstance(data, np.ndarray), "Must input a valid numpy data array." # assert dtype, "Must input a valid numpy data type." # assert fillvalue is not None, "Must input a valid fill value to pad the array." # assert chunks is not None, "Must input a valid chunk size." # assert compression, "Must input a valid compression algorithm" # assert compression_opts, "Must input a valid compression value." # # h5_group = self.get_group(group) # # if dtype is None: # dtype = data.dtype # # h5_field = h5_group.create_dataset( # name=field, # data=data, # shape=data.shape, # dtype=dtype, # chunks=chunks, # compression=compression, # compression_opts=compression_opts, # fillvalue=fillvalue # ) # # return h5_field # # def get_group(self, group): # if self.exists_group(group): # return self.file[group] # else: # return self.create_group(group) . Output only the next line.
mocker.patch.object(HDF5Manager, "open_file", return_value={'test_group': 'dummy_data'})
Using the snippet: <|code_start|> session = requests.Session() token = self.get_confirmation_token(session, file_id) response = session.get(self.base_url, params={'id': file_id, 'confirm': token}, stream=True) self.save_response_content(response, filename) def get_confirmation_token(self, session, file_id): """Returns a confirmation token. Parameters ---------- session : requests.sessions.Session Request session. file_id : str File ID in the google drive. Returns ------ str Token string. Raises ------ GoogleDriveFileIdDoesNotExist If the google drive's file id is invalid. """ response = session.get(self.base_url, params={'id': file_id}, stream=True) for key, value in response.cookies.items(): if key.startswith('download_warning'): return value <|code_end|> , determine the next line of code. You have imports: import os import hashlib import shutil import tempfile import requests import patoolib import progressbar from dbcollection.core.exceptions import ( GoogleDriveFileIdDoesNotExist, InvalidURLDownloadSource, MD5HashNotEqual, URLDoesNotExist, ) and context (class names, function names, or code) available: # Path: dbcollection/core/exceptions.py # class GoogleDriveFileIdDoesNotExist(Exception): # """Google drive's file id does not exist.""" # pass # # class InvalidURLDownloadSource(Exception): # """The url source is invalid/undefined.""" # pass # # class MD5HashNotEqual(Exception): # """The MD5 hashes are not equal.""" # pass # # class URLDoesNotExist(Exception): # """URL path does not exist.""" # pass . Output only the next line.
raise GoogleDriveFileIdDoesNotExist('Invalid google drive file id: {}.'.format(file_id))
Given the following code snippet before the placeholder: <|code_start|> def download_url_to_file(self, url_metadata, filename, verbose=True): """Downloads a single url to a file. Parameters ---------- url_metadata : dict URL metadata. filename : str File name + path to save the url's data to disk. verbose : bool, optional Display messages + progress bar on screen when downloading the file. Raises ------ InvalidURLDownloadSource If the input download method is invalid. """ # Create temporary file to store the downloaded data tmpfile = self.create_temp_file(filename) # download the file method = url_metadata['method'] url = url_metadata['url'] if method == 'requests': URLDownload().download(url, filename=tmpfile, verbose=verbose) elif method == 'googledrive': URLDownloadGoogleDrive().download(url, filename=tmpfile) else: <|code_end|> , predict the next line using imports from the current file: import os import hashlib import shutil import tempfile import requests import patoolib import progressbar from dbcollection.core.exceptions import ( GoogleDriveFileIdDoesNotExist, InvalidURLDownloadSource, MD5HashNotEqual, URLDoesNotExist, ) and context including class names, function names, and sometimes code from other files: # Path: dbcollection/core/exceptions.py # class GoogleDriveFileIdDoesNotExist(Exception): # """Google drive's file id does not exist.""" # pass # # class InvalidURLDownloadSource(Exception): # """The url source is invalid/undefined.""" # pass # # class MD5HashNotEqual(Exception): # """The MD5 hashes are not equal.""" # pass # # class URLDoesNotExist(Exception): # """URL path does not exist.""" # pass . Output only the next line.
raise InvalidURLDownloadSource('Invalid url source: {}'.format(method))
Next line prediction: <|code_start|> Returns ------ str File name + path of the temporary file. """ filename_dir = os.path.dirname(filename) (fd, tmpfile) = tempfile.mkstemp(".tmp", prefix=filename, dir=filename_dir) os.close(fd) os.unlink(tmpfile) return tmpfile def md5_checksum(self, filename, md5hash): """Check file integrity using a checksum. Parameters ---------- filename : str File path + name of the downloaded url. md5hash : str Md5 hash string. Raises ------ MD5HashNotEqual MD5 hash checksum do not match. """ file_hash = self.get_file_hash(filename) if not file_hash == md5hash: <|code_end|> . Use current file imports: (import os import hashlib import shutil import tempfile import requests import patoolib import progressbar from dbcollection.core.exceptions import ( GoogleDriveFileIdDoesNotExist, InvalidURLDownloadSource, MD5HashNotEqual, URLDoesNotExist, )) and context including class names, function names, or small code snippets from other files: # Path: dbcollection/core/exceptions.py # class GoogleDriveFileIdDoesNotExist(Exception): # """Google drive's file id does not exist.""" # pass # # class InvalidURLDownloadSource(Exception): # """The url source is invalid/undefined.""" # pass # # class MD5HashNotEqual(Exception): # """The MD5 hashes are not equal.""" # pass # # class URLDoesNotExist(Exception): # """URL path does not exist.""" # pass . Output only the next line.
raise MD5HashNotEqual("MD5 checksums do not match: {} != {}".format(md5hash, file_hash))
Given snippet: <|code_start|> str URL file name. """ url_metadata = URL().parse_url_metadata(url) return url_metadata['filename'] class URLDownload: """Download an URL using the requests module.""" def download(self, url, filename, verbose=False): """Downloads an url data and stores it into a file. Parameters ---------- url : str URL location. filename : str File name + path to store the downloaded data to disk. verbose : bool, optional Display progress bar Raises ------ URLDoesNotExist If an URL is invalid/does not exist. """ if not self.check_exists_url(url): <|code_end|> , continue by predicting the next line. Consider current file imports: import os import hashlib import shutil import tempfile import requests import patoolib import progressbar from dbcollection.core.exceptions import ( GoogleDriveFileIdDoesNotExist, InvalidURLDownloadSource, MD5HashNotEqual, URLDoesNotExist, ) and context: # Path: dbcollection/core/exceptions.py # class GoogleDriveFileIdDoesNotExist(Exception): # """Google drive's file id does not exist.""" # pass # # class InvalidURLDownloadSource(Exception): # """The url source is invalid/undefined.""" # pass # # class MD5HashNotEqual(Exception): # """The MD5 hashes are not equal.""" # pass # # class URLDoesNotExist(Exception): # """URL path does not exist.""" # pass which might include code, classes, or functions. Output only the next line.
raise URLDoesNotExist("Invalid url or does not exist: {}".format(url))
Based on the snippet: <|code_start|> Parameters ---------- index : int/list/tuple, optional Index number of he field. If it is a list, returns the data for all the value indexes of that list. convert_to_str : bool, optional Convert the output data into a string. Warning: output must be of type np.uint8 Returns ------- np.ndarray/list/str Numpy array containing the field's data. If convert_to_str is set to True, it returns a string or list of strings. Note ---- When using lists/tuples of indexes, this method sorts the list and removes duplicate values. This is because the h5py api requires the indexing elements to be in increasing order when retrieving data. """ if index is None: data = self._get_all_idx() else: data = self._get_range_idx(index) if convert_to_str: <|code_end|> , predict the immediate next line with the help of imports: import h5py from dbcollection.utils.string_ascii import convert_ascii_to_str and context (classes, functions, sometimes code) from other files: # Path: dbcollection/utils/string_ascii.py # def convert_ascii_to_str(input_array): # """Convert a numpy array to a string (or a list of strings) # # Parameters # ---------- # input_array : np.ndarray # Array of strings encoded in ASCII format. # # Returns # ------- # str/list # String or list of strings. # # Examples # -------- # Convert a numpy array to a string. # # >>> from dbcollection.utils.string_ascii import convert_ascii_to_str # >>> import numpy as np # >>> # ascii format of 'string1' # >>> tensor = np.array([[115, 116, 114, 105, 110, 103, 49, 0]], dtype=np.uint8) # >>> convert_ascii_to_str(tensor) # ['string1'] # # """ # assert isinstance(input_array, np.ndarray), "Must input a valid numpy array." # list_str = input_array.tolist() # if input_array.ndim > 1: # return [ascii_to_str(list(filter(lambda x: x > 0, str_))) for str_ in list_str] # else: # return ascii_to_str(list(filter(lambda x: x > 0, list_str))) . Output only the next line.
data = convert_ascii_to_str(data)
Predict the next line for this snippet: <|code_start|>#coding: utf-8 class BaseMongoAdminTests(unittest.TestCase): def setUp(self): self.req = RequestFactory().get('/') def testHasViewPermissions(self): self.req.user = DummyUser(is_authenticated=True, is_active=True) <|code_end|> with the help of current file imports: import unittest from django.test import RequestFactory from mongonaut.sites import BaseMongoAdmin from common.utils import DummyUser and context from other files: # Path: mongonaut/sites.py # class BaseMongoAdmin(object): # """Base model class for replication django.site.ModelAdmin class. # """ # # search_fields = [] # # # Show the fields to be displayed as columns # # TODO: Confirm that this is what the Django admin uses # list_fields = [] # # #This shows up on the DocumentListView of the Posts # list_actions = [] # # # This shows up in the DocumentDetailView of the Posts. # document_actions = [] # # # shows up on a particular field # field_actions = {} # # fields = None # exclude = None # fieldsets = None # form = forms.ModelForm # filter_vertical = () # filter_horizontal = () # radio_fields = {} # prepopulated_fields = {} # formfield_overrides = {} # readonly_fields = () # ordering = None # # def has_view_permission(self, request): # """ # Returns True if the given HttpRequest has permission to view # *at least one* page in the mongonaut site. # """ # return request.user.is_authenticated and request.user.is_active # # def has_edit_permission(self, request): # """ Can edit this object """ # return request.user.is_authenticated and request.user.is_active and request.user.is_staff # # def has_add_permission(self, request): # """ Can add this object """ # return request.user.is_authenticated and request.user.is_active and request.user.is_staff # # def has_delete_permission(self, request): # """ Can delete this object """ # return request.user.is_authenticated and request.user.is_active and request.user.is_superuser , which may contain function names, class names, or code. Output only the next line.
self.assertTrue(BaseMongoAdmin().has_view_permission(self.req))
Predict the next line for this snippet: <|code_start|> urlpatterns = [ url( regex=r'^$', <|code_end|> with the help of current file imports: from django.conf.urls import url from mongonaut import views and context from other files: # Path: mongonaut/views.py # class IndexView(MongonautViewMixin, ListView): # class DocumentListView(MongonautViewMixin, FormView): # class DocumentDetailView(MongonautViewMixin, TemplateView): # class DocumentEditFormView(MongonautViewMixin, FormView, MongonautFormViewMixin): # class DocumentAddFormView(MongonautViewMixin, FormView, MongonautFormViewMixin): # class DocumentDeleteView(DeletionMixin, MongonautViewMixin, TemplateView): # def get_queryset(self): # def get_qset(self, queryset, q): # def get_queryset(self): # def get_initial(self): # def get_context_data(self, **kwargs): # def post(self, request, *args, **kwargs): # def get_context_data(self, **kwargs): # def get_success_url(self): # def get_context_data(self, **kwargs): # def get_form(self): #get_form(self, Form) leads to "get_form() missing 1 required positional argument: 'Form'" error." # def get_success_url(self): # def get_context_data(self, **kwargs): # def get_form(self): # def get_success_url(self): # def get_object(self): , which may contain function names, class names, or code. Output only the next line.
view=views.IndexView.as_view(),
Given snippet: <|code_start|> u = NewUser(email='test@test.com') u.id=ObjectId('abcabcabcabc') p = Post(author=u, title='Test') p.id = ObjectId('abcabcabcabc') match_found = True try: v = get_document_value(p, 'author') except NoReverseMatch as e: match_found = False settings.ROOT_URLCONF = urls_tmp self.assertEquals(match_found, True) def testDetailViewRendering(self): ''' Tries to render a detail view byt giving it data from examples.blog. As <app_label> and <document_name> may contain dots, it checks whether NoReverseMatch exception was raised. ''' self.req.user = DummyUser() urls_tmp = settings.ROOT_URLCONF settings.ROOT_URLCONF = 'examples.blog.urls' <|code_end|> , continue by predicting the next line. Consider current file imports: import unittest import django from importlib import import_module from django.test import RequestFactory from bson.objectid import ObjectId from django.core.urlresolvers import NoReverseMatch from django.conf import settings from mongonaut.views import DocumentDetailView from common.utils import DummyUser from examples.blog.articles.models import Post, NewUser from mongonaut.templatetags.mongonaut_tags import get_document_value and context: # Path: mongonaut/views.py # class DocumentDetailView(MongonautViewMixin, TemplateView): # """ :args: <app_label> <document_name> <id> """ # template_name = "mongonaut/document_detail.html" # permission = 'has_view_permission' # # def get_context_data(self, **kwargs): # context = super(DocumentDetailView, self).get_context_data(**kwargs) # self.set_mongoadmin() # context = self.set_permissions_in_context(context) # self.document_type = getattr(self.models, self.document_name) # self.ident = self.kwargs.get('id') # self.document = self.document_type.objects.get(pk=self.ident) # # context['document'] = self.document # context['app_label'] = self.app_label # context['document_name'] = self.document_name # context['keys'] = ['id', ] # context['embedded_documents'] = [] # context['list_fields'] = [] # for key in sorted([x for x in self.document._fields.keys() if x != 'id']): # # TODO - Figure out why this EmbeddedDocumentField and ListField breaks this view # # Note - This is the challenge part, right? :) # if isinstance(self.document._fields[key], EmbeddedDocumentField): # context['embedded_documents'].append(key) # continue # if isinstance(self.document._fields[key], ListField): # context['list_fields'].append(key) # continue # context['keys'].append(key) # return context # # Path: examples/blog/articles/models.py # class Post(Document): # # See Post.title.max_length to make validation better! # title = StringField(max_length=120, required=True, unique=True) # content = StringField(default="I am default content") # author = ReferenceField(User, required=True) # created_date = DateTimeField() # published = BooleanField() # creator = EmbeddedDocumentField(EmbeddedUser) # published_dates = ListField(DateTimeField()) # tags = ListField(StringField(max_length=30)) # past_authors = ListField(ReferenceField(User)) # comments = ListField(EmbeddedDocumentField(Comment)) # # def save(self, *args, **kwargs): # if not self.created_date: # self.created_date = datetime.utcnow() # if not self.creator: # self.creator = EmbeddedUser() # self.creator.email = self.author.email # self.creator.first_name = self.author.first_name # self.creator.last_name = self.author.last_name # if self.published: # self.published_dates.append(datetime.utcnow()) # super(Post, self).save(*args, **kwargs) # # class NewUser(User): # new_field = StringField() # # def __unicode__(self): # return self.email # # Path: mongonaut/templatetags/mongonaut_tags.py # @register.simple_tag() # def get_document_value(document, key): # ''' # Returns the display value of a field for a particular MongoDB document. # ''' # value = getattr(document, key) # if isinstance(value, ObjectId): # return value # # if isinstance(document._fields.get(key), URLField): # return mark_safe("""<a href="{0}">{1}</a>""".format(value, value)) # # if isinstance(value, Document): # app_label = value.__module__.replace(".models", "") # document_name = value._class_name # url = reverse( # "document_detail", # kwargs={'app_label': app_label, 'document_name': document_name, # 'id': value.id}) # return mark_safe("""<a href="{0}">{1}</a>""".format(url, value)) # # return value which might include code, classes, or functions. Output only the next line.
self.view = DocumentDetailView.as_view()(
Given the following code snippet before the placeholder: <|code_start|>#coding: utf-8 class IndexViewTests(unittest.TestCase): def setUp(self): self.req = RequestFactory().get('/') django.setup() def testURLResolver(self): ''' Tests whether reverse function inside get_document_value can correctly return a document_detail url when given a set of: <document_name> <app_label> and <id> Both <document_name> and <app_label> will contain dots, eg. <document_name> : 'User.NewUser' <app_label> : 'examples.blog.articles' ''' urls_tmp = settings.ROOT_URLCONF settings.ROOT_URLCONF = 'examples.blog.urls' u = NewUser(email='test@test.com') u.id=ObjectId('abcabcabcabc') <|code_end|> , predict the next line using imports from the current file: import unittest import django from importlib import import_module from django.test import RequestFactory from bson.objectid import ObjectId from django.core.urlresolvers import NoReverseMatch from django.conf import settings from mongonaut.views import DocumentDetailView from common.utils import DummyUser from examples.blog.articles.models import Post, NewUser from mongonaut.templatetags.mongonaut_tags import get_document_value and context including class names, function names, and sometimes code from other files: # Path: mongonaut/views.py # class DocumentDetailView(MongonautViewMixin, TemplateView): # """ :args: <app_label> <document_name> <id> """ # template_name = "mongonaut/document_detail.html" # permission = 'has_view_permission' # # def get_context_data(self, **kwargs): # context = super(DocumentDetailView, self).get_context_data(**kwargs) # self.set_mongoadmin() # context = self.set_permissions_in_context(context) # self.document_type = getattr(self.models, self.document_name) # self.ident = self.kwargs.get('id') # self.document = self.document_type.objects.get(pk=self.ident) # # context['document'] = self.document # context['app_label'] = self.app_label # context['document_name'] = self.document_name # context['keys'] = ['id', ] # context['embedded_documents'] = [] # context['list_fields'] = [] # for key in sorted([x for x in self.document._fields.keys() if x != 'id']): # # TODO - Figure out why this EmbeddedDocumentField and ListField breaks this view # # Note - This is the challenge part, right? :) # if isinstance(self.document._fields[key], EmbeddedDocumentField): # context['embedded_documents'].append(key) # continue # if isinstance(self.document._fields[key], ListField): # context['list_fields'].append(key) # continue # context['keys'].append(key) # return context # # Path: examples/blog/articles/models.py # class Post(Document): # # See Post.title.max_length to make validation better! # title = StringField(max_length=120, required=True, unique=True) # content = StringField(default="I am default content") # author = ReferenceField(User, required=True) # created_date = DateTimeField() # published = BooleanField() # creator = EmbeddedDocumentField(EmbeddedUser) # published_dates = ListField(DateTimeField()) # tags = ListField(StringField(max_length=30)) # past_authors = ListField(ReferenceField(User)) # comments = ListField(EmbeddedDocumentField(Comment)) # # def save(self, *args, **kwargs): # if not self.created_date: # self.created_date = datetime.utcnow() # if not self.creator: # self.creator = EmbeddedUser() # self.creator.email = self.author.email # self.creator.first_name = self.author.first_name # self.creator.last_name = self.author.last_name # if self.published: # self.published_dates.append(datetime.utcnow()) # super(Post, self).save(*args, **kwargs) # # class NewUser(User): # new_field = StringField() # # def __unicode__(self): # return self.email # # Path: mongonaut/templatetags/mongonaut_tags.py # @register.simple_tag() # def get_document_value(document, key): # ''' # Returns the display value of a field for a particular MongoDB document. # ''' # value = getattr(document, key) # if isinstance(value, ObjectId): # return value # # if isinstance(document._fields.get(key), URLField): # return mark_safe("""<a href="{0}">{1}</a>""".format(value, value)) # # if isinstance(value, Document): # app_label = value.__module__.replace(".models", "") # document_name = value._class_name # url = reverse( # "document_detail", # kwargs={'app_label': app_label, 'document_name': document_name, # 'id': value.id}) # return mark_safe("""<a href="{0}">{1}</a>""".format(url, value)) # # return value . Output only the next line.
p = Post(author=u, title='Test')
Here is a snippet: <|code_start|>#coding: utf-8 class IndexViewTests(unittest.TestCase): def setUp(self): self.req = RequestFactory().get('/') django.setup() def testURLResolver(self): ''' Tests whether reverse function inside get_document_value can correctly return a document_detail url when given a set of: <document_name> <app_label> and <id> Both <document_name> and <app_label> will contain dots, eg. <document_name> : 'User.NewUser' <app_label> : 'examples.blog.articles' ''' urls_tmp = settings.ROOT_URLCONF settings.ROOT_URLCONF = 'examples.blog.urls' <|code_end|> . Write the next line using the current file imports: import unittest import django from importlib import import_module from django.test import RequestFactory from bson.objectid import ObjectId from django.core.urlresolvers import NoReverseMatch from django.conf import settings from mongonaut.views import DocumentDetailView from common.utils import DummyUser from examples.blog.articles.models import Post, NewUser from mongonaut.templatetags.mongonaut_tags import get_document_value and context from other files: # Path: mongonaut/views.py # class DocumentDetailView(MongonautViewMixin, TemplateView): # """ :args: <app_label> <document_name> <id> """ # template_name = "mongonaut/document_detail.html" # permission = 'has_view_permission' # # def get_context_data(self, **kwargs): # context = super(DocumentDetailView, self).get_context_data(**kwargs) # self.set_mongoadmin() # context = self.set_permissions_in_context(context) # self.document_type = getattr(self.models, self.document_name) # self.ident = self.kwargs.get('id') # self.document = self.document_type.objects.get(pk=self.ident) # # context['document'] = self.document # context['app_label'] = self.app_label # context['document_name'] = self.document_name # context['keys'] = ['id', ] # context['embedded_documents'] = [] # context['list_fields'] = [] # for key in sorted([x for x in self.document._fields.keys() if x != 'id']): # # TODO - Figure out why this EmbeddedDocumentField and ListField breaks this view # # Note - This is the challenge part, right? :) # if isinstance(self.document._fields[key], EmbeddedDocumentField): # context['embedded_documents'].append(key) # continue # if isinstance(self.document._fields[key], ListField): # context['list_fields'].append(key) # continue # context['keys'].append(key) # return context # # Path: examples/blog/articles/models.py # class Post(Document): # # See Post.title.max_length to make validation better! # title = StringField(max_length=120, required=True, unique=True) # content = StringField(default="I am default content") # author = ReferenceField(User, required=True) # created_date = DateTimeField() # published = BooleanField() # creator = EmbeddedDocumentField(EmbeddedUser) # published_dates = ListField(DateTimeField()) # tags = ListField(StringField(max_length=30)) # past_authors = ListField(ReferenceField(User)) # comments = ListField(EmbeddedDocumentField(Comment)) # # def save(self, *args, **kwargs): # if not self.created_date: # self.created_date = datetime.utcnow() # if not self.creator: # self.creator = EmbeddedUser() # self.creator.email = self.author.email # self.creator.first_name = self.author.first_name # self.creator.last_name = self.author.last_name # if self.published: # self.published_dates.append(datetime.utcnow()) # super(Post, self).save(*args, **kwargs) # # class NewUser(User): # new_field = StringField() # # def __unicode__(self): # return self.email # # Path: mongonaut/templatetags/mongonaut_tags.py # @register.simple_tag() # def get_document_value(document, key): # ''' # Returns the display value of a field for a particular MongoDB document. # ''' # value = getattr(document, key) # if isinstance(value, ObjectId): # return value # # if isinstance(document._fields.get(key), URLField): # return mark_safe("""<a href="{0}">{1}</a>""".format(value, value)) # # if isinstance(value, Document): # app_label = value.__module__.replace(".models", "") # document_name = value._class_name # url = reverse( # "document_detail", # kwargs={'app_label': app_label, 'document_name': document_name, # 'id': value.id}) # return mark_safe("""<a href="{0}">{1}</a>""".format(url, value)) # # return value , which may include functions, classes, or code. Output only the next line.
u = NewUser(email='test@test.com')
Next line prediction: <|code_start|> class IndexViewTests(unittest.TestCase): def setUp(self): self.req = RequestFactory().get('/') django.setup() def testURLResolver(self): ''' Tests whether reverse function inside get_document_value can correctly return a document_detail url when given a set of: <document_name> <app_label> and <id> Both <document_name> and <app_label> will contain dots, eg. <document_name> : 'User.NewUser' <app_label> : 'examples.blog.articles' ''' urls_tmp = settings.ROOT_URLCONF settings.ROOT_URLCONF = 'examples.blog.urls' u = NewUser(email='test@test.com') u.id=ObjectId('abcabcabcabc') p = Post(author=u, title='Test') p.id = ObjectId('abcabcabcabc') match_found = True try: <|code_end|> . Use current file imports: (import unittest import django from importlib import import_module from django.test import RequestFactory from bson.objectid import ObjectId from django.core.urlresolvers import NoReverseMatch from django.conf import settings from mongonaut.views import DocumentDetailView from common.utils import DummyUser from examples.blog.articles.models import Post, NewUser from mongonaut.templatetags.mongonaut_tags import get_document_value) and context including class names, function names, or small code snippets from other files: # Path: mongonaut/views.py # class DocumentDetailView(MongonautViewMixin, TemplateView): # """ :args: <app_label> <document_name> <id> """ # template_name = "mongonaut/document_detail.html" # permission = 'has_view_permission' # # def get_context_data(self, **kwargs): # context = super(DocumentDetailView, self).get_context_data(**kwargs) # self.set_mongoadmin() # context = self.set_permissions_in_context(context) # self.document_type = getattr(self.models, self.document_name) # self.ident = self.kwargs.get('id') # self.document = self.document_type.objects.get(pk=self.ident) # # context['document'] = self.document # context['app_label'] = self.app_label # context['document_name'] = self.document_name # context['keys'] = ['id', ] # context['embedded_documents'] = [] # context['list_fields'] = [] # for key in sorted([x for x in self.document._fields.keys() if x != 'id']): # # TODO - Figure out why this EmbeddedDocumentField and ListField breaks this view # # Note - This is the challenge part, right? :) # if isinstance(self.document._fields[key], EmbeddedDocumentField): # context['embedded_documents'].append(key) # continue # if isinstance(self.document._fields[key], ListField): # context['list_fields'].append(key) # continue # context['keys'].append(key) # return context # # Path: examples/blog/articles/models.py # class Post(Document): # # See Post.title.max_length to make validation better! # title = StringField(max_length=120, required=True, unique=True) # content = StringField(default="I am default content") # author = ReferenceField(User, required=True) # created_date = DateTimeField() # published = BooleanField() # creator = EmbeddedDocumentField(EmbeddedUser) # published_dates = ListField(DateTimeField()) # tags = ListField(StringField(max_length=30)) # past_authors = ListField(ReferenceField(User)) # comments = ListField(EmbeddedDocumentField(Comment)) # # def save(self, *args, **kwargs): # if not self.created_date: # self.created_date = datetime.utcnow() # if not self.creator: # self.creator = EmbeddedUser() # self.creator.email = self.author.email # self.creator.first_name = self.author.first_name # self.creator.last_name = self.author.last_name # if self.published: # self.published_dates.append(datetime.utcnow()) # super(Post, self).save(*args, **kwargs) # # class NewUser(User): # new_field = StringField() # # def __unicode__(self): # return self.email # # Path: mongonaut/templatetags/mongonaut_tags.py # @register.simple_tag() # def get_document_value(document, key): # ''' # Returns the display value of a field for a particular MongoDB document. # ''' # value = getattr(document, key) # if isinstance(value, ObjectId): # return value # # if isinstance(document._fields.get(key), URLField): # return mark_safe("""<a href="{0}">{1}</a>""".format(value, value)) # # if isinstance(value, Document): # app_label = value.__module__.replace(".models", "") # document_name = value._class_name # url = reverse( # "document_detail", # kwargs={'app_label': app_label, 'document_name': document_name, # 'id': value.id}) # return mark_safe("""<a href="{0}">{1}</a>""".format(url, value)) # # return value . Output only the next line.
v = get_document_value(p, 'author')
Predict the next line for this snippet: <|code_start|> """ Sets a number of commonly used attributes """ if hasattr(self, "app_label"): # prevents us from calling this multiple times return None self.app_label = self.kwargs.get('app_label') self.document_name = self.kwargs.get('document_name') # TODO Allow this to be assigned via url variable self.models_name = self.kwargs.get('models_name', 'models') # import the models file self.model_name = "{0}.{1}".format(self.app_label, self.models_name) self.models = import_module(self.model_name) def set_mongoadmin(self): """ Returns the MongoAdmin object for an app_label/document_name style view """ if hasattr(self, "mongoadmin"): return None if not hasattr(self, "document_name"): self.set_mongonaut_base() for mongoadmin in self.get_mongoadmins(): for model in mongoadmin['obj'].models: if model.name == self.document_name: self.mongoadmin = model.mongoadmin break # TODO change this to use 'finally' or 'else' or something if not hasattr(self, "mongoadmin"): <|code_end|> with the help of current file imports: import types from importlib import import_module from django.conf import settings from django.contrib import messages from django.http import HttpResponseForbidden from mongoengine.fields import EmbeddedDocumentField from mongonaut.exceptions import NoMongoAdminSpecified from mongonaut.forms import MongoModelForm from mongonaut.forms.form_utils import has_digit from mongonaut.forms.form_utils import make_key from mongonaut.utils import translate_value from mongonaut.utils import trim_field_key and context from other files: # Path: mongonaut/exceptions.py # class NoMongoAdminSpecified(Exception): # """ Called when no MongoAdmin is specified. Unlikely to ever be called.""" # pass # # Path: mongonaut/forms/form_utils.py # def has_digit(string_or_list, sep="_"): # """ # Given a string or a list will return true if the last word or # element is a digit. sep is used when a string is given to know # what separates one word from another. # """ # if isinstance(string_or_list, (tuple, list)): # list_length = len(string_or_list) # if list_length: # return six.text_type(string_or_list[-1]).isdigit() # else: # return False # else: # return has_digit(string_or_list.split(sep)) # # Path: mongonaut/forms/form_utils.py # def make_key(*args, **kwargs): # """ # Given any number of lists and strings will join them in order as one # string separated by the sep kwarg. sep defaults to u"_". # # Add exclude_last_string=True as a kwarg to exclude the last item in a # given string after being split by sep. Note if you only have one word # in your string you can end up getting an empty string. # # Example uses: # # >>> from mongonaut.forms.form_utils import make_key # >>> make_key('hi', 'my', 'firend') # >>> u'hi_my_firend' # # >>> make_key('hi', 'my', 'firend', sep='i') # >>> 'hiimyifirend' # # >>> make_key('hi', 'my', 'firend',['this', 'be', 'what'], sep='i') # >>> 'hiimyifirendithisibeiwhat' # # >>> make_key('hi', 'my', 'firend',['this', 'be', 'what']) # >>> u'hi_my_firend_this_be_what' # # """ # sep = kwargs.get('sep', u"_") # exclude_last_string = kwargs.get('exclude_last_string', False) # string_array = [] # # for arg in args: # if isinstance(arg, list): # string_array.append(six.text_type(sep.join(arg))) # else: # if exclude_last_string: # new_key_array = arg.split(sep)[:-1] # if len(new_key_array) > 0: # string_array.append(make_key(new_key_array)) # else: # string_array.append(six.text_type(arg)) # return sep.join(string_array) # # Path: mongonaut/utils.py # def translate_value(document_field, form_value): # """ # Given a document_field and a form_value this will translate the value # to the correct result for mongo to use. # """ # value = form_value # if isinstance(document_field, ReferenceField): # value = document_field.document_type.objects.get(id=form_value) if form_value else None # return value # # Path: mongonaut/utils.py # def trim_field_key(document, field_key): # """ # Returns the smallest delimited version of field_key that # is an attribute on document. # # return (key, left_over_array) # """ # trimming = True # left_over_key_values = [] # current_key = field_key # while trimming and current_key: # if hasattr(document, current_key): # trimming = False # else: # key_array = current_key.split("_") # left_over_key_values.append(key_array.pop()) # current_key = u"_".join(key_array) # # left_over_key_values.reverse() # return current_key, left_over_key_values , which may contain function names, class names, or code. Output only the next line.
raise NoMongoAdminSpecified("No MongoAdmin for {0}.{1}".format(self.app_label, self.document_name))
Predict the next line after this snippet: <|code_start|> # document. self.embedded_list_docs = {} if self.new_document is None: messages.error(self.request, u"Failed to save document") else: self.new_document = self.new_document() for form_key in self.form.cleaned_data.keys(): if form_key == 'id' and hasattr(self, 'document'): self.new_document.id = self.document.id continue self.process_document(self.new_document, form_key, None) self.new_document.save() if success_message: messages.success(self.request, success_message) return self.form def process_document(self, document, form_key, passed_key): """ Given the form_key will evaluate the document and set values correctly for the document given. """ if passed_key is not None: current_key, remaining_key_array = trim_field_key(document, passed_key) else: current_key, remaining_key_array = trim_field_key(document, form_key) <|code_end|> using the current file's imports: import types from importlib import import_module from django.conf import settings from django.contrib import messages from django.http import HttpResponseForbidden from mongoengine.fields import EmbeddedDocumentField from mongonaut.exceptions import NoMongoAdminSpecified from mongonaut.forms import MongoModelForm from mongonaut.forms.form_utils import has_digit from mongonaut.forms.form_utils import make_key from mongonaut.utils import translate_value from mongonaut.utils import trim_field_key and any relevant context from other files: # Path: mongonaut/exceptions.py # class NoMongoAdminSpecified(Exception): # """ Called when no MongoAdmin is specified. Unlikely to ever be called.""" # pass # # Path: mongonaut/forms/form_utils.py # def has_digit(string_or_list, sep="_"): # """ # Given a string or a list will return true if the last word or # element is a digit. sep is used when a string is given to know # what separates one word from another. # """ # if isinstance(string_or_list, (tuple, list)): # list_length = len(string_or_list) # if list_length: # return six.text_type(string_or_list[-1]).isdigit() # else: # return False # else: # return has_digit(string_or_list.split(sep)) # # Path: mongonaut/forms/form_utils.py # def make_key(*args, **kwargs): # """ # Given any number of lists and strings will join them in order as one # string separated by the sep kwarg. sep defaults to u"_". # # Add exclude_last_string=True as a kwarg to exclude the last item in a # given string after being split by sep. Note if you only have one word # in your string you can end up getting an empty string. # # Example uses: # # >>> from mongonaut.forms.form_utils import make_key # >>> make_key('hi', 'my', 'firend') # >>> u'hi_my_firend' # # >>> make_key('hi', 'my', 'firend', sep='i') # >>> 'hiimyifirend' # # >>> make_key('hi', 'my', 'firend',['this', 'be', 'what'], sep='i') # >>> 'hiimyifirendithisibeiwhat' # # >>> make_key('hi', 'my', 'firend',['this', 'be', 'what']) # >>> u'hi_my_firend_this_be_what' # # """ # sep = kwargs.get('sep', u"_") # exclude_last_string = kwargs.get('exclude_last_string', False) # string_array = [] # # for arg in args: # if isinstance(arg, list): # string_array.append(six.text_type(sep.join(arg))) # else: # if exclude_last_string: # new_key_array = arg.split(sep)[:-1] # if len(new_key_array) > 0: # string_array.append(make_key(new_key_array)) # else: # string_array.append(six.text_type(arg)) # return sep.join(string_array) # # Path: mongonaut/utils.py # def translate_value(document_field, form_value): # """ # Given a document_field and a form_value this will translate the value # to the correct result for mongo to use. # """ # value = form_value # if isinstance(document_field, ReferenceField): # value = document_field.document_type.objects.get(id=form_value) if form_value else None # return value # # Path: mongonaut/utils.py # def trim_field_key(document, field_key): # """ # Returns the smallest delimited version of field_key that # is an attribute on document. # # return (key, left_over_array) # """ # trimming = True # left_over_key_values = [] # current_key = field_key # while trimming and current_key: # if hasattr(document, current_key): # trimming = False # else: # key_array = current_key.split("_") # left_over_key_values.append(key_array.pop()) # current_key = u"_".join(key_array) # # left_over_key_values.reverse() # return current_key, left_over_key_values . Output only the next line.
key_array_digit = remaining_key_array[-1] if remaining_key_array and has_digit(remaining_key_array) else None
Here is a snippet: <|code_start|> self.embedded_list_docs = {} if self.new_document is None: messages.error(self.request, u"Failed to save document") else: self.new_document = self.new_document() for form_key in self.form.cleaned_data.keys(): if form_key == 'id' and hasattr(self, 'document'): self.new_document.id = self.document.id continue self.process_document(self.new_document, form_key, None) self.new_document.save() if success_message: messages.success(self.request, success_message) return self.form def process_document(self, document, form_key, passed_key): """ Given the form_key will evaluate the document and set values correctly for the document given. """ if passed_key is not None: current_key, remaining_key_array = trim_field_key(document, passed_key) else: current_key, remaining_key_array = trim_field_key(document, form_key) key_array_digit = remaining_key_array[-1] if remaining_key_array and has_digit(remaining_key_array) else None <|code_end|> . Write the next line using the current file imports: import types from importlib import import_module from django.conf import settings from django.contrib import messages from django.http import HttpResponseForbidden from mongoengine.fields import EmbeddedDocumentField from mongonaut.exceptions import NoMongoAdminSpecified from mongonaut.forms import MongoModelForm from mongonaut.forms.form_utils import has_digit from mongonaut.forms.form_utils import make_key from mongonaut.utils import translate_value from mongonaut.utils import trim_field_key and context from other files: # Path: mongonaut/exceptions.py # class NoMongoAdminSpecified(Exception): # """ Called when no MongoAdmin is specified. Unlikely to ever be called.""" # pass # # Path: mongonaut/forms/form_utils.py # def has_digit(string_or_list, sep="_"): # """ # Given a string or a list will return true if the last word or # element is a digit. sep is used when a string is given to know # what separates one word from another. # """ # if isinstance(string_or_list, (tuple, list)): # list_length = len(string_or_list) # if list_length: # return six.text_type(string_or_list[-1]).isdigit() # else: # return False # else: # return has_digit(string_or_list.split(sep)) # # Path: mongonaut/forms/form_utils.py # def make_key(*args, **kwargs): # """ # Given any number of lists and strings will join them in order as one # string separated by the sep kwarg. sep defaults to u"_". # # Add exclude_last_string=True as a kwarg to exclude the last item in a # given string after being split by sep. Note if you only have one word # in your string you can end up getting an empty string. # # Example uses: # # >>> from mongonaut.forms.form_utils import make_key # >>> make_key('hi', 'my', 'firend') # >>> u'hi_my_firend' # # >>> make_key('hi', 'my', 'firend', sep='i') # >>> 'hiimyifirend' # # >>> make_key('hi', 'my', 'firend',['this', 'be', 'what'], sep='i') # >>> 'hiimyifirendithisibeiwhat' # # >>> make_key('hi', 'my', 'firend',['this', 'be', 'what']) # >>> u'hi_my_firend_this_be_what' # # """ # sep = kwargs.get('sep', u"_") # exclude_last_string = kwargs.get('exclude_last_string', False) # string_array = [] # # for arg in args: # if isinstance(arg, list): # string_array.append(six.text_type(sep.join(arg))) # else: # if exclude_last_string: # new_key_array = arg.split(sep)[:-1] # if len(new_key_array) > 0: # string_array.append(make_key(new_key_array)) # else: # string_array.append(six.text_type(arg)) # return sep.join(string_array) # # Path: mongonaut/utils.py # def translate_value(document_field, form_value): # """ # Given a document_field and a form_value this will translate the value # to the correct result for mongo to use. # """ # value = form_value # if isinstance(document_field, ReferenceField): # value = document_field.document_type.objects.get(id=form_value) if form_value else None # return value # # Path: mongonaut/utils.py # def trim_field_key(document, field_key): # """ # Returns the smallest delimited version of field_key that # is an attribute on document. # # return (key, left_over_array) # """ # trimming = True # left_over_key_values = [] # current_key = field_key # while trimming and current_key: # if hasattr(document, current_key): # trimming = False # else: # key_array = current_key.split("_") # left_over_key_values.append(key_array.pop()) # current_key = u"_".join(key_array) # # left_over_key_values.reverse() # return current_key, left_over_key_values , which may include functions, classes, or code. Output only the next line.
remaining_key = make_key(remaining_key_array)
Continue the code snippet: <|code_start|> def process_document(self, document, form_key, passed_key): """ Given the form_key will evaluate the document and set values correctly for the document given. """ if passed_key is not None: current_key, remaining_key_array = trim_field_key(document, passed_key) else: current_key, remaining_key_array = trim_field_key(document, form_key) key_array_digit = remaining_key_array[-1] if remaining_key_array and has_digit(remaining_key_array) else None remaining_key = make_key(remaining_key_array) if current_key.lower() == 'id': raise KeyError(u"Mongonaut does not work with models which have fields beginning with id_") # Create boolean checks to make processing document easier is_embedded_doc = (isinstance(document._fields.get(current_key, None), EmbeddedDocumentField) if hasattr(document, '_fields') else False) is_list = not key_array_digit is None key_in_fields = current_key in document._fields.keys() if hasattr(document, '_fields') else False # This ensures you only go through each documents keys once, and do not duplicate data if key_in_fields: if is_embedded_doc: self.set_embedded_doc(document, form_key, current_key, remaining_key) elif is_list: self.set_list_field(document, form_key, current_key, remaining_key, key_array_digit) else: <|code_end|> . Use current file imports: import types from importlib import import_module from django.conf import settings from django.contrib import messages from django.http import HttpResponseForbidden from mongoengine.fields import EmbeddedDocumentField from mongonaut.exceptions import NoMongoAdminSpecified from mongonaut.forms import MongoModelForm from mongonaut.forms.form_utils import has_digit from mongonaut.forms.form_utils import make_key from mongonaut.utils import translate_value from mongonaut.utils import trim_field_key and context (classes, functions, or code) from other files: # Path: mongonaut/exceptions.py # class NoMongoAdminSpecified(Exception): # """ Called when no MongoAdmin is specified. Unlikely to ever be called.""" # pass # # Path: mongonaut/forms/form_utils.py # def has_digit(string_or_list, sep="_"): # """ # Given a string or a list will return true if the last word or # element is a digit. sep is used when a string is given to know # what separates one word from another. # """ # if isinstance(string_or_list, (tuple, list)): # list_length = len(string_or_list) # if list_length: # return six.text_type(string_or_list[-1]).isdigit() # else: # return False # else: # return has_digit(string_or_list.split(sep)) # # Path: mongonaut/forms/form_utils.py # def make_key(*args, **kwargs): # """ # Given any number of lists and strings will join them in order as one # string separated by the sep kwarg. sep defaults to u"_". # # Add exclude_last_string=True as a kwarg to exclude the last item in a # given string after being split by sep. Note if you only have one word # in your string you can end up getting an empty string. # # Example uses: # # >>> from mongonaut.forms.form_utils import make_key # >>> make_key('hi', 'my', 'firend') # >>> u'hi_my_firend' # # >>> make_key('hi', 'my', 'firend', sep='i') # >>> 'hiimyifirend' # # >>> make_key('hi', 'my', 'firend',['this', 'be', 'what'], sep='i') # >>> 'hiimyifirendithisibeiwhat' # # >>> make_key('hi', 'my', 'firend',['this', 'be', 'what']) # >>> u'hi_my_firend_this_be_what' # # """ # sep = kwargs.get('sep', u"_") # exclude_last_string = kwargs.get('exclude_last_string', False) # string_array = [] # # for arg in args: # if isinstance(arg, list): # string_array.append(six.text_type(sep.join(arg))) # else: # if exclude_last_string: # new_key_array = arg.split(sep)[:-1] # if len(new_key_array) > 0: # string_array.append(make_key(new_key_array)) # else: # string_array.append(six.text_type(arg)) # return sep.join(string_array) # # Path: mongonaut/utils.py # def translate_value(document_field, form_value): # """ # Given a document_field and a form_value this will translate the value # to the correct result for mongo to use. # """ # value = form_value # if isinstance(document_field, ReferenceField): # value = document_field.document_type.objects.get(id=form_value) if form_value else None # return value # # Path: mongonaut/utils.py # def trim_field_key(document, field_key): # """ # Returns the smallest delimited version of field_key that # is an attribute on document. # # return (key, left_over_array) # """ # trimming = True # left_over_key_values = [] # current_key = field_key # while trimming and current_key: # if hasattr(document, current_key): # trimming = False # else: # key_array = current_key.split("_") # left_over_key_values.append(key_array.pop()) # current_key = u"_".join(key_array) # # left_over_key_values.reverse() # return current_key, left_over_key_values . Output only the next line.
value = translate_value(document._fields[current_key],
Based on the snippet: <|code_start|> self.document_map_dict = MongoModelForm(model=self.document_type).create_document_dictionary(self.document_type) self.new_document = self.document_type # Used to keep track of embedded documents in lists. Keyed by the list and the number of the # document. self.embedded_list_docs = {} if self.new_document is None: messages.error(self.request, u"Failed to save document") else: self.new_document = self.new_document() for form_key in self.form.cleaned_data.keys(): if form_key == 'id' and hasattr(self, 'document'): self.new_document.id = self.document.id continue self.process_document(self.new_document, form_key, None) self.new_document.save() if success_message: messages.success(self.request, success_message) return self.form def process_document(self, document, form_key, passed_key): """ Given the form_key will evaluate the document and set values correctly for the document given. """ if passed_key is not None: <|code_end|> , predict the immediate next line with the help of imports: import types from importlib import import_module from django.conf import settings from django.contrib import messages from django.http import HttpResponseForbidden from mongoengine.fields import EmbeddedDocumentField from mongonaut.exceptions import NoMongoAdminSpecified from mongonaut.forms import MongoModelForm from mongonaut.forms.form_utils import has_digit from mongonaut.forms.form_utils import make_key from mongonaut.utils import translate_value from mongonaut.utils import trim_field_key and context (classes, functions, sometimes code) from other files: # Path: mongonaut/exceptions.py # class NoMongoAdminSpecified(Exception): # """ Called when no MongoAdmin is specified. Unlikely to ever be called.""" # pass # # Path: mongonaut/forms/form_utils.py # def has_digit(string_or_list, sep="_"): # """ # Given a string or a list will return true if the last word or # element is a digit. sep is used when a string is given to know # what separates one word from another. # """ # if isinstance(string_or_list, (tuple, list)): # list_length = len(string_or_list) # if list_length: # return six.text_type(string_or_list[-1]).isdigit() # else: # return False # else: # return has_digit(string_or_list.split(sep)) # # Path: mongonaut/forms/form_utils.py # def make_key(*args, **kwargs): # """ # Given any number of lists and strings will join them in order as one # string separated by the sep kwarg. sep defaults to u"_". # # Add exclude_last_string=True as a kwarg to exclude the last item in a # given string after being split by sep. Note if you only have one word # in your string you can end up getting an empty string. # # Example uses: # # >>> from mongonaut.forms.form_utils import make_key # >>> make_key('hi', 'my', 'firend') # >>> u'hi_my_firend' # # >>> make_key('hi', 'my', 'firend', sep='i') # >>> 'hiimyifirend' # # >>> make_key('hi', 'my', 'firend',['this', 'be', 'what'], sep='i') # >>> 'hiimyifirendithisibeiwhat' # # >>> make_key('hi', 'my', 'firend',['this', 'be', 'what']) # >>> u'hi_my_firend_this_be_what' # # """ # sep = kwargs.get('sep', u"_") # exclude_last_string = kwargs.get('exclude_last_string', False) # string_array = [] # # for arg in args: # if isinstance(arg, list): # string_array.append(six.text_type(sep.join(arg))) # else: # if exclude_last_string: # new_key_array = arg.split(sep)[:-1] # if len(new_key_array) > 0: # string_array.append(make_key(new_key_array)) # else: # string_array.append(six.text_type(arg)) # return sep.join(string_array) # # Path: mongonaut/utils.py # def translate_value(document_field, form_value): # """ # Given a document_field and a form_value this will translate the value # to the correct result for mongo to use. # """ # value = form_value # if isinstance(document_field, ReferenceField): # value = document_field.document_type.objects.get(id=form_value) if form_value else None # return value # # Path: mongonaut/utils.py # def trim_field_key(document, field_key): # """ # Returns the smallest delimited version of field_key that # is an attribute on document. # # return (key, left_over_array) # """ # trimming = True # left_over_key_values = [] # current_key = field_key # while trimming and current_key: # if hasattr(document, current_key): # trimming = False # else: # key_array = current_key.split("_") # left_over_key_values.append(key_array.pop()) # current_key = u"_".join(key_array) # # left_over_key_values.reverse() # return current_key, left_over_key_values . Output only the next line.
current_key, remaining_key_array = trim_field_key(document, passed_key)
Given snippet: <|code_start|> raise TypeError(u"The model supplied must be a mongoengine Document") if self.is_initialized and not isinstance(self.model_instance, self.model): raise TypeError(u"The provided instance must be an instance of the given model") if self.post_data_dict is not None and not isinstance(self.post_data_dict, dict): raise TypeError(u"You must pass in a dictionary for form_post_data") def get_form_field_dict(self, model_dict): """ Takes a model dictionary representation and creates a dictionary keyed by form field. Each value is a keyed 4 tuple of: (widget, mode_field_instance, model_field_type, field_key) """ return_dict = OrderedDict() # Workaround: mongoengine doesn't preserve form fields ordering from metaclass __new__ if hasattr(self.model, 'Meta') and hasattr(self.model.Meta, 'form_fields_ordering'): field_order_list = tuple(form_field for form_field in self.model.Meta.form_fields_ordering if form_field in model_dict.iterkeys()) order_dict = OrderedDict.fromkeys(field_order_list) return_dict = order_dict for field_key, field_dict in sorted(model_dict.items()): if not field_key.startswith("_"): widget = field_dict.get('_widget', None) if widget is None: return_dict[field_key] = self.get_form_field_dict(field_dict) return_dict[field_key].update({'_field_type': field_dict.get('_field_type', None)}) else: <|code_end|> , continue by predicting the next line. Consider current file imports: import six from copy import deepcopy from django import forms from mongoengine.base import BaseList from mongoengine.base import TopLevelDocumentMetaclass from mongoengine.fields import Document from mongoengine.fields import EmbeddedDocumentField from mongoengine.fields import ListField from mongoengine.fields import ReferenceField from .form_utils import FieldTuple from .form_utils import has_digit from .form_utils import make_key from .widgets import get_form_field_class from mongonaut.utils import trim_field_key from collections import OrderedDict and context: # Path: mongonaut/forms/form_utils.py # def has_digit(string_or_list, sep="_"): # def make_key(*args, **kwargs): # # Path: mongonaut/forms/form_utils.py # def has_digit(string_or_list, sep="_"): # """ # Given a string or a list will return true if the last word or # element is a digit. sep is used when a string is given to know # what separates one word from another. # """ # if isinstance(string_or_list, (tuple, list)): # list_length = len(string_or_list) # if list_length: # return six.text_type(string_or_list[-1]).isdigit() # else: # return False # else: # return has_digit(string_or_list.split(sep)) # # Path: mongonaut/forms/form_utils.py # def make_key(*args, **kwargs): # """ # Given any number of lists and strings will join them in order as one # string separated by the sep kwarg. sep defaults to u"_". # # Add exclude_last_string=True as a kwarg to exclude the last item in a # given string after being split by sep. Note if you only have one word # in your string you can end up getting an empty string. # # Example uses: # # >>> from mongonaut.forms.form_utils import make_key # >>> make_key('hi', 'my', 'firend') # >>> u'hi_my_firend' # # >>> make_key('hi', 'my', 'firend', sep='i') # >>> 'hiimyifirend' # # >>> make_key('hi', 'my', 'firend',['this', 'be', 'what'], sep='i') # >>> 'hiimyifirendithisibeiwhat' # # >>> make_key('hi', 'my', 'firend',['this', 'be', 'what']) # >>> u'hi_my_firend_this_be_what' # # """ # sep = kwargs.get('sep', u"_") # exclude_last_string = kwargs.get('exclude_last_string', False) # string_array = [] # # for arg in args: # if isinstance(arg, list): # string_array.append(six.text_type(sep.join(arg))) # else: # if exclude_last_string: # new_key_array = arg.split(sep)[:-1] # if len(new_key_array) > 0: # string_array.append(make_key(new_key_array)) # else: # string_array.append(six.text_type(arg)) # return sep.join(string_array) # # Path: mongonaut/forms/widgets.py # def get_form_field_class(model_field): # """Gets the default form field for a mongoenigne field.""" # # FIELD_MAPPING = { # IntField: forms.IntegerField, # StringField: forms.CharField, # FloatField: forms.FloatField, # BooleanField: forms.BooleanField, # DateTimeField: forms.DateTimeField, # DecimalField: forms.DecimalField, # URLField: forms.URLField, # EmailField: forms.EmailField # } # # return FIELD_MAPPING.get(model_field.__class__, forms.CharField) # # Path: mongonaut/utils.py # def trim_field_key(document, field_key): # """ # Returns the smallest delimited version of field_key that # is an attribute on document. # # return (key, left_over_array) # """ # trimming = True # left_over_key_values = [] # current_key = field_key # while trimming and current_key: # if hasattr(document, current_key): # trimming = False # else: # key_array = current_key.split("_") # left_over_key_values.append(key_array.pop()) # current_key = u"_".join(key_array) # # left_over_key_values.reverse() # return current_key, left_over_key_values which might include code, classes, or functions. Output only the next line.
return_dict[field_key] = FieldTuple(widget,
Based on the snippet: <|code_start|> def set_form_fields(self, form_field_dict, parent_key=None, field_type=None): """ Set the form fields for every key in the form_field_dict. Params: form_field_dict -- a dictionary created by get_form_field_dict parent_key -- the key for the previous key in the recursive call field_type -- used to determine what kind of field we are setting """ for form_key, field_value in form_field_dict.items(): form_key = make_key(parent_key, form_key) if parent_key is not None else form_key if isinstance(field_value, tuple): set_list_class = False base_key = form_key # Style list fields if ListField in (field_value.field_type, field_type): # Nested lists/embedded docs need special care to get # styles to work out nicely. if parent_key is None or ListField == field_value.field_type: if field_type != EmbeddedDocumentField: field_value.widget.attrs['class'] += ' listField {0}'.format(form_key) set_list_class = True else: field_value.widget.attrs['class'] += ' listField' # Compute number value for list key list_keys = [field_key for field_key in self.form.fields.keys() <|code_end|> , predict the immediate next line with the help of imports: import six from copy import deepcopy from django import forms from mongoengine.base import BaseList from mongoengine.base import TopLevelDocumentMetaclass from mongoengine.fields import Document from mongoengine.fields import EmbeddedDocumentField from mongoengine.fields import ListField from mongoengine.fields import ReferenceField from .form_utils import FieldTuple from .form_utils import has_digit from .form_utils import make_key from .widgets import get_form_field_class from mongonaut.utils import trim_field_key from collections import OrderedDict and context (classes, functions, sometimes code) from other files: # Path: mongonaut/forms/form_utils.py # def has_digit(string_or_list, sep="_"): # def make_key(*args, **kwargs): # # Path: mongonaut/forms/form_utils.py # def has_digit(string_or_list, sep="_"): # """ # Given a string or a list will return true if the last word or # element is a digit. sep is used when a string is given to know # what separates one word from another. # """ # if isinstance(string_or_list, (tuple, list)): # list_length = len(string_or_list) # if list_length: # return six.text_type(string_or_list[-1]).isdigit() # else: # return False # else: # return has_digit(string_or_list.split(sep)) # # Path: mongonaut/forms/form_utils.py # def make_key(*args, **kwargs): # """ # Given any number of lists and strings will join them in order as one # string separated by the sep kwarg. sep defaults to u"_". # # Add exclude_last_string=True as a kwarg to exclude the last item in a # given string after being split by sep. Note if you only have one word # in your string you can end up getting an empty string. # # Example uses: # # >>> from mongonaut.forms.form_utils import make_key # >>> make_key('hi', 'my', 'firend') # >>> u'hi_my_firend' # # >>> make_key('hi', 'my', 'firend', sep='i') # >>> 'hiimyifirend' # # >>> make_key('hi', 'my', 'firend',['this', 'be', 'what'], sep='i') # >>> 'hiimyifirendithisibeiwhat' # # >>> make_key('hi', 'my', 'firend',['this', 'be', 'what']) # >>> u'hi_my_firend_this_be_what' # # """ # sep = kwargs.get('sep', u"_") # exclude_last_string = kwargs.get('exclude_last_string', False) # string_array = [] # # for arg in args: # if isinstance(arg, list): # string_array.append(six.text_type(sep.join(arg))) # else: # if exclude_last_string: # new_key_array = arg.split(sep)[:-1] # if len(new_key_array) > 0: # string_array.append(make_key(new_key_array)) # else: # string_array.append(six.text_type(arg)) # return sep.join(string_array) # # Path: mongonaut/forms/widgets.py # def get_form_field_class(model_field): # """Gets the default form field for a mongoenigne field.""" # # FIELD_MAPPING = { # IntField: forms.IntegerField, # StringField: forms.CharField, # FloatField: forms.FloatField, # BooleanField: forms.BooleanField, # DateTimeField: forms.DateTimeField, # DecimalField: forms.DecimalField, # URLField: forms.URLField, # EmailField: forms.EmailField # } # # return FIELD_MAPPING.get(model_field.__class__, forms.CharField) # # Path: mongonaut/utils.py # def trim_field_key(document, field_key): # """ # Returns the smallest delimited version of field_key that # is an attribute on document. # # return (key, left_over_array) # """ # trimming = True # left_over_key_values = [] # current_key = field_key # while trimming and current_key: # if hasattr(document, current_key): # trimming = False # else: # key_array = current_key.split("_") # left_over_key_values.append(key_array.pop()) # current_key = u"_".join(key_array) # # left_over_key_values.reverse() # return current_key, left_over_key_values . Output only the next line.
if has_digit(field_key)]
Continue the code snippet: <|code_start|> if hasattr(self.model, 'Meta') and hasattr(self.model.Meta, 'form_fields_ordering'): field_order_list = tuple(form_field for form_field in self.model.Meta.form_fields_ordering if form_field in model_dict.iterkeys()) order_dict = OrderedDict.fromkeys(field_order_list) return_dict = order_dict for field_key, field_dict in sorted(model_dict.items()): if not field_key.startswith("_"): widget = field_dict.get('_widget', None) if widget is None: return_dict[field_key] = self.get_form_field_dict(field_dict) return_dict[field_key].update({'_field_type': field_dict.get('_field_type', None)}) else: return_dict[field_key] = FieldTuple(widget, field_dict.get('_document_field', None), field_dict.get('_field_type', None), field_dict.get('_key', None)) return return_dict def set_form_fields(self, form_field_dict, parent_key=None, field_type=None): """ Set the form fields for every key in the form_field_dict. Params: form_field_dict -- a dictionary created by get_form_field_dict parent_key -- the key for the previous key in the recursive call field_type -- used to determine what kind of field we are setting """ for form_key, field_value in form_field_dict.items(): <|code_end|> . Use current file imports: import six from copy import deepcopy from django import forms from mongoengine.base import BaseList from mongoengine.base import TopLevelDocumentMetaclass from mongoengine.fields import Document from mongoengine.fields import EmbeddedDocumentField from mongoengine.fields import ListField from mongoengine.fields import ReferenceField from .form_utils import FieldTuple from .form_utils import has_digit from .form_utils import make_key from .widgets import get_form_field_class from mongonaut.utils import trim_field_key from collections import OrderedDict and context (classes, functions, or code) from other files: # Path: mongonaut/forms/form_utils.py # def has_digit(string_or_list, sep="_"): # def make_key(*args, **kwargs): # # Path: mongonaut/forms/form_utils.py # def has_digit(string_or_list, sep="_"): # """ # Given a string or a list will return true if the last word or # element is a digit. sep is used when a string is given to know # what separates one word from another. # """ # if isinstance(string_or_list, (tuple, list)): # list_length = len(string_or_list) # if list_length: # return six.text_type(string_or_list[-1]).isdigit() # else: # return False # else: # return has_digit(string_or_list.split(sep)) # # Path: mongonaut/forms/form_utils.py # def make_key(*args, **kwargs): # """ # Given any number of lists and strings will join them in order as one # string separated by the sep kwarg. sep defaults to u"_". # # Add exclude_last_string=True as a kwarg to exclude the last item in a # given string after being split by sep. Note if you only have one word # in your string you can end up getting an empty string. # # Example uses: # # >>> from mongonaut.forms.form_utils import make_key # >>> make_key('hi', 'my', 'firend') # >>> u'hi_my_firend' # # >>> make_key('hi', 'my', 'firend', sep='i') # >>> 'hiimyifirend' # # >>> make_key('hi', 'my', 'firend',['this', 'be', 'what'], sep='i') # >>> 'hiimyifirendithisibeiwhat' # # >>> make_key('hi', 'my', 'firend',['this', 'be', 'what']) # >>> u'hi_my_firend_this_be_what' # # """ # sep = kwargs.get('sep', u"_") # exclude_last_string = kwargs.get('exclude_last_string', False) # string_array = [] # # for arg in args: # if isinstance(arg, list): # string_array.append(six.text_type(sep.join(arg))) # else: # if exclude_last_string: # new_key_array = arg.split(sep)[:-1] # if len(new_key_array) > 0: # string_array.append(make_key(new_key_array)) # else: # string_array.append(six.text_type(arg)) # return sep.join(string_array) # # Path: mongonaut/forms/widgets.py # def get_form_field_class(model_field): # """Gets the default form field for a mongoenigne field.""" # # FIELD_MAPPING = { # IntField: forms.IntegerField, # StringField: forms.CharField, # FloatField: forms.FloatField, # BooleanField: forms.BooleanField, # DateTimeField: forms.DateTimeField, # DecimalField: forms.DecimalField, # URLField: forms.URLField, # EmailField: forms.EmailField # } # # return FIELD_MAPPING.get(model_field.__class__, forms.CharField) # # Path: mongonaut/utils.py # def trim_field_key(document, field_key): # """ # Returns the smallest delimited version of field_key that # is an attribute on document. # # return (key, left_over_array) # """ # trimming = True # left_over_key_values = [] # current_key = field_key # while trimming and current_key: # if hasattr(document, current_key): # trimming = False # else: # key_array = current_key.split("_") # left_over_key_values.append(key_array.pop()) # current_key = u"_".join(key_array) # # left_over_key_values.reverse() # return current_key, left_over_key_values . Output only the next line.
form_key = make_key(parent_key, form_key) if parent_key is not None else form_key
Given the code snippet: <|code_start|> list_widget = deepcopy(field_value.widget) new_key = make_key(new_base_key, six.text_type(key_index)) list_widget.attrs['class'] += " {0}".format(make_key(base_key, key_index)) self.set_form_field(list_widget, field_value.document_field, new_key, list_value) key_index += 1 else: self.set_form_field(field_value.widget, field_value.document_field, form_key, default_value) elif isinstance(field_value, dict): self.set_form_fields(field_value, form_key, field_value.get("_field_type", None)) def set_form_field(self, widget, model_field, field_key, default_value): """ Parmams: widget -- the widget to use for displyaing the model_field model_field -- the field on the model to create a form field with field_key -- the name for the field on the form default_value -- the value to give for the field Default: None """ # Empty lists cause issues on form validation if default_value == []: default_value = None if widget and isinstance(widget, forms.widgets.Select): self.form.fields[field_key] = forms.ChoiceField(label=model_field.name, required=model_field.required, widget=widget) else: <|code_end|> , generate the next line using the imports in this file: import six from copy import deepcopy from django import forms from mongoengine.base import BaseList from mongoengine.base import TopLevelDocumentMetaclass from mongoengine.fields import Document from mongoengine.fields import EmbeddedDocumentField from mongoengine.fields import ListField from mongoengine.fields import ReferenceField from .form_utils import FieldTuple from .form_utils import has_digit from .form_utils import make_key from .widgets import get_form_field_class from mongonaut.utils import trim_field_key from collections import OrderedDict and context (functions, classes, or occasionally code) from other files: # Path: mongonaut/forms/form_utils.py # def has_digit(string_or_list, sep="_"): # def make_key(*args, **kwargs): # # Path: mongonaut/forms/form_utils.py # def has_digit(string_or_list, sep="_"): # """ # Given a string or a list will return true if the last word or # element is a digit. sep is used when a string is given to know # what separates one word from another. # """ # if isinstance(string_or_list, (tuple, list)): # list_length = len(string_or_list) # if list_length: # return six.text_type(string_or_list[-1]).isdigit() # else: # return False # else: # return has_digit(string_or_list.split(sep)) # # Path: mongonaut/forms/form_utils.py # def make_key(*args, **kwargs): # """ # Given any number of lists and strings will join them in order as one # string separated by the sep kwarg. sep defaults to u"_". # # Add exclude_last_string=True as a kwarg to exclude the last item in a # given string after being split by sep. Note if you only have one word # in your string you can end up getting an empty string. # # Example uses: # # >>> from mongonaut.forms.form_utils import make_key # >>> make_key('hi', 'my', 'firend') # >>> u'hi_my_firend' # # >>> make_key('hi', 'my', 'firend', sep='i') # >>> 'hiimyifirend' # # >>> make_key('hi', 'my', 'firend',['this', 'be', 'what'], sep='i') # >>> 'hiimyifirendithisibeiwhat' # # >>> make_key('hi', 'my', 'firend',['this', 'be', 'what']) # >>> u'hi_my_firend_this_be_what' # # """ # sep = kwargs.get('sep', u"_") # exclude_last_string = kwargs.get('exclude_last_string', False) # string_array = [] # # for arg in args: # if isinstance(arg, list): # string_array.append(six.text_type(sep.join(arg))) # else: # if exclude_last_string: # new_key_array = arg.split(sep)[:-1] # if len(new_key_array) > 0: # string_array.append(make_key(new_key_array)) # else: # string_array.append(six.text_type(arg)) # return sep.join(string_array) # # Path: mongonaut/forms/widgets.py # def get_form_field_class(model_field): # """Gets the default form field for a mongoenigne field.""" # # FIELD_MAPPING = { # IntField: forms.IntegerField, # StringField: forms.CharField, # FloatField: forms.FloatField, # BooleanField: forms.BooleanField, # DateTimeField: forms.DateTimeField, # DecimalField: forms.DecimalField, # URLField: forms.URLField, # EmailField: forms.EmailField # } # # return FIELD_MAPPING.get(model_field.__class__, forms.CharField) # # Path: mongonaut/utils.py # def trim_field_key(document, field_key): # """ # Returns the smallest delimited version of field_key that # is an attribute on document. # # return (key, left_over_array) # """ # trimming = True # left_over_key_values = [] # current_key = field_key # while trimming and current_key: # if hasattr(document, current_key): # trimming = False # else: # key_array = current_key.split("_") # left_over_key_values.append(key_array.pop()) # current_key = u"_".join(key_array) # # left_over_key_values.reverse() # return current_key, left_over_key_values . Output only the next line.
field_class = get_form_field_class(model_field)
Based on the snippet: <|code_start|> else: self.form.fields[field_key].initial = default_value else: self.form.fields[field_key].initial = getattr(model_field, 'default', None) if isinstance(model_field, ReferenceField): self.form.fields[field_key].choices = [(six.text_type(x.id), get_document_unicode(x)) for x in model_field.document_type.objects.all()] # Adding in blank choice so a reference field can be deleted by selecting blank self.form.fields[field_key].choices.insert(0, ("", "")) elif model_field.choices: self.form.fields[field_key].choices = model_field.choices for key, form_attr in CHECK_ATTRS.items(): if hasattr(model_field, key): value = getattr(model_field, key) setattr(self.form.fields[field_key], key, value) def get_field_value(self, field_key): """ Given field_key will return value held at self.model_instance. If model_instance has not been provided will return None. """ def get_value(document, field_key): # Short circuit the function if we do not have a document if document is None: return None <|code_end|> , predict the immediate next line with the help of imports: import six from copy import deepcopy from django import forms from mongoengine.base import BaseList from mongoengine.base import TopLevelDocumentMetaclass from mongoengine.fields import Document from mongoengine.fields import EmbeddedDocumentField from mongoengine.fields import ListField from mongoengine.fields import ReferenceField from .form_utils import FieldTuple from .form_utils import has_digit from .form_utils import make_key from .widgets import get_form_field_class from mongonaut.utils import trim_field_key from collections import OrderedDict and context (classes, functions, sometimes code) from other files: # Path: mongonaut/forms/form_utils.py # def has_digit(string_or_list, sep="_"): # def make_key(*args, **kwargs): # # Path: mongonaut/forms/form_utils.py # def has_digit(string_or_list, sep="_"): # """ # Given a string or a list will return true if the last word or # element is a digit. sep is used when a string is given to know # what separates one word from another. # """ # if isinstance(string_or_list, (tuple, list)): # list_length = len(string_or_list) # if list_length: # return six.text_type(string_or_list[-1]).isdigit() # else: # return False # else: # return has_digit(string_or_list.split(sep)) # # Path: mongonaut/forms/form_utils.py # def make_key(*args, **kwargs): # """ # Given any number of lists and strings will join them in order as one # string separated by the sep kwarg. sep defaults to u"_". # # Add exclude_last_string=True as a kwarg to exclude the last item in a # given string after being split by sep. Note if you only have one word # in your string you can end up getting an empty string. # # Example uses: # # >>> from mongonaut.forms.form_utils import make_key # >>> make_key('hi', 'my', 'firend') # >>> u'hi_my_firend' # # >>> make_key('hi', 'my', 'firend', sep='i') # >>> 'hiimyifirend' # # >>> make_key('hi', 'my', 'firend',['this', 'be', 'what'], sep='i') # >>> 'hiimyifirendithisibeiwhat' # # >>> make_key('hi', 'my', 'firend',['this', 'be', 'what']) # >>> u'hi_my_firend_this_be_what' # # """ # sep = kwargs.get('sep', u"_") # exclude_last_string = kwargs.get('exclude_last_string', False) # string_array = [] # # for arg in args: # if isinstance(arg, list): # string_array.append(six.text_type(sep.join(arg))) # else: # if exclude_last_string: # new_key_array = arg.split(sep)[:-1] # if len(new_key_array) > 0: # string_array.append(make_key(new_key_array)) # else: # string_array.append(six.text_type(arg)) # return sep.join(string_array) # # Path: mongonaut/forms/widgets.py # def get_form_field_class(model_field): # """Gets the default form field for a mongoenigne field.""" # # FIELD_MAPPING = { # IntField: forms.IntegerField, # StringField: forms.CharField, # FloatField: forms.FloatField, # BooleanField: forms.BooleanField, # DateTimeField: forms.DateTimeField, # DecimalField: forms.DecimalField, # URLField: forms.URLField, # EmailField: forms.EmailField # } # # return FIELD_MAPPING.get(model_field.__class__, forms.CharField) # # Path: mongonaut/utils.py # def trim_field_key(document, field_key): # """ # Returns the smallest delimited version of field_key that # is an attribute on document. # # return (key, left_over_array) # """ # trimming = True # left_over_key_values = [] # current_key = field_key # while trimming and current_key: # if hasattr(document, current_key): # trimming = False # else: # key_array = current_key.split("_") # left_over_key_values.append(key_array.pop()) # current_key = u"_".join(key_array) # # left_over_key_values.reverse() # return current_key, left_over_key_values . Output only the next line.
current_key, new_key_array = trim_field_key(document, field_key)
Next line prediction: <|code_start|> PLAT_LINE_SEP = '\n' class BaseGenerator(object): """Base generator class""" def __init__(self, site_config, base_path): """ :site_config: site global configuration parsed from _config.yml :base_path: root path of wiki directory """ self.site_config = copy.deepcopy(site_config) self.base_path = base_path self._templates = {} # templates cache self._template_vars = self._get_template_vars() _template_path = os.path.join( self.base_path, site_config["themes_dir"], site_config["theme"] ) if not os.path.exists(_template_path): raise Exception("Theme `{0}' not exists".format(_template_path)) self.env = Environment( loader=FileSystemLoader(_template_path) ) self._jinja_load_exts() def _jinja_load_exts(self): """Load jinja custom filters and extensions""" <|code_end|> . Use current file imports: (import os import os.path import io import copy import re import traceback import warnings import markdown import yaml from collections import OrderedDict from ordereddict import OrderedDict from jinja2 import (Environment, FileSystemLoader, TemplateError) from simiki import jinja_exts from simiki.utils import import_string from simiki.compat import is_py2, is_py3, basestring from functools import cmp_to_key) and context including class names, function names, or small code snippets from other files: # Path: simiki/jinja_exts.py # def rfc3339(dt_obj): # # Path: simiki/utils.py # def import_string(import_name, silent=False): # """Imports an object based on a string. This is useful if you want to # use import paths as endpoints or something similar. An import path can # be specified either in dotted notation (``xml.sax.saxutils.escape``) # or with a colon as object delimiter (``xml.sax.saxutils:escape``). # If `silent` is True the return value will be `None` if the import fails. # :param import_name: the dotted name for the object to import. # :param silent: if set to `True` import errors are ignored and # `None` is returned instead. # :return: imported object # """ # # ref: https://github.com/pallets/werkzeug/blob/master/werkzeug/utils.py # # # force the import name to automatically convert to strings # # __import__ is not able to handle unicode strings in the fromlist # # if the module is a package # import_name = str(import_name).replace(':', '.') # try: # try: # __import__(import_name) # except ImportError: # if '.' not in import_name: # raise # else: # return sys.modules[import_name] # # module_name, obj_name = import_name.rsplit('.', 1) # try: # module = __import__(module_name, None, None, [obj_name]) # except ImportError: # # support importing modules not yet set up by the parent module # # (or package for that matter) # module = import_string(module_name) # # try: # return getattr(module, obj_name) # except AttributeError as e: # raise ImportError(e) # # except ImportError as e: # if not silent: # raise ImportError(e) # # Path: simiki/compat.py . Output only the next line.
for _filter in jinja_exts.filters:
Given snippet: <|code_start|> markdown_extensions = self._set_markdown_extensions() html_content = markdown.markdown( markup_text, extensions=markdown_extensions, ) return html_content def _set_markdown_extensions(self): """Set the extensions for markdown parser""" # Default enabled extensions markdown_extensions_config = { "fenced_code": {}, "nl2br": {}, "toc": {"title": "Table of Contents"}, "extra": {}, } # Handle pygments if self.site_config["pygments"]: markdown_extensions_config.update({ "codehilite": {"css_class": "hlcode"} }) # Handle markdown_ext # Ref: https://pythonhosted.org/Markdown/extensions/index.html#officially-supported-extensions # noqa if "markdown_ext" in self.site_config: markdown_extensions_config.update(self.site_config["markdown_ext"]) markdown_extensions = [] for k, v in markdown_extensions_config.items(): <|code_end|> , continue by predicting the next line. Consider current file imports: import os import os.path import io import copy import re import traceback import warnings import markdown import yaml from collections import OrderedDict from ordereddict import OrderedDict from jinja2 import (Environment, FileSystemLoader, TemplateError) from simiki import jinja_exts from simiki.utils import import_string from simiki.compat import is_py2, is_py3, basestring from functools import cmp_to_key and context: # Path: simiki/jinja_exts.py # def rfc3339(dt_obj): # # Path: simiki/utils.py # def import_string(import_name, silent=False): # """Imports an object based on a string. This is useful if you want to # use import paths as endpoints or something similar. An import path can # be specified either in dotted notation (``xml.sax.saxutils.escape``) # or with a colon as object delimiter (``xml.sax.saxutils:escape``). # If `silent` is True the return value will be `None` if the import fails. # :param import_name: the dotted name for the object to import. # :param silent: if set to `True` import errors are ignored and # `None` is returned instead. # :return: imported object # """ # # ref: https://github.com/pallets/werkzeug/blob/master/werkzeug/utils.py # # # force the import name to automatically convert to strings # # __import__ is not able to handle unicode strings in the fromlist # # if the module is a package # import_name = str(import_name).replace(':', '.') # try: # try: # __import__(import_name) # except ImportError: # if '.' not in import_name: # raise # else: # return sys.modules[import_name] # # module_name, obj_name = import_name.rsplit('.', 1) # try: # module = __import__(module_name, None, None, [obj_name]) # except ImportError: # # support importing modules not yet set up by the parent module # # (or package for that matter) # module = import_string(module_name) # # try: # return getattr(module, obj_name) # except AttributeError as e: # raise ImportError(e) # # except ImportError as e: # if not silent: # raise ImportError(e) # # Path: simiki/compat.py which might include code, classes, or functions. Output only the next line.
ext = import_string("markdown.extensions." + k).makeExtension()
Next line prediction: <|code_start|> return html @property def src_file(self): return self._src_file @src_file.setter def src_file(self, filename): self._src_file = os.path.relpath(filename, self.base_path) def get_meta_and_content(self, do_render=True): meta_str, content_str = self.extract_page(self._src_file) meta = self.parse_meta(meta_str) # This is the most time consuming part if do_render and meta.get('render', True): content = self._parse_markup(content_str) else: content = content_str return meta, content def get_layout(self, meta): """Get layout config in meta, default is `page'""" if "layout" in meta: # Compatible with previous version, which default layout is "post" # XXX Will remove this checker in v2.0 if meta["layout"] == "post": warn_msg = "{0}: layout `post' is deprecated, use `page'" \ .format(self._src_file) <|code_end|> . Use current file imports: (import os import os.path import io import copy import re import traceback import warnings import markdown import yaml from collections import OrderedDict from ordereddict import OrderedDict from jinja2 import (Environment, FileSystemLoader, TemplateError) from simiki import jinja_exts from simiki.utils import import_string from simiki.compat import is_py2, is_py3, basestring from functools import cmp_to_key) and context including class names, function names, or small code snippets from other files: # Path: simiki/jinja_exts.py # def rfc3339(dt_obj): # # Path: simiki/utils.py # def import_string(import_name, silent=False): # """Imports an object based on a string. This is useful if you want to # use import paths as endpoints or something similar. An import path can # be specified either in dotted notation (``xml.sax.saxutils.escape``) # or with a colon as object delimiter (``xml.sax.saxutils:escape``). # If `silent` is True the return value will be `None` if the import fails. # :param import_name: the dotted name for the object to import. # :param silent: if set to `True` import errors are ignored and # `None` is returned instead. # :return: imported object # """ # # ref: https://github.com/pallets/werkzeug/blob/master/werkzeug/utils.py # # # force the import name to automatically convert to strings # # __import__ is not able to handle unicode strings in the fromlist # # if the module is a package # import_name = str(import_name).replace(':', '.') # try: # try: # __import__(import_name) # except ImportError: # if '.' not in import_name: # raise # else: # return sys.modules[import_name] # # module_name, obj_name = import_name.rsplit('.', 1) # try: # module = __import__(module_name, None, None, [obj_name]) # except ImportError: # # support importing modules not yet set up by the parent module # # (or package for that matter) # module = import_string(module_name) # # try: # return getattr(module, obj_name) # except AttributeError as e: # raise ImportError(e) # # except ImportError as e: # if not silent: # raise ImportError(e) # # Path: simiki/compat.py . Output only the next line.
if is_py2:
Using the snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """Convert Markdown file to html, which is embeded in html template. """ from __future__ import (print_function, with_statement, unicode_literals, absolute_import) try: except ImportError: <|code_end|> , determine the next line of code. You have imports: import os import os.path import io import copy import re import traceback import warnings import markdown import yaml from collections import OrderedDict from ordereddict import OrderedDict from jinja2 import (Environment, FileSystemLoader, TemplateError) from simiki import jinja_exts from simiki.utils import import_string from simiki.compat import is_py2, is_py3, basestring from functools import cmp_to_key and context (class names, function names, or code) available: # Path: simiki/jinja_exts.py # def rfc3339(dt_obj): # # Path: simiki/utils.py # def import_string(import_name, silent=False): # """Imports an object based on a string. This is useful if you want to # use import paths as endpoints or something similar. An import path can # be specified either in dotted notation (``xml.sax.saxutils.escape``) # or with a colon as object delimiter (``xml.sax.saxutils:escape``). # If `silent` is True the return value will be `None` if the import fails. # :param import_name: the dotted name for the object to import. # :param silent: if set to `True` import errors are ignored and # `None` is returned instead. # :return: imported object # """ # # ref: https://github.com/pallets/werkzeug/blob/master/werkzeug/utils.py # # # force the import name to automatically convert to strings # # __import__ is not able to handle unicode strings in the fromlist # # if the module is a package # import_name = str(import_name).replace(':', '.') # try: # try: # __import__(import_name) # except ImportError: # if '.' not in import_name: # raise # else: # return sys.modules[import_name] # # module_name, obj_name = import_name.rsplit('.', 1) # try: # module = __import__(module_name, None, None, [obj_name]) # except ImportError: # # support importing modules not yet set up by the parent module # # (or package for that matter) # module = import_string(module_name) # # try: # return getattr(module, obj_name) # except AttributeError as e: # raise ImportError(e) # # except ImportError as e: # if not silent: # raise ImportError(e) # # Path: simiki/compat.py . Output only the next line.
if is_py3:
Given the following code snippet before the placeholder: <|code_start|> returns: meta_str (str): page's meta string content_str (str): html parsed from markdown or other markup text. """ regex = re.compile('(?sm)^---(?P<meta>.*?)^---(?P<body>.*)') with io.open(filename, "rt", encoding="utf-8") as fd: match_obj = re.match(regex, fd.read()) if match_obj: meta_str = match_obj.group('meta') content_str = match_obj.group('body') else: raise Exception('extracting page with format error, ' 'see <http://simiki.org/docs/metadata.html>') return meta_str, content_str def parse_meta(self, yaml_str): """Parse meta from yaml string, and validate yaml filed, return dict""" try: meta = yaml.load(yaml_str, Loader=yaml.FullLoader) except yaml.YAMLError as e: e.extra_msg = 'yaml format error' raise category, src_fname = self.get_category_and_file() dst_fname = src_fname.replace( ".{0}".format(self.site_config['default_ext']), '.html') meta.update({'category': category, 'filename': dst_fname}) if 'tag' in meta: <|code_end|> , predict the next line using imports from the current file: import os import os.path import io import copy import re import traceback import warnings import markdown import yaml from collections import OrderedDict from ordereddict import OrderedDict from jinja2 import (Environment, FileSystemLoader, TemplateError) from simiki import jinja_exts from simiki.utils import import_string from simiki.compat import is_py2, is_py3, basestring from functools import cmp_to_key and context including class names, function names, and sometimes code from other files: # Path: simiki/jinja_exts.py # def rfc3339(dt_obj): # # Path: simiki/utils.py # def import_string(import_name, silent=False): # """Imports an object based on a string. This is useful if you want to # use import paths as endpoints or something similar. An import path can # be specified either in dotted notation (``xml.sax.saxutils.escape``) # or with a colon as object delimiter (``xml.sax.saxutils:escape``). # If `silent` is True the return value will be `None` if the import fails. # :param import_name: the dotted name for the object to import. # :param silent: if set to `True` import errors are ignored and # `None` is returned instead. # :return: imported object # """ # # ref: https://github.com/pallets/werkzeug/blob/master/werkzeug/utils.py # # # force the import name to automatically convert to strings # # __import__ is not able to handle unicode strings in the fromlist # # if the module is a package # import_name = str(import_name).replace(':', '.') # try: # try: # __import__(import_name) # except ImportError: # if '.' not in import_name: # raise # else: # return sys.modules[import_name] # # module_name, obj_name = import_name.rsplit('.', 1) # try: # module = __import__(module_name, None, None, [obj_name]) # except ImportError: # # support importing modules not yet set up by the parent module # # (or package for that matter) # module = import_string(module_name) # # try: # return getattr(module, obj_name) # except AttributeError as e: # raise ImportError(e) # # except ImportError as e: # if not silent: # raise ImportError(e) # # Path: simiki/compat.py . Output only the next line.
if isinstance(meta['tag'], basestring):
Given the code snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals, absolute_import yes_answer = ('y', 'yes') class Initiator(object): conf_template_dn = "conf_templates" config_fn = "_config.yml" fabfile_fn = "fabfile.py" demo_fn = "gettingstarted.md" dockerfile_fn = "Dockerfile" def __init__(self, config_file, target_path): self.config_file = config_file <|code_end|> , generate the next line using the imports in this file: import os import os.path import shutil import logging from simiki.config import parse_config from simiki.utils import (copytree, mkdir_p, listdir_nohidden) from simiki.compat import raw_input and context (functions, classes, or occasionally code) from other files: # Path: simiki/config.py # def parse_config(config_file): # if not os.path.exists(config_file): # raise ConfigFileNotFound("{0} not exists".format(config_file)) # # default_config = _set_default_config() # # with io.open(config_file, "rt", encoding="utf-8") as fd: # config = yaml.load(fd, Loader=yaml.FullLoader) # # default_config.update(config) # config = _post_process(default_config) # # return config # # Path: simiki/utils.py # def copytree(src, dst, symlinks=False, ignore=None): # """Copy from source directory to destination""" # # if not os.path.exists(dst): # os.makedirs(dst) # for item in os.listdir(src): # s = os.path.join(src, item) # d = os.path.join(dst, item) # if os.path.isdir(s): # copytree(s, d, symlinks, ignore) # else: # shutil.copy2(s, d) # # def mkdir_p(path): # """Make parent directories as needed, like `mkdir -p`""" # try: # os.makedirs(path) # except OSError as exc: # Python >2.5 # # if dir exists, not error # if exc.errno == errno.EEXIST and os.path.isdir(path): # pass # else: # raise # # def listdir_nohidden(path): # """List not hidden files or directories under path""" # for f in os.listdir(path): # if isinstance(f, str): # f = unicode(f) # if not f.startswith('.'): # yield f # # Path: simiki/compat.py . Output only the next line.
self.config = parse_config(self.config_file)
Continue the code snippet: <|code_start|> def get_dockerfile(self): src_dockerfile = os.path.join( self.source_path, self.conf_template_dn, self.dockerfile_fn ) dst_dockerfile = os.path.join(self.target_path, self.dockerfile_fn) self.get_file(src_dockerfile, dst_dockerfile) def get_demo_page(self): nohidden_dir = listdir_nohidden( os.path.join(self.target_path, self.config['source'])) # If there is file/directory under content, do not create first page if next(nohidden_dir, False): return src_demo = os.path.join(self.source_path, self.conf_template_dn, self.demo_fn) dst_demo = os.path.join(self.target_path, "content", "intro", self.demo_fn) self.get_file(src_demo, dst_demo) def get_default_theme(self, theme_path): default_theme_name = self.config['theme'] src_theme = os.path.join(self.source_path, self.config['themes_dir'], default_theme_name) dst_theme = os.path.join(theme_path, default_theme_name) if os.path.exists(dst_theme): logging.warning('{0} exists'.format(dst_theme)) else: <|code_end|> . Use current file imports: import os import os.path import shutil import logging from simiki.config import parse_config from simiki.utils import (copytree, mkdir_p, listdir_nohidden) from simiki.compat import raw_input and context (classes, functions, or code) from other files: # Path: simiki/config.py # def parse_config(config_file): # if not os.path.exists(config_file): # raise ConfigFileNotFound("{0} not exists".format(config_file)) # # default_config = _set_default_config() # # with io.open(config_file, "rt", encoding="utf-8") as fd: # config = yaml.load(fd, Loader=yaml.FullLoader) # # default_config.update(config) # config = _post_process(default_config) # # return config # # Path: simiki/utils.py # def copytree(src, dst, symlinks=False, ignore=None): # """Copy from source directory to destination""" # # if not os.path.exists(dst): # os.makedirs(dst) # for item in os.listdir(src): # s = os.path.join(src, item) # d = os.path.join(dst, item) # if os.path.isdir(s): # copytree(s, d, symlinks, ignore) # else: # shutil.copy2(s, d) # # def mkdir_p(path): # """Make parent directories as needed, like `mkdir -p`""" # try: # os.makedirs(path) # except OSError as exc: # Python >2.5 # # if dir exists, not error # if exc.errno == errno.EEXIST and os.path.isdir(path): # pass # else: # raise # # def listdir_nohidden(path): # """List not hidden files or directories under path""" # for f in os.listdir(path): # if isinstance(f, str): # f = unicode(f) # if not f.startswith('.'): # yield f # # Path: simiki/compat.py . Output only the next line.
copytree(src_theme, dst_theme)
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals, absolute_import yes_answer = ('y', 'yes') class Initiator(object): conf_template_dn = "conf_templates" config_fn = "_config.yml" fabfile_fn = "fabfile.py" demo_fn = "gettingstarted.md" dockerfile_fn = "Dockerfile" def __init__(self, config_file, target_path): self.config_file = config_file self.config = parse_config(self.config_file) self.source_path = os.path.dirname(__file__) self.target_path = target_path @staticmethod def get_file(src, dst): if os.path.exists(dst): logging.warning("{0} exists".format(dst)) return # Create parent directory dst_directory = os.path.dirname(dst) if not os.path.exists(dst_directory): <|code_end|> , generate the next line using the imports in this file: import os import os.path import shutil import logging from simiki.config import parse_config from simiki.utils import (copytree, mkdir_p, listdir_nohidden) from simiki.compat import raw_input and context (functions, classes, or occasionally code) from other files: # Path: simiki/config.py # def parse_config(config_file): # if not os.path.exists(config_file): # raise ConfigFileNotFound("{0} not exists".format(config_file)) # # default_config = _set_default_config() # # with io.open(config_file, "rt", encoding="utf-8") as fd: # config = yaml.load(fd, Loader=yaml.FullLoader) # # default_config.update(config) # config = _post_process(default_config) # # return config # # Path: simiki/utils.py # def copytree(src, dst, symlinks=False, ignore=None): # """Copy from source directory to destination""" # # if not os.path.exists(dst): # os.makedirs(dst) # for item in os.listdir(src): # s = os.path.join(src, item) # d = os.path.join(dst, item) # if os.path.isdir(s): # copytree(s, d, symlinks, ignore) # else: # shutil.copy2(s, d) # # def mkdir_p(path): # """Make parent directories as needed, like `mkdir -p`""" # try: # os.makedirs(path) # except OSError as exc: # Python >2.5 # # if dir exists, not error # if exc.errno == errno.EEXIST and os.path.isdir(path): # pass # else: # raise # # def listdir_nohidden(path): # """List not hidden files or directories under path""" # for f in os.listdir(path): # if isinstance(f, str): # f = unicode(f) # if not f.startswith('.'): # yield f # # Path: simiki/compat.py . Output only the next line.
mkdir_p(dst_directory)
Predict the next line for this snippet: <|code_start|> if not os.path.exists(dst_directory): mkdir_p(dst_directory) logging.info("Creating directory: {0}".format(dst_directory)) shutil.copyfile(src, dst) logging.info("Creating file: {0}".format(dst)) def get_config_file(self): dst_config_file = os.path.join(self.target_path, self.config_fn) self.get_file(self.config_file, dst_config_file) def get_fabfile(self): src_fabfile = os.path.join( self.source_path, self.conf_template_dn, self.fabfile_fn ) dst_fabfile = os.path.join(self.target_path, self.fabfile_fn) self.get_file(src_fabfile, dst_fabfile) def get_dockerfile(self): src_dockerfile = os.path.join( self.source_path, self.conf_template_dn, self.dockerfile_fn ) dst_dockerfile = os.path.join(self.target_path, self.dockerfile_fn) self.get_file(src_dockerfile, dst_dockerfile) def get_demo_page(self): <|code_end|> with the help of current file imports: import os import os.path import shutil import logging from simiki.config import parse_config from simiki.utils import (copytree, mkdir_p, listdir_nohidden) from simiki.compat import raw_input and context from other files: # Path: simiki/config.py # def parse_config(config_file): # if not os.path.exists(config_file): # raise ConfigFileNotFound("{0} not exists".format(config_file)) # # default_config = _set_default_config() # # with io.open(config_file, "rt", encoding="utf-8") as fd: # config = yaml.load(fd, Loader=yaml.FullLoader) # # default_config.update(config) # config = _post_process(default_config) # # return config # # Path: simiki/utils.py # def copytree(src, dst, symlinks=False, ignore=None): # """Copy from source directory to destination""" # # if not os.path.exists(dst): # os.makedirs(dst) # for item in os.listdir(src): # s = os.path.join(src, item) # d = os.path.join(dst, item) # if os.path.isdir(s): # copytree(s, d, symlinks, ignore) # else: # shutil.copy2(s, d) # # def mkdir_p(path): # """Make parent directories as needed, like `mkdir -p`""" # try: # os.makedirs(path) # except OSError as exc: # Python >2.5 # # if dir exists, not error # if exc.errno == errno.EEXIST and os.path.isdir(path): # pass # else: # raise # # def listdir_nohidden(path): # """List not hidden files or directories under path""" # for f in os.listdir(path): # if isinstance(f, str): # f = unicode(f) # if not f.startswith('.'): # yield f # # Path: simiki/compat.py , which may contain function names, class names, or code. Output only the next line.
nohidden_dir = listdir_nohidden(
Predict the next line after this snippet: <|code_start|> default_theme_name = self.config['theme'] src_theme = os.path.join(self.source_path, self.config['themes_dir'], default_theme_name) dst_theme = os.path.join(theme_path, default_theme_name) if os.path.exists(dst_theme): logging.warning('{0} exists'.format(dst_theme)) else: copytree(src_theme, dst_theme) logging.info("Copying default theme '{0}' to: {1}" .format(default_theme_name, theme_path)) def init(self, ask=False, **kwargs): content_path = os.path.join(self.target_path, self.config["source"]) output_path = os.path.join(self.target_path, self.config["destination"]) theme_path = os.path.join(self.target_path, self.config['themes_dir']) for path in (content_path, output_path, theme_path): if os.path.exists(path): logging.warning("{0} exists".format(path)) else: mkdir_p(path) logging.info("Creating directory: {0}".format(path)) self.get_config_file() self.get_fabfile() self.get_demo_page() self.get_default_theme(theme_path) if ask is True: try: <|code_end|> using the current file's imports: import os import os.path import shutil import logging from simiki.config import parse_config from simiki.utils import (copytree, mkdir_p, listdir_nohidden) from simiki.compat import raw_input and any relevant context from other files: # Path: simiki/config.py # def parse_config(config_file): # if not os.path.exists(config_file): # raise ConfigFileNotFound("{0} not exists".format(config_file)) # # default_config = _set_default_config() # # with io.open(config_file, "rt", encoding="utf-8") as fd: # config = yaml.load(fd, Loader=yaml.FullLoader) # # default_config.update(config) # config = _post_process(default_config) # # return config # # Path: simiki/utils.py # def copytree(src, dst, symlinks=False, ignore=None): # """Copy from source directory to destination""" # # if not os.path.exists(dst): # os.makedirs(dst) # for item in os.listdir(src): # s = os.path.join(src, item) # d = os.path.join(dst, item) # if os.path.isdir(s): # copytree(s, d, symlinks, ignore) # else: # shutil.copy2(s, d) # # def mkdir_p(path): # """Make parent directories as needed, like `mkdir -p`""" # try: # os.makedirs(path) # except OSError as exc: # Python >2.5 # # if dir exists, not error # if exc.errno == errno.EEXIST and os.path.isdir(path): # pass # else: # raise # # def listdir_nohidden(path): # """List not hidden files or directories under path""" # for f in os.listdir(path): # if isinstance(f, str): # f = unicode(f) # if not f.startswith('.'): # yield f # # Path: simiki/compat.py . Output only the next line.
_ans = raw_input('Create Dockerfile? (y/N) ')
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- class TestInitiator(unittest.TestCase): def setUp(self): BASE_DIR = os.path.join(os.path.dirname(__file__), '..') <|code_end|> , predict the next line using imports from the current file: import os import os.path import unittest import shutil from simiki.config import get_default_config from simiki.initiator import Initiator and context including class names, function names, and sometimes code from other files: # Path: simiki/config.py # def get_default_config(): # return _post_process(_set_default_config()) # # Path: simiki/initiator.py # class Initiator(object): # conf_template_dn = "conf_templates" # config_fn = "_config.yml" # fabfile_fn = "fabfile.py" # demo_fn = "gettingstarted.md" # dockerfile_fn = "Dockerfile" # # def __init__(self, config_file, target_path): # self.config_file = config_file # self.config = parse_config(self.config_file) # self.source_path = os.path.dirname(__file__) # self.target_path = target_path # # @staticmethod # def get_file(src, dst): # if os.path.exists(dst): # logging.warning("{0} exists".format(dst)) # return # # # Create parent directory # dst_directory = os.path.dirname(dst) # if not os.path.exists(dst_directory): # mkdir_p(dst_directory) # logging.info("Creating directory: {0}".format(dst_directory)) # # shutil.copyfile(src, dst) # logging.info("Creating file: {0}".format(dst)) # # def get_config_file(self): # dst_config_file = os.path.join(self.target_path, self.config_fn) # self.get_file(self.config_file, dst_config_file) # # def get_fabfile(self): # src_fabfile = os.path.join( # self.source_path, # self.conf_template_dn, # self.fabfile_fn # ) # dst_fabfile = os.path.join(self.target_path, self.fabfile_fn) # self.get_file(src_fabfile, dst_fabfile) # # def get_dockerfile(self): # src_dockerfile = os.path.join( # self.source_path, # self.conf_template_dn, # self.dockerfile_fn # ) # dst_dockerfile = os.path.join(self.target_path, self.dockerfile_fn) # self.get_file(src_dockerfile, dst_dockerfile) # # def get_demo_page(self): # nohidden_dir = listdir_nohidden( # os.path.join(self.target_path, self.config['source'])) # # If there is file/directory under content, do not create first page # if next(nohidden_dir, False): # return # # src_demo = os.path.join(self.source_path, self.conf_template_dn, # self.demo_fn) # dst_demo = os.path.join(self.target_path, "content", "intro", # self.demo_fn) # self.get_file(src_demo, dst_demo) # # def get_default_theme(self, theme_path): # default_theme_name = self.config['theme'] # src_theme = os.path.join(self.source_path, self.config['themes_dir'], # default_theme_name) # dst_theme = os.path.join(theme_path, default_theme_name) # if os.path.exists(dst_theme): # logging.warning('{0} exists'.format(dst_theme)) # else: # copytree(src_theme, dst_theme) # logging.info("Copying default theme '{0}' to: {1}" # .format(default_theme_name, theme_path)) # # def init(self, ask=False, **kwargs): # content_path = os.path.join(self.target_path, self.config["source"]) # output_path = os.path.join(self.target_path, # self.config["destination"]) # theme_path = os.path.join(self.target_path, self.config['themes_dir']) # for path in (content_path, output_path, theme_path): # if os.path.exists(path): # logging.warning("{0} exists".format(path)) # else: # mkdir_p(path) # logging.info("Creating directory: {0}".format(path)) # # self.get_config_file() # self.get_fabfile() # self.get_demo_page() # self.get_default_theme(theme_path) # # if ask is True: # try: # _ans = raw_input('Create Dockerfile? (y/N) ') # if _ans.lower() in yes_answer: # self.get_dockerfile() # except (KeyboardInterrupt, SystemExit): # print() # newline with Ctrl-C # elif ask is False and kwargs.get('dockerfile', False): # self.get_dockerfile() . Output only the next line.
self.default_config = get_default_config()
Next line prediction: <|code_start|> class TestInitiator(unittest.TestCase): def setUp(self): BASE_DIR = os.path.join(os.path.dirname(__file__), '..') self.default_config = get_default_config() self.config_file = os.path.join(BASE_DIR, "simiki", "conf_templates", "_config.yml.in") self.target_path = os.path.join(BASE_DIR, "tests", "_build") if os.path.exists(self.target_path): shutil.rmtree(self.target_path) self.files = [ "_config.yml", "fabfile.py", os.path.join(self.default_config['source'], "intro", "gettingstarted.md"), ] self.dirs = [ self.default_config['source'], self.default_config['destination'], self.default_config['themes_dir'], os.path.join(self.default_config['themes_dir'], self.default_config['theme']), ] def test_target_exist(self): """ test Initiator target path exist """ <|code_end|> . Use current file imports: (import os import os.path import unittest import shutil from simiki.config import get_default_config from simiki.initiator import Initiator) and context including class names, function names, or small code snippets from other files: # Path: simiki/config.py # def get_default_config(): # return _post_process(_set_default_config()) # # Path: simiki/initiator.py # class Initiator(object): # conf_template_dn = "conf_templates" # config_fn = "_config.yml" # fabfile_fn = "fabfile.py" # demo_fn = "gettingstarted.md" # dockerfile_fn = "Dockerfile" # # def __init__(self, config_file, target_path): # self.config_file = config_file # self.config = parse_config(self.config_file) # self.source_path = os.path.dirname(__file__) # self.target_path = target_path # # @staticmethod # def get_file(src, dst): # if os.path.exists(dst): # logging.warning("{0} exists".format(dst)) # return # # # Create parent directory # dst_directory = os.path.dirname(dst) # if not os.path.exists(dst_directory): # mkdir_p(dst_directory) # logging.info("Creating directory: {0}".format(dst_directory)) # # shutil.copyfile(src, dst) # logging.info("Creating file: {0}".format(dst)) # # def get_config_file(self): # dst_config_file = os.path.join(self.target_path, self.config_fn) # self.get_file(self.config_file, dst_config_file) # # def get_fabfile(self): # src_fabfile = os.path.join( # self.source_path, # self.conf_template_dn, # self.fabfile_fn # ) # dst_fabfile = os.path.join(self.target_path, self.fabfile_fn) # self.get_file(src_fabfile, dst_fabfile) # # def get_dockerfile(self): # src_dockerfile = os.path.join( # self.source_path, # self.conf_template_dn, # self.dockerfile_fn # ) # dst_dockerfile = os.path.join(self.target_path, self.dockerfile_fn) # self.get_file(src_dockerfile, dst_dockerfile) # # def get_demo_page(self): # nohidden_dir = listdir_nohidden( # os.path.join(self.target_path, self.config['source'])) # # If there is file/directory under content, do not create first page # if next(nohidden_dir, False): # return # # src_demo = os.path.join(self.source_path, self.conf_template_dn, # self.demo_fn) # dst_demo = os.path.join(self.target_path, "content", "intro", # self.demo_fn) # self.get_file(src_demo, dst_demo) # # def get_default_theme(self, theme_path): # default_theme_name = self.config['theme'] # src_theme = os.path.join(self.source_path, self.config['themes_dir'], # default_theme_name) # dst_theme = os.path.join(theme_path, default_theme_name) # if os.path.exists(dst_theme): # logging.warning('{0} exists'.format(dst_theme)) # else: # copytree(src_theme, dst_theme) # logging.info("Copying default theme '{0}' to: {1}" # .format(default_theme_name, theme_path)) # # def init(self, ask=False, **kwargs): # content_path = os.path.join(self.target_path, self.config["source"]) # output_path = os.path.join(self.target_path, # self.config["destination"]) # theme_path = os.path.join(self.target_path, self.config['themes_dir']) # for path in (content_path, output_path, theme_path): # if os.path.exists(path): # logging.warning("{0} exists".format(path)) # else: # mkdir_p(path) # logging.info("Creating directory: {0}".format(path)) # # self.get_config_file() # self.get_fabfile() # self.get_demo_page() # self.get_default_theme(theme_path) # # if ask is True: # try: # _ans = raw_input('Create Dockerfile? (y/N) ') # if _ans.lower() in yes_answer: # self.get_dockerfile() # except (KeyboardInterrupt, SystemExit): # print() # newline with Ctrl-C # elif ask is False and kwargs.get('dockerfile', False): # self.get_dockerfile() . Output only the next line.
i = Initiator(self.config_file, self.target_path)
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- """ Jinja2 custom filters and extensions """ filters = ['rfc3339'] def rfc3339(dt_obj): """ dt_obj: datetime object or string The filter use `datetime.datetime.isoformat()`, which is in ISO 8601 format, not in RFC 3339 format, but they have a lot in common, so I used ISO 8601 format directly. """ if isinstance(dt_obj, datetime.datetime): pass <|code_end|> with the help of current file imports: import datetime import tzlocal from simiki.compat import basestring and context from other files: # Path: simiki/compat.py , which may contain function names, class names, or code. Output only the next line.
elif isinstance(dt_obj, basestring):
Predict the next line for this snippet: <|code_start|> def setUp(self): logging.disable(logging.NOTSET) self.stream = StringIO() self.logger = logging.getLogger() self.handler = logging.StreamHandler(self.stream) for handler in self.logger.handlers: # exclude nosetest capture handler if not isinstance(handler, nose.plugins.logcapture.MyMemoryHandler): self.logger.removeHandler(handler) logging_init(level=logging.DEBUG, handler=self.handler) def test_logging_init(self): l2c = { "debug": "blue", "info": "green", "warning": "yellow", "error": "red", "critical": "bgred" } for level in l2c: # self.handler.flush() self.stream.truncate(0) # in python 3.x, truncate(0) would not change the current file pos # via <http://stackoverflow.com/a/4330829/1276501> self.stream.seek(0) func = getattr(self.logger, level) func(level) expected_output = "[{0}]: {1}" \ <|code_end|> with the help of current file imports: import unittest import logging import nose from cStringIO import StringIO from StringIO import StringIO from io import StringIO as StringIO from simiki.utils import color_msg from simiki.log import logging_init from simiki.compat import is_py2, unicode and context from other files: # Path: simiki/utils.py # def color_msg(color, msg): # return COLOR_CODES[color] + msg + COLOR_CODES["reset"] # # Path: simiki/log.py # def logging_init(level=None, logger=getLogger(), # handler=StreamHandler(), use_color=True): # if use_color and _is_platform_allowed_ansi(): # fmt = ANSIFormatter() # else: # fmt = NonANSIFormatter() # handler.setFormatter(fmt) # logger.addHandler(handler) # # if level: # logger.setLevel(level) # # Path: simiki/compat.py , which may contain function names, class names, or code. Output only the next line.
.format(color_msg(l2c[level], level.upper()), level)
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function, with_statement, unicode_literals try: # py2 except ImportError: try: # py2 except ImportError: # py3 # from io import BytesIO as StringIO class TestLogInit(unittest.TestCase): def setUp(self): logging.disable(logging.NOTSET) self.stream = StringIO() self.logger = logging.getLogger() self.handler = logging.StreamHandler(self.stream) for handler in self.logger.handlers: # exclude nosetest capture handler if not isinstance(handler, nose.plugins.logcapture.MyMemoryHandler): self.logger.removeHandler(handler) <|code_end|> using the current file's imports: import unittest import logging import nose from cStringIO import StringIO from StringIO import StringIO from io import StringIO as StringIO from simiki.utils import color_msg from simiki.log import logging_init from simiki.compat import is_py2, unicode and any relevant context from other files: # Path: simiki/utils.py # def color_msg(color, msg): # return COLOR_CODES[color] + msg + COLOR_CODES["reset"] # # Path: simiki/log.py # def logging_init(level=None, logger=getLogger(), # handler=StreamHandler(), use_color=True): # if use_color and _is_platform_allowed_ansi(): # fmt = ANSIFormatter() # else: # fmt = NonANSIFormatter() # handler.setFormatter(fmt) # logger.addHandler(handler) # # if level: # logger.setLevel(level) # # Path: simiki/compat.py . Output only the next line.
logging_init(level=logging.DEBUG, handler=self.handler)
Continue the code snippet: <|code_start|> logging.disable(logging.NOTSET) self.stream = StringIO() self.logger = logging.getLogger() self.handler = logging.StreamHandler(self.stream) for handler in self.logger.handlers: # exclude nosetest capture handler if not isinstance(handler, nose.plugins.logcapture.MyMemoryHandler): self.logger.removeHandler(handler) logging_init(level=logging.DEBUG, handler=self.handler) def test_logging_init(self): l2c = { "debug": "blue", "info": "green", "warning": "yellow", "error": "red", "critical": "bgred" } for level in l2c: # self.handler.flush() self.stream.truncate(0) # in python 3.x, truncate(0) would not change the current file pos # via <http://stackoverflow.com/a/4330829/1276501> self.stream.seek(0) func = getattr(self.logger, level) func(level) expected_output = "[{0}]: {1}" \ .format(color_msg(l2c[level], level.upper()), level) stream_output = self.stream.getvalue().strip() <|code_end|> . Use current file imports: import unittest import logging import nose from cStringIO import StringIO from StringIO import StringIO from io import StringIO as StringIO from simiki.utils import color_msg from simiki.log import logging_init from simiki.compat import is_py2, unicode and context (classes, functions, or code) from other files: # Path: simiki/utils.py # def color_msg(color, msg): # return COLOR_CODES[color] + msg + COLOR_CODES["reset"] # # Path: simiki/log.py # def logging_init(level=None, logger=getLogger(), # handler=StreamHandler(), use_color=True): # if use_color and _is_platform_allowed_ansi(): # fmt = ANSIFormatter() # else: # fmt = NonANSIFormatter() # handler.setFormatter(fmt) # logger.addHandler(handler) # # if level: # logger.setLevel(level) # # Path: simiki/compat.py . Output only the next line.
if is_py2:
Given the code snippet: <|code_start|> self.stream = StringIO() self.logger = logging.getLogger() self.handler = logging.StreamHandler(self.stream) for handler in self.logger.handlers: # exclude nosetest capture handler if not isinstance(handler, nose.plugins.logcapture.MyMemoryHandler): self.logger.removeHandler(handler) logging_init(level=logging.DEBUG, handler=self.handler) def test_logging_init(self): l2c = { "debug": "blue", "info": "green", "warning": "yellow", "error": "red", "critical": "bgred" } for level in l2c: # self.handler.flush() self.stream.truncate(0) # in python 3.x, truncate(0) would not change the current file pos # via <http://stackoverflow.com/a/4330829/1276501> self.stream.seek(0) func = getattr(self.logger, level) func(level) expected_output = "[{0}]: {1}" \ .format(color_msg(l2c[level], level.upper()), level) stream_output = self.stream.getvalue().strip() if is_py2: <|code_end|> , generate the next line using the imports in this file: import unittest import logging import nose from cStringIO import StringIO from StringIO import StringIO from io import StringIO as StringIO from simiki.utils import color_msg from simiki.log import logging_init from simiki.compat import is_py2, unicode and context (functions, classes, or occasionally code) from other files: # Path: simiki/utils.py # def color_msg(color, msg): # return COLOR_CODES[color] + msg + COLOR_CODES["reset"] # # Path: simiki/log.py # def logging_init(level=None, logger=getLogger(), # handler=StreamHandler(), use_color=True): # if use_color and _is_platform_allowed_ansi(): # fmt = ANSIFormatter() # else: # fmt = NonANSIFormatter() # handler.setFormatter(fmt) # logger.addHandler(handler) # # if level: # logger.setLevel(level) # # Path: simiki/compat.py . Output only the next line.
stream_output = unicode(stream_output)
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals test_path = os.path.dirname(os.path.abspath(__file__)) class TestUtils(unittest.TestCase): def setUp(self): wiki_path = os.path.join(test_path, 'mywiki_for_others') os.chdir(wiki_path) self.content = 'content' self.output = 'output' if os.path.exists(self.output): <|code_end|> , predict the next line using imports from the current file: import os import os.path import unittest from simiki import utils and context including class names, function names, and sometimes code from other files: # Path: simiki/utils.py # COLOR_CODES = { # "reset": "\033[0m", # "black": "\033[1;30m", # "red": "\033[1;31m", # "green": "\033[1;32m", # "yellow": "\033[1;33m", # "blue": "\033[1;34m", # "magenta": "\033[1;35m", # "cyan": "\033[1;36m", # "white": "\033[1;37m", # "bgred": "\033[1;41m", # "bggrey": "\033[1;100m", # } # def color_msg(color, msg): # def check_extension(filename): # def copytree(src, dst, symlinks=False, ignore=None): # def emptytree(directory, exclude_list=None): # def mkdir_p(path): # def listdir_nohidden(path): # def write_file(filename, content): # def get_md5(filename): # def get_dir_md5(dirname): # def import_string(import_name, silent=False): . Output only the next line.
utils.emptytree(self.output)
Given snippet: <|code_start|> class TestUpdater(unittest.TestCase): def setUp(self): self.default_config = get_default_config() self.wiki_path = os.path.join(test_path, 'mywiki_for_others') os.chdir(self.wiki_path) self.kwargs = {'themes_dir': 'themes'} self.original_fabfile = os.path.join(base_path, 'simiki', 'conf_templates', 'fabfile.py') self.local_fabfile = os.path.join(self.wiki_path, 'fabfile.py') self.original_theme = os.path.join(base_path, 'simiki', self.default_config['themes_dir'], self.default_config['theme']) self.local_theme = os.path.join(self.wiki_path, self.default_config['themes_dir'], self.default_config['theme']) self.local_theme_afile = os.path.join(self.local_theme, 'base.html') @patch('simiki.updater.get_input', return_value='yes') def test_update_builtin_not_exists_with_yes(self, mock_input): self.assertFalse(os.path.exists(self.local_fabfile)) self.assertFalse(os.path.exists(self.local_theme)) updater.update_builtin(**self.kwargs) <|code_end|> , continue by predicting the next line. Consider current file imports: import os import os.path import shutil import unittest from unittest.mock import patch from mock import patch from simiki import utils, updater from simiki.config import get_default_config and context: # Path: simiki/utils.py # COLOR_CODES = { # "reset": "\033[0m", # "black": "\033[1;30m", # "red": "\033[1;31m", # "green": "\033[1;32m", # "yellow": "\033[1;33m", # "blue": "\033[1;34m", # "magenta": "\033[1;35m", # "cyan": "\033[1;36m", # "white": "\033[1;37m", # "bgred": "\033[1;41m", # "bggrey": "\033[1;100m", # } # def color_msg(color, msg): # def check_extension(filename): # def copytree(src, dst, symlinks=False, ignore=None): # def emptytree(directory, exclude_list=None): # def mkdir_p(path): # def listdir_nohidden(path): # def write_file(filename, content): # def get_md5(filename): # def get_dir_md5(dirname): # def import_string(import_name, silent=False): # # Path: simiki/updater.py # def get_input(text): # def _update_file(filename, local_path, original_path): # def _update_dir(dirname, local_dir, original_dir, tag='directory'): # def update_builtin(**kwargs): # # Path: simiki/config.py # def get_default_config(): # return _post_process(_set_default_config()) which might include code, classes, or functions. Output only the next line.
original_fn_md5 = utils.get_md5(self.original_fabfile)
Predict the next line after this snippet: <|code_start|>base_path = os.path.dirname(test_path) class TestUpdater(unittest.TestCase): def setUp(self): self.default_config = get_default_config() self.wiki_path = os.path.join(test_path, 'mywiki_for_others') os.chdir(self.wiki_path) self.kwargs = {'themes_dir': 'themes'} self.original_fabfile = os.path.join(base_path, 'simiki', 'conf_templates', 'fabfile.py') self.local_fabfile = os.path.join(self.wiki_path, 'fabfile.py') self.original_theme = os.path.join(base_path, 'simiki', self.default_config['themes_dir'], self.default_config['theme']) self.local_theme = os.path.join(self.wiki_path, self.default_config['themes_dir'], self.default_config['theme']) self.local_theme_afile = os.path.join(self.local_theme, 'base.html') @patch('simiki.updater.get_input', return_value='yes') def test_update_builtin_not_exists_with_yes(self, mock_input): self.assertFalse(os.path.exists(self.local_fabfile)) self.assertFalse(os.path.exists(self.local_theme)) <|code_end|> using the current file's imports: import os import os.path import shutil import unittest from unittest.mock import patch from mock import patch from simiki import utils, updater from simiki.config import get_default_config and any relevant context from other files: # Path: simiki/utils.py # COLOR_CODES = { # "reset": "\033[0m", # "black": "\033[1;30m", # "red": "\033[1;31m", # "green": "\033[1;32m", # "yellow": "\033[1;33m", # "blue": "\033[1;34m", # "magenta": "\033[1;35m", # "cyan": "\033[1;36m", # "white": "\033[1;37m", # "bgred": "\033[1;41m", # "bggrey": "\033[1;100m", # } # def color_msg(color, msg): # def check_extension(filename): # def copytree(src, dst, symlinks=False, ignore=None): # def emptytree(directory, exclude_list=None): # def mkdir_p(path): # def listdir_nohidden(path): # def write_file(filename, content): # def get_md5(filename): # def get_dir_md5(dirname): # def import_string(import_name, silent=False): # # Path: simiki/updater.py # def get_input(text): # def _update_file(filename, local_path, original_path): # def _update_dir(dirname, local_dir, original_dir, tag='directory'): # def update_builtin(**kwargs): # # Path: simiki/config.py # def get_default_config(): # return _post_process(_set_default_config()) . Output only the next line.
updater.update_builtin(**self.kwargs)