Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Predict the next line after this snippet: <|code_start|>__author__ = 'Stuart Gordon Reid'
__email__ = 'stuartgordonreid@gmail.com'
__website__ = 'http://www.stuartreid.co.za'
"""
File description
"""
<|code_end|>
using the current file's imports:
import random
import profile
from Optimizers.Solution import Solution
from Problems.Cigar import Cigar
and any relevant context from other files:
# Path: Optimizers/Solution.py
# class Solution(object):
# solution = []
#
# def __init__(self, solution, problem):
# """
# Abstract initialization method for a solution to some optimization function
# :param solution: a numpy array (much faster than lists)
# """
# self.solution = solution
# self.problem = problem
# return
#
# def __len__(self):
# """
# Overload of the len operator for the Solution class
# :rtype : Sized?
# """
# return len(self.solution)
#
# def update(self, solution):
# """
# This method is used for updating a solution
# """
# self.solution = solution
#
# def get(self):
# """
# This method is used to retrieve the numpy array for direct manipulation
# """
# return self.solution
#
# def evaluate(self):
# return self.problem.evaluate(self.solution)
#
# def __gt__(self, other):
# assert isinstance(other, Solution)
# if self.problem.optimization is "min":
# return self.evaluate() < other.evaluate()
# elif self.problem.optimization is "max":
# return self.evaluate() > other.evaluate()
#
# def deep_copy(self):
# copy = Solution(None, self.problem)
# copy.solution = []
# for i in range(len(self.solution)):
# copy.solution.append(self.solution[i])
# return copy
#
# Path: Problems/Cigar.py
# class Cigar(Problem):
#
# def __init__(self, dimension, upper_bound, lower_bound, optimization="min"):
# super(Cigar, self).__init__(dimension, upper_bound, lower_bound, optimization)
#
# def evaluate(self, candidate):
# """
# LaTeX: f_{\textrm{Cigar}}(\textbf{x}) = x_0^2 + \sum_{i=1}^N x^2_i
# """
# value = 0
# for i in xrange(0, self.dimension):
# value += candidate[i] ** 2
# #ToDo: move this out into the Abstract base class and force call
# if candidate[i] > self.upper_bound or candidate < self.lower_bound:
# if self.optimization is "min":
# value = float("+inf")
# break
# elif self.optimization is "max":
# value = float("-inf")
# break
# return value
. Output only the next line. | class BrownianSolution(Solution): |
Predict the next line after this snippet: <|code_start|>__website__ = 'http://www.stuartreid.co.za'
"""
File description
"""
class BrownianSolution(Solution):
def __init__(self, solution, problem, parameters=None):
"""
:param solution: the initial solution
:param parameters: [0] num attempts, [1] variance
"""
super(BrownianSolution, self).__init__(solution, problem)
if parameters is None:
self.parameters = [10, 0.001]
def update_solution(self):
# For number of tries, try create a better solution randomly
for i in range(self.parameters[0]):
brownian = self.deep_copy()
dimension = random.randint(0, self.problem.dimension - 1)
brownian.solution[dimension] *= random.uniform(-self.parameters[1], self.parameters[1])
if brownian > self:
self.solution = brownian.solution
def brownian_solution_test():
<|code_end|>
using the current file's imports:
import random
import profile
from Optimizers.Solution import Solution
from Problems.Cigar import Cigar
and any relevant context from other files:
# Path: Optimizers/Solution.py
# class Solution(object):
# solution = []
#
# def __init__(self, solution, problem):
# """
# Abstract initialization method for a solution to some optimization function
# :param solution: a numpy array (much faster than lists)
# """
# self.solution = solution
# self.problem = problem
# return
#
# def __len__(self):
# """
# Overload of the len operator for the Solution class
# :rtype : Sized?
# """
# return len(self.solution)
#
# def update(self, solution):
# """
# This method is used for updating a solution
# """
# self.solution = solution
#
# def get(self):
# """
# This method is used to retrieve the numpy array for direct manipulation
# """
# return self.solution
#
# def evaluate(self):
# return self.problem.evaluate(self.solution)
#
# def __gt__(self, other):
# assert isinstance(other, Solution)
# if self.problem.optimization is "min":
# return self.evaluate() < other.evaluate()
# elif self.problem.optimization is "max":
# return self.evaluate() > other.evaluate()
#
# def deep_copy(self):
# copy = Solution(None, self.problem)
# copy.solution = []
# for i in range(len(self.solution)):
# copy.solution.append(self.solution[i])
# return copy
#
# Path: Problems/Cigar.py
# class Cigar(Problem):
#
# def __init__(self, dimension, upper_bound, lower_bound, optimization="min"):
# super(Cigar, self).__init__(dimension, upper_bound, lower_bound, optimization)
#
# def evaluate(self, candidate):
# """
# LaTeX: f_{\textrm{Cigar}}(\textbf{x}) = x_0^2 + \sum_{i=1}^N x^2_i
# """
# value = 0
# for i in xrange(0, self.dimension):
# value += candidate[i] ** 2
# #ToDo: move this out into the Abstract base class and force call
# if candidate[i] > self.upper_bound or candidate < self.lower_bound:
# if self.optimization is "min":
# value = float("+inf")
# break
# elif self.optimization is "max":
# value = float("-inf")
# break
# return value
. Output only the next line. | problem = Cigar(50, 25, -25) |
Based on the snippet: <|code_start|> self.parent.title(self.title)
self.content_grid = Frame(self.parent)
self.parent.geometry("%dx%d" % (self.width, self.height))
def pack_window(self):
"""
This method just 'packs' the window with the different components
"""
self.pack(fill=BOTH, expand=1)
def setup_grid(self, padding=1.0, rows=5, columns=5, grid_elements=None):
"""
This method initializes a grid within the root window
:param grid_elements: the particular layout for the canvases
:param rows: the number of rows to create
:param columns: the number of columns to create
"""
self.content_grid.grid(column=0, row=0, columnspan=columns, rowspan=rows)
self.fill_grid(padding, rows, columns, grid_elements)
def fill_grid(self, padding=1.0, rows=5, columns=5, grid_elements=None):
"""
This method creates elements (canvases) inside of the grid and links to them
:param grid_elements: the particular layout for the canvases
:param rows: the number of rows to create
:param columns: the number of columns to create
"""
one_width = (self.width * padding) / columns
one_height = (self.height * padding) / rows
for element in grid_elements:
<|code_end|>
, predict the immediate next line with the help of imports:
from Interface.GridElements import GridElement, FormGridElement
from Tkinter import *
from ttk import *
import abc
and context (classes, functions, sometimes code) from other files:
# Path: Interface/GridElements.py
# class GridElement():
# """
# This class contains data for grid elements
# """
# __metaclass__ = abc.ABCMeta
#
# @abc.abstractmethod
# def __init__(self, x, y, x_length, y_length, colour="black"):
# self.x, self.y, self.colour = x, y, colour
# self.x_length, self.y_length = x_length, y_length
# self.canvas = None
#
# @abc.abstractmethod
# def add_elements(self):
# pass
#
# class FormGridElement(GridElement):
# """
# This class contains data for grid elements
# """
# def __init__(self, x, y, x_length, y_length, colour="black"):
# GridElement.__init__(self, x, y, x_length, y_length, colour)
#
# def add_elements(self):
# assert isinstance(self.canvas, Canvas)
# button = Button(self.canvas, text="Quit")
# label = Label(self.canvas, text="This is a label")
# window_one = self.canvas.create_window(10, 10, anchor=NW, window=label)
# window_two = self.canvas.create_window(100, 10, anchor=NW, window=button)
. Output only the next line. | assert isinstance(element, GridElement) |
Predict the next line for this snippet: <|code_start|> :param columns: the number of columns to create
"""
one_width = (self.width * padding) / columns
one_height = (self.height * padding) / rows
for element in grid_elements:
assert isinstance(element, GridElement)
canvas_width = one_width * element.x_length
canvas_height = one_height * element.y_length
element.canvas = Canvas(self.content_grid, width=canvas_width, height=canvas_height)
element.canvas.configure(bg=element.colour)
element.canvas.grid(column=element.x, row=element.y, columns=element.x_length, rows=element.y_length)
def add_tabs(self, tabs=3):
"""
This is a method for adding tabs to the window
:param tabs: the number of tabs to add to the window
"""
note_book = Notebook(self.parent)
for i in range(tabs):
tab = Frame()
note_book.add(tab, text="Hello World!")
note_book.pack()
def main():
root = Tk()
top_level = root.winfo_toplevel()
top_level.wm_state('zoomed')
comp_finance_window = Window(root, "Computational Finance Package")
<|code_end|>
with the help of current file imports:
from Interface.GridElements import GridElement, FormGridElement
from Tkinter import *
from ttk import *
import abc
and context from other files:
# Path: Interface/GridElements.py
# class GridElement():
# """
# This class contains data for grid elements
# """
# __metaclass__ = abc.ABCMeta
#
# @abc.abstractmethod
# def __init__(self, x, y, x_length, y_length, colour="black"):
# self.x, self.y, self.colour = x, y, colour
# self.x_length, self.y_length = x_length, y_length
# self.canvas = None
#
# @abc.abstractmethod
# def add_elements(self):
# pass
#
# class FormGridElement(GridElement):
# """
# This class contains data for grid elements
# """
# def __init__(self, x, y, x_length, y_length, colour="black"):
# GridElement.__init__(self, x, y, x_length, y_length, colour)
#
# def add_elements(self):
# assert isinstance(self.canvas, Canvas)
# button = Button(self.canvas, text="Quit")
# label = Label(self.canvas, text="This is a label")
# window_one = self.canvas.create_window(10, 10, anchor=NW, window=label)
# window_two = self.canvas.create_window(100, 10, anchor=NW, window=button)
, which may contain function names, class names, or code. Output only the next line. | grid_elements = [FormGridElement(0, 0, 2, 1, 'grey'), |
Based on the snippet: <|code_start|>__author__ = 'stuartreid'
def investing_example():
"""
This method creates a set of regression analyses based on fundamental trading (revenues)
"""
# b: blue, g: green, r: red, c: cyan, m: magenta, y: yellow, k: black, w: white
statsmodels_args_inv = RegressionSettings(2, False)
quandl_args_inv = QuandlSettings(5, 1, "yearly")
<|code_end|>
, predict the immediate next line with the help of imports:
from LinearRegression import RegressionAnalysis
from LinearRegression import RegressionSettings
from Data.QuandlDownloader import QuandlDownloader
from Data.QuandlDownloader import QuandlSettings
from Visualization import SimplePlotter
and context (classes, functions, sometimes code) from other files:
# Path: Data/QuandlDownloader.py
# class QuandlDownloader():
# """
# This class contains the logic for downloading and transforming Quandl data sets. It receives,
# * A QuandlSetting object as a parameter which determines how to download the data set
# * The name of a Quandl data set to be downloaded
# """
#
# def __init__(self, quandl_data_set_name, quandl_settings=QuandlSettings(500, 1)):
# """
# Initialization method for the Quandl Downloader object
# :param quandl_data_set_name: this is a string which contains the name of the data set to download
# :param quandl_settings: this is a setting object
# """
# self.fetched = False
# self.quandl_data_set = np.array
# self.quandl_settings = quandl_settings
# self.quandl_data_set_name = quandl_data_set_name
# self.quandl_dates, self.quandl_data = self.get_quandl_data()
# pass
#
# def get_quandl_data(self):
# """
# This method retrieves the quandl data set given the settings specified in the quandl_settings object. For more
# information about these settings see documentation from the QuandlSettings class
# """
# if not self.fetched:
# self.quandl_data_set = Quandl.get(self.quandl_data_set_name,
# returns="numpy",
# rows=self.quandl_settings.rows,
# sort_order=self.quandl_settings.order,
# collapse=self.quandl_settings.frequency,
# transformation=self.quandl_settings.transformation,)
# self.quandl_dates = np.arange(1, self.quandl_settings.rows + 1, 1)
# self.quandl_data = zip(*self.quandl_data_set)[self.quandl_settings.column]
# self.quandl_data = self.quandl_data[::-1]
# self.fetched = True
# return self.quandl_dates, self.quandl_data
#
# Path: Data/QuandlDownloader.py
# class QuandlSettings():
# """
# This class contains settings for the quandl integration package, settings include,
# """
#
# def __init__(self, rows, column, frequency="weekly", transformation="normalize", order="desc"):
# """
# This initialization method constructs a new QuandlSettings object
# :param rows: the number of rows of data to download from Quandl
# :param column: which column of the downloaded data to extract
# :param frequency: daily, weekly, monthly, quarterly, yearly
# :param transformation: normalize, rdiff, etc.
# :param order: which order to sort into w.r.t date
# """
# self.rows = rows
# self.column = column
# self.frequency = frequency
# self.transformation = transformation
# self.order = order
# pass
#
# Path: Visualization/SimplePlotter.py
# def plot_regression_line(regression_analyses):
. Output only the next line. | regressions_inv = [RegressionAnalysis(QuandlDownloader("DMDRN/GOOG_REV_LAST", quandl_args_inv), |
Given the code snippet: <|code_start|>__author__ = 'stuartreid'
def investing_example():
"""
This method creates a set of regression analyses based on fundamental trading (revenues)
"""
# b: blue, g: green, r: red, c: cyan, m: magenta, y: yellow, k: black, w: white
statsmodels_args_inv = RegressionSettings(2, False)
<|code_end|>
, generate the next line using the imports in this file:
from LinearRegression import RegressionAnalysis
from LinearRegression import RegressionSettings
from Data.QuandlDownloader import QuandlDownloader
from Data.QuandlDownloader import QuandlSettings
from Visualization import SimplePlotter
and context (functions, classes, or occasionally code) from other files:
# Path: Data/QuandlDownloader.py
# class QuandlDownloader():
# """
# This class contains the logic for downloading and transforming Quandl data sets. It receives,
# * A QuandlSetting object as a parameter which determines how to download the data set
# * The name of a Quandl data set to be downloaded
# """
#
# def __init__(self, quandl_data_set_name, quandl_settings=QuandlSettings(500, 1)):
# """
# Initialization method for the Quandl Downloader object
# :param quandl_data_set_name: this is a string which contains the name of the data set to download
# :param quandl_settings: this is a setting object
# """
# self.fetched = False
# self.quandl_data_set = np.array
# self.quandl_settings = quandl_settings
# self.quandl_data_set_name = quandl_data_set_name
# self.quandl_dates, self.quandl_data = self.get_quandl_data()
# pass
#
# def get_quandl_data(self):
# """
# This method retrieves the quandl data set given the settings specified in the quandl_settings object. For more
# information about these settings see documentation from the QuandlSettings class
# """
# if not self.fetched:
# self.quandl_data_set = Quandl.get(self.quandl_data_set_name,
# returns="numpy",
# rows=self.quandl_settings.rows,
# sort_order=self.quandl_settings.order,
# collapse=self.quandl_settings.frequency,
# transformation=self.quandl_settings.transformation,)
# self.quandl_dates = np.arange(1, self.quandl_settings.rows + 1, 1)
# self.quandl_data = zip(*self.quandl_data_set)[self.quandl_settings.column]
# self.quandl_data = self.quandl_data[::-1]
# self.fetched = True
# return self.quandl_dates, self.quandl_data
#
# Path: Data/QuandlDownloader.py
# class QuandlSettings():
# """
# This class contains settings for the quandl integration package, settings include,
# """
#
# def __init__(self, rows, column, frequency="weekly", transformation="normalize", order="desc"):
# """
# This initialization method constructs a new QuandlSettings object
# :param rows: the number of rows of data to download from Quandl
# :param column: which column of the downloaded data to extract
# :param frequency: daily, weekly, monthly, quarterly, yearly
# :param transformation: normalize, rdiff, etc.
# :param order: which order to sort into w.r.t date
# """
# self.rows = rows
# self.column = column
# self.frequency = frequency
# self.transformation = transformation
# self.order = order
# pass
#
# Path: Visualization/SimplePlotter.py
# def plot_regression_line(regression_analyses):
. Output only the next line. | quandl_args_inv = QuandlSettings(5, 1, "yearly") |
Here is a snippet: <|code_start|>__author__ = 'stuartreid'
def investing_example():
"""
This method creates a set of regression analyses based on fundamental trading (revenues)
"""
# b: blue, g: green, r: red, c: cyan, m: magenta, y: yellow, k: black, w: white
statsmodels_args_inv = RegressionSettings(2, False)
quandl_args_inv = QuandlSettings(5, 1, "yearly")
regressions_inv = [RegressionAnalysis(QuandlDownloader("DMDRN/GOOG_REV_LAST", quandl_args_inv),
statsmodels_args_inv, 'b'),
RegressionAnalysis(QuandlDownloader("DMDRN/YHOO_REV_LAST", quandl_args_inv),
statsmodels_args_inv, 'g'),
RegressionAnalysis(QuandlDownloader("DMDRN/AAPL_REV_LAST", quandl_args_inv),
statsmodels_args_inv, 'k')]
<|code_end|>
. Write the next line using the current file imports:
from LinearRegression import RegressionAnalysis
from LinearRegression import RegressionSettings
from Data.QuandlDownloader import QuandlDownloader
from Data.QuandlDownloader import QuandlSettings
from Visualization import SimplePlotter
and context from other files:
# Path: Data/QuandlDownloader.py
# class QuandlDownloader():
# """
# This class contains the logic for downloading and transforming Quandl data sets. It receives,
# * A QuandlSetting object as a parameter which determines how to download the data set
# * The name of a Quandl data set to be downloaded
# """
#
# def __init__(self, quandl_data_set_name, quandl_settings=QuandlSettings(500, 1)):
# """
# Initialization method for the Quandl Downloader object
# :param quandl_data_set_name: this is a string which contains the name of the data set to download
# :param quandl_settings: this is a setting object
# """
# self.fetched = False
# self.quandl_data_set = np.array
# self.quandl_settings = quandl_settings
# self.quandl_data_set_name = quandl_data_set_name
# self.quandl_dates, self.quandl_data = self.get_quandl_data()
# pass
#
# def get_quandl_data(self):
# """
# This method retrieves the quandl data set given the settings specified in the quandl_settings object. For more
# information about these settings see documentation from the QuandlSettings class
# """
# if not self.fetched:
# self.quandl_data_set = Quandl.get(self.quandl_data_set_name,
# returns="numpy",
# rows=self.quandl_settings.rows,
# sort_order=self.quandl_settings.order,
# collapse=self.quandl_settings.frequency,
# transformation=self.quandl_settings.transformation,)
# self.quandl_dates = np.arange(1, self.quandl_settings.rows + 1, 1)
# self.quandl_data = zip(*self.quandl_data_set)[self.quandl_settings.column]
# self.quandl_data = self.quandl_data[::-1]
# self.fetched = True
# return self.quandl_dates, self.quandl_data
#
# Path: Data/QuandlDownloader.py
# class QuandlSettings():
# """
# This class contains settings for the quandl integration package, settings include,
# """
#
# def __init__(self, rows, column, frequency="weekly", transformation="normalize", order="desc"):
# """
# This initialization method constructs a new QuandlSettings object
# :param rows: the number of rows of data to download from Quandl
# :param column: which column of the downloaded data to extract
# :param frequency: daily, weekly, monthly, quarterly, yearly
# :param transformation: normalize, rdiff, etc.
# :param order: which order to sort into w.r.t date
# """
# self.rows = rows
# self.column = column
# self.frequency = frequency
# self.transformation = transformation
# self.order = order
# pass
#
# Path: Visualization/SimplePlotter.py
# def plot_regression_line(regression_analyses):
, which may include functions, classes, or code. Output only the next line. | SimplePlotter.plot_regression_line(regressions_inv) |
Here is a snippet: <|code_start|>__author__ = 'Stuart Gordon Reid'
__email__ = 'stuartgordonreid@gmail.com'
__website__ = 'http://www.stuartreid.co.za'
"""
File description
"""
<|code_end|>
. Write the next line using the current file imports:
from Optimizers.Optimizer import Optimizer
and context from other files:
# Path: Optimizers/Optimizer.py
# class Optimizer(object):
# __metaclass__ = abc.ABCMeta
#
# @abc.abstractmethod
# def __init__(self, problem, parameters):
# """
# This method initialized the Optimizer with an objective function and a set of parameters
# :param problem: this is the problem being optimized
# :param parameters: set of algorithm control parameters
# """
# self.problem = problem
# self.parameters = parameters
# return
#
# @abc.abstractmethod
# def optimize(self, iterations=1000, stopping=True):
# """
# This is the generic optimization method to be overloaded by each optimizer
# :param stopping: whether or not the algorithm should use early stopping
# :param iterations: the number of iterations to optimize for, default is 1000
# """
# return
#
# def fitness(self, candidate):
# """
# This is the generic optimization method to be overloaded by each optimizer
# :param candidate:
# """
# assert isinstance(self.problem, Problems.Function)
# assert isinstance(candidate, Solution)
# return self.problem.evaluate(candidate)
, which may include functions, classes, or code. Output only the next line. | class SimulatedAnnealing(Optimizer): |
Given the following code snippet before the placeholder: <|code_start|>
FILEONLY = 'fileonly'
class Artefacts(FunctionType):
"""
Will return a list of artefacts (relative path) inside directories starting with !
If fileonly == True is passed in then only filenames will be listed
"""
def __init__(self, obj, config=None):
_config = {FILEONLY: False}
if config is not None:
_configlist = [c.strip().lower() for c in config.split('=')]
if len(_configlist) == 2 and _configlist[0] == FILEONLY:
_config[FILEONLY] = strtobool(_configlist[1])
else:
raise ValueError('Artefact method plugin (used in user defined class %s) accepts a single argument of either '
'"fileonly = True" or "fileonly = False". By default fileonly mode is False '
<|code_end|>
, predict the next line using imports from the current file:
from gtool.core.types.core import FunctionType
from gtool.core.utils.misc import striptoclassname
from distutils.util import strtobool
import os
and context including class names, function names, and sometimes code from other files:
# Path: gtool/core/types/core.py
# class FunctionType(object):
# """
# Use as the base class for method plugins
# """
#
# @abstractmethod
# def __init__(self, obj, config=str(), defer=False):
# """
# Based class for method plugins
#
# :param obj: the DynamicType Object that the function will operate one
# :param config: instructions on how the plugin should work. May be a list, dict or string
# """
#
# self.targetobject = obj
# self.config = config
# self.computable = False
# self.__result__ = None
# self.__context__ = obj.__context__
# self.__defer__ = defer
#
# # TODO implement an attribute getter for method plugins
# def __getname__(self, attrname, nativetypes = [], singletononly=False):
# raise NotImplemented
#
# @abstractmethod
# def compute(self):
# """
# processes any instructions in config, determine if required input exists.
# If required input exists, sets self.computable to true, computes and stores result
# :return: None
# """
# # process config or do something
#
# if True: #determine if result can be computed
# self.computable = True
#
# if self.computable:
# self.__result__ = 'some result' #set result
# raise NotImplemented('compute must be overridden')
# else:
# pass
# # if not computable don't set result
# #TODO look at returning True or False is compute completes
#
# @property
# def context(self):
# return self.__context__
#
# def result(self, force=False):
#
# if not self.__defer__ or force:
# self.compute() #TODO look at making this an if statement
# return self.__result__
# else:
# raise NotComputed('Computation deferred')
#
# def __repr__(self):
# return '<%s>:()' % (self.__class__, self.config)
#
# def __str__(self):
# self.compute() #TODO look at making this an if statement
# return self.__result__
#
# Path: gtool/core/utils/misc.py
# def striptoclassname(fullclassstring):
# return '{0}'.format(fullclassstring)[7:-2].split('.')[-1]
. Output only the next line. | 'and does not need to be specified' % striptoclassname(type(obj))) |
Next line prediction: <|code_start|> return metaDef
expr = p.OneOrMore(p.Group(aggregatorIdParser() + p.OneOrMore(aggregatorMetas())))
match = expr.parseString(configstring)
_retlist = []
for m in match:
_retdict = {}
_retdict['id'] = m[0]
for k, v in m.items():
_retdict[k] = v
_retlist.append(_retdict)
return _retlist
def parseSelector(selectorstring):
# *select = @attr1 | /tf1/@attr | @attr1//objtype
"""
def enumtype(*args,**kwargs): #s, l, t, selectortype=None):
print(args)
selectortype = kwargs['selectortype']
if selectortype is None or not isinstance(selectortype, str):
raise ValueError('enumtype requires a selectortype string but got a', type(selectortype))
return selectortype
"""
def attrtype():
<|code_end|>
. Use current file imports:
(import pyparsing as p
from gtool.core.types.core import AttrSelector, FullPathSelector, AttrByObjectSelector)
and context including class names, function names, or small code snippets from other files:
# Path: gtool/core/types/core.py
# class AttrSelector(Selector):
#
# def __init__(self):
# self.__method__ = searchByAttrib
#
# class FullPathSelector(Selector):
#
# def __init__(self):
# self.__method__ = getObjectByUri
#
# class AttrByObjectSelector(Selector):
#
# def __init__(self):
# self.__method__ = searchByAttribAndObjectType
. Output only the next line. | return AttrSelector() # 'ATTRTYPE' |
Continue the code snippet: <|code_start|>
match = expr.parseString(configstring)
_retlist = []
for m in match:
_retdict = {}
_retdict['id'] = m[0]
for k, v in m.items():
_retdict[k] = v
_retlist.append(_retdict)
return _retlist
def parseSelector(selectorstring):
# *select = @attr1 | /tf1/@attr | @attr1//objtype
"""
def enumtype(*args,**kwargs): #s, l, t, selectortype=None):
print(args)
selectortype = kwargs['selectortype']
if selectortype is None or not isinstance(selectortype, str):
raise ValueError('enumtype requires a selectortype string but got a', type(selectortype))
return selectortype
"""
def attrtype():
return AttrSelector() # 'ATTRTYPE'
def fullpathtype():
<|code_end|>
. Use current file imports:
import pyparsing as p
from gtool.core.types.core import AttrSelector, FullPathSelector, AttrByObjectSelector
and context (classes, functions, or code) from other files:
# Path: gtool/core/types/core.py
# class AttrSelector(Selector):
#
# def __init__(self):
# self.__method__ = searchByAttrib
#
# class FullPathSelector(Selector):
#
# def __init__(self):
# self.__method__ = getObjectByUri
#
# class AttrByObjectSelector(Selector):
#
# def __init__(self):
# self.__method__ = searchByAttribAndObjectType
. Output only the next line. | return FullPathSelector() #'FULLPATH' |
Based on the snippet: <|code_start|> _retlist = []
for m in match:
_retdict = {}
_retdict['id'] = m[0]
for k, v in m.items():
_retdict[k] = v
_retlist.append(_retdict)
return _retlist
def parseSelector(selectorstring):
# *select = @attr1 | /tf1/@attr | @attr1//objtype
"""
def enumtype(*args,**kwargs): #s, l, t, selectortype=None):
print(args)
selectortype = kwargs['selectortype']
if selectortype is None or not isinstance(selectortype, str):
raise ValueError('enumtype requires a selectortype string but got a', type(selectortype))
return selectortype
"""
def attrtype():
return AttrSelector() # 'ATTRTYPE'
def fullpathtype():
return FullPathSelector() #'FULLPATH'
def attrbyobjtype():
<|code_end|>
, predict the immediate next line with the help of imports:
import pyparsing as p
from gtool.core.types.core import AttrSelector, FullPathSelector, AttrByObjectSelector
and context (classes, functions, sometimes code) from other files:
# Path: gtool/core/types/core.py
# class AttrSelector(Selector):
#
# def __init__(self):
# self.__method__ = searchByAttrib
#
# class FullPathSelector(Selector):
#
# def __init__(self):
# self.__method__ = getObjectByUri
#
# class AttrByObjectSelector(Selector):
#
# def __init__(self):
# self.__method__ = searchByAttribAndObjectType
. Output only the next line. | return AttrByObjectSelector() #'ATTRBYOBJECT' |
Predict the next line for this snippet: <|code_start|>
class Slice(FunctionType):
"""
Truncates a single string. Will return None if the attributes in the config string is missing.
Does not work with multiple value attributes or attributes that are dynamic objects.
Example strings are:
'@text1[:5] returns the first 5 characters of the string'
'@text2[1:-1] returns the string without the first and last character'
'@text3[1:4] returns the string without the first character stopping at the 4th'
'@text4[1:] returns the string without the first character'
"""
def __init__(self, obj, config=str()):
self.stringvalue = ""
self.slicestart = None
self.sliceend = None
super(Slice, self).__init__(obj, config=config)
if self.config is None or len(self.config) < 1 or not isinstance(self.config, str):
raise ValueError('Slice plugin function requires a attribute and string slice be specified such as "@state[1:3]"')
def compute(self):
def slicer(stringvalue, start=None, end=None):
if not isinstance(stringvalue, str):
raise ValueError('Slice plugin only works on string '
'or string like attributes but got '
<|code_end|>
with the help of current file imports:
from gtool.core.types.core import FunctionType
from gtool.core.utils.misc import striptoclassname
import pyparsing as p
and context from other files:
# Path: gtool/core/types/core.py
# class FunctionType(object):
# """
# Use as the base class for method plugins
# """
#
# @abstractmethod
# def __init__(self, obj, config=str(), defer=False):
# """
# Based class for method plugins
#
# :param obj: the DynamicType Object that the function will operate one
# :param config: instructions on how the plugin should work. May be a list, dict or string
# """
#
# self.targetobject = obj
# self.config = config
# self.computable = False
# self.__result__ = None
# self.__context__ = obj.__context__
# self.__defer__ = defer
#
# # TODO implement an attribute getter for method plugins
# def __getname__(self, attrname, nativetypes = [], singletononly=False):
# raise NotImplemented
#
# @abstractmethod
# def compute(self):
# """
# processes any instructions in config, determine if required input exists.
# If required input exists, sets self.computable to true, computes and stores result
# :return: None
# """
# # process config or do something
#
# if True: #determine if result can be computed
# self.computable = True
#
# if self.computable:
# self.__result__ = 'some result' #set result
# raise NotImplemented('compute must be overridden')
# else:
# pass
# # if not computable don't set result
# #TODO look at returning True or False is compute completes
#
# @property
# def context(self):
# return self.__context__
#
# def result(self, force=False):
#
# if not self.__defer__ or force:
# self.compute() #TODO look at making this an if statement
# return self.__result__
# else:
# raise NotComputed('Computation deferred')
#
# def __repr__(self):
# return '<%s>:()' % (self.__class__, self.config)
#
# def __str__(self):
# self.compute() #TODO look at making this an if statement
# return self.__result__
#
# Path: gtool/core/utils/misc.py
# def striptoclassname(fullclassstring):
# return '{0}'.format(fullclassstring)[7:-2].split('.')[-1]
, which may contain function names, class names, or code. Output only the next line. | 'a %s instead' % striptoclassname(type(self.targetobject))) |
Given snippet: <|code_start|>
if self.config is None or len(self.config) < 1 or not isinstance(self.config, str):
raise ValueError('Cvssv2 plugin function requires an attribute be specified such as "@vector"')
def compute(self):
def getname(obj, name):
_val = None
if hasattr(obj, name):
_val = getattr(obj, name, None)
if _val is None:
return _val
# handling for values from a method
if isinstance(_val, str):
return _val
try:
if _val.isdynamic:
raise ValueError('Cvssv2 plugin cannot process %s because it contains a dynamic class' % name)
except AttributeError:
raise TypeError('Expected an attribute but got a %s' % type(_val))
if _val.issingleton():
_ret = '%s' % _val[0].raw()
else:
raise ValueError('Cvssv2 method plugin specified in user defined class %s '
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from gtool.core.types.core import FunctionType
from gtool.core.utils.misc import striptoclassname
from cvsslib import cvss2, calculate_vector
import pyparsing as p
and context:
# Path: gtool/core/types/core.py
# class FunctionType(object):
# """
# Use as the base class for method plugins
# """
#
# @abstractmethod
# def __init__(self, obj, config=str(), defer=False):
# """
# Based class for method plugins
#
# :param obj: the DynamicType Object that the function will operate one
# :param config: instructions on how the plugin should work. May be a list, dict or string
# """
#
# self.targetobject = obj
# self.config = config
# self.computable = False
# self.__result__ = None
# self.__context__ = obj.__context__
# self.__defer__ = defer
#
# # TODO implement an attribute getter for method plugins
# def __getname__(self, attrname, nativetypes = [], singletononly=False):
# raise NotImplemented
#
# @abstractmethod
# def compute(self):
# """
# processes any instructions in config, determine if required input exists.
# If required input exists, sets self.computable to true, computes and stores result
# :return: None
# """
# # process config or do something
#
# if True: #determine if result can be computed
# self.computable = True
#
# if self.computable:
# self.__result__ = 'some result' #set result
# raise NotImplemented('compute must be overridden')
# else:
# pass
# # if not computable don't set result
# #TODO look at returning True or False is compute completes
#
# @property
# def context(self):
# return self.__context__
#
# def result(self, force=False):
#
# if not self.__defer__ or force:
# self.compute() #TODO look at making this an if statement
# return self.__result__
# else:
# raise NotComputed('Computation deferred')
#
# def __repr__(self):
# return '<%s>:()' % (self.__class__, self.config)
#
# def __str__(self):
# self.compute() #TODO look at making this an if statement
# return self.__result__
#
# Path: gtool/core/utils/misc.py
# def striptoclassname(fullclassstring):
# return '{0}'.format(fullclassstring)[7:-2].split('.')[-1]
which might include code, classes, or functions. Output only the next line. | 'only works on singleton attributes' % striptoclassname(type(self.targetobject))) |
Predict the next line after this snippet: <|code_start|> return trailers
def get_movie_data(tmdb_id, lang):
tmdb = get_tmdb(lang=lang)
return tmdb.Movies(tmdb_id)
movie_data_en = get_movie_data(tmdb_id, "en")
movie_info_en = movie_data_en.info()
# We have to get all info in english first before we switch to russian or everything breaks.
trailers_en = get_trailers(movie_data_en)
movie_data_ru = get_movie_data(tmdb_id, "ru")
movie_info_ru = movie_data_ru.info()
trailers_ru = get_trailers(movie_data_ru)
imdb_id = movie_info_en["imdb_id"]
if imdb_id:
return {
"tmdb_id": tmdb_id,
"imdb_id": imdb_id,
"release_date": get_release_date(movie_info_en["release_date"]),
"title_original": movie_info_en["original_title"],
"poster_ru": get_poster_from_tmdb(movie_info_ru["poster_path"]),
"poster_en": get_poster_from_tmdb(movie_info_en["poster_path"]),
"homepage": movie_info_en["homepage"],
"trailers_en": trailers_en,
"trailers_ru": trailers_ru,
"title_en": movie_info_en["title"],
"title_ru": movie_info_ru["title"],
"description_en": movie_info_en["overview"],
"description_ru": movie_info_ru["overview"],
}
<|code_end|>
using the current file's imports:
from datetime import datetime
from operator import itemgetter
from babel.dates import format_date
from django.conf import settings
from .exceptions import MovieNotInDb
from .models import get_poster_url
import tmdbsimple
and any relevant context from other files:
# Path: src/moviesapp/exceptions.py
# class MovieNotInDb(Exception):
# """
# Movie is not in DB.
#
# It means the movie does not have an IMDB id.
# """
#
# Path: src/moviesapp/models.py
# def get_poster_url(size, poster):
# if size == "small":
# poster_size = settings.POSTER_SIZE_SMALL
# no_image_url = settings.NO_POSTER_SMALL_IMAGE_URL
# elif size == "normal":
# poster_size = settings.POSTER_SIZE_NORMAL
# no_image_url = settings.NO_POSTER_NORMAL_IMAGE_URL
# elif size == "big":
# poster_size = settings.POSTER_SIZE_BIG
# no_image_url = None # is not used anywhere
# if poster is not None:
# return settings.POSTER_BASE_URL + poster_size + "/" + poster
# return no_image_url
. Output only the next line. | raise MovieNotInDb(tmdb_id) |
Predict the next line after this snippet: <|code_start|> if search_type == "actor":
movies = filter_movies_only(person.cast)
else:
movies = filter_movies_only(person.crew)
movies = [m for m in movies if m["job"] == "Director"]
return movies
movies_data = get_data(query, search_type)
movies = []
i = 0
if movies_data:
user_movies_tmdb_ids = user.get_records().values_list("movie__tmdb_id", flat=True)
for movie in movies_data:
tmdb_id = movie["id"]
i += 1
if i > settings.MAX_RESULTS:
break
if tmdb_id in user_movies_tmdb_ids:
continue
poster = get_poster_from_tmdb(movie["poster_path"])
# Skip unpopular movies if this option is enabled.
if search_type == "movie" and options["popularOnly"] and not is_popular_movie(movie):
continue
movie = {
"id": tmdb_id,
"tmdbLink": f"{settings.TMDB_MOVIE_BASE_URL}{tmdb_id}",
"elementId": f"movie{tmdb_id}",
"releaseDate": movie.get("release_date"),
"title": movie["title"],
<|code_end|>
using the current file's imports:
from datetime import datetime
from operator import itemgetter
from babel.dates import format_date
from django.conf import settings
from .exceptions import MovieNotInDb
from .models import get_poster_url
import tmdbsimple
and any relevant context from other files:
# Path: src/moviesapp/exceptions.py
# class MovieNotInDb(Exception):
# """
# Movie is not in DB.
#
# It means the movie does not have an IMDB id.
# """
#
# Path: src/moviesapp/models.py
# def get_poster_url(size, poster):
# if size == "small":
# poster_size = settings.POSTER_SIZE_SMALL
# no_image_url = settings.NO_POSTER_SMALL_IMAGE_URL
# elif size == "normal":
# poster_size = settings.POSTER_SIZE_NORMAL
# no_image_url = settings.NO_POSTER_NORMAL_IMAGE_URL
# elif size == "big":
# poster_size = settings.POSTER_SIZE_BIG
# no_image_url = None # is not used anywhere
# if poster is not None:
# return settings.POSTER_BASE_URL + poster_size + "/" + poster
# return no_image_url
. Output only the next line. | "poster": get_poster_url("small", poster), |
Continue the code snippet: <|code_start|>
class SearchView(TemplateAnonymousView):
template_name = "search.html"
class SearchMovieView(AjaxAnonymousView):
def get(self, request):
AVAILABLE_SEARCH_TYPES = [
"actor",
"movie",
"director",
]
try:
GET = request.GET
query = GET["query"]
options = json.loads(GET["options"])
type_ = GET["type"]
if type_ not in AVAILABLE_SEARCH_TYPES:
raise NotAvailableSearchType
except (KeyError, NotAvailableSearchType):
return self.render_bad_request_response()
movies = get_movies_from_tmdb(query, type_, options, request.user, self.request.LANGUAGE_CODE)
return self.success(movies=movies)
<|code_end|>
. Use current file imports:
import json
from sentry_sdk import capture_exception
from moviesapp.exceptions import MovieNotInDb, NotAvailableSearchType
from moviesapp.models import Movie
from moviesapp.tmdb import get_movies_from_tmdb
from moviesapp.utils import add_movie_to_db
from .mixins import AjaxAnonymousView, AjaxView, TemplateAnonymousView
from .utils import add_movie_to_list
and context (classes, functions, or code) from other files:
# Path: src/moviesapp/views/mixins.py
# class AjaxAnonymousView(JsonRequestResponseMixin, View):
# def success(self, **kwargs):
# response = {"status": "success"}
# response.update(kwargs)
# return self.render_json_response(response)
#
# class AjaxView(LoginRequiredMixin, AjaxAnonymousView):
# raise_exception = True
#
# class TemplateAnonymousView(TemplateViewOriginal):
# pass
#
# Path: src/moviesapp/views/utils.py
# def add_movie_to_list(movie_id, list_id, user):
# record = user.get_records().filter(movie_id=movie_id)
# if record.exists():
# record = record[0]
# if record.list_id != list_id:
# ActionRecord(action_id=2, user=user, movie_id=movie_id, list_id=list_id).save()
# record.list_id = list_id
# record.date = datetime.today()
# record.save()
# else:
# record = Record(movie_id=movie_id, list_id=list_id, user=user)
# record.save()
# ActionRecord(action_id=1, user=user, movie_id=movie_id, list_id=list_id).save()
. Output only the next line. | class AddToListFromDbView(AjaxView): |
Continue the code snippet: <|code_start|> options = json.loads(GET["options"])
type_ = GET["type"]
if type_ not in AVAILABLE_SEARCH_TYPES:
raise NotAvailableSearchType
except (KeyError, NotAvailableSearchType):
return self.render_bad_request_response()
movies = get_movies_from_tmdb(query, type_, options, request.user, self.request.LANGUAGE_CODE)
return self.success(movies=movies)
class AddToListFromDbView(AjaxView):
@staticmethod
def _get_movie_id(tmdb_id):
"""Return movie id or None if movie is not found."""
try:
movie = Movie.objects.get(tmdb_id=tmdb_id)
return movie.id
except Movie.DoesNotExist:
return None
@staticmethod
def _add_to_list_from_db(movie_id, tmdb_id, list_id, user):
"""Return True on success and None of failure."""
# If we don't find the movie in the db we add it to the database.
if movie_id is None:
try:
movie_id = add_movie_to_db(tmdb_id)
except MovieNotInDb as e:
capture_exception(e)
return None
<|code_end|>
. Use current file imports:
import json
from sentry_sdk import capture_exception
from moviesapp.exceptions import MovieNotInDb, NotAvailableSearchType
from moviesapp.models import Movie
from moviesapp.tmdb import get_movies_from_tmdb
from moviesapp.utils import add_movie_to_db
from .mixins import AjaxAnonymousView, AjaxView, TemplateAnonymousView
from .utils import add_movie_to_list
and context (classes, functions, or code) from other files:
# Path: src/moviesapp/views/mixins.py
# class AjaxAnonymousView(JsonRequestResponseMixin, View):
# def success(self, **kwargs):
# response = {"status": "success"}
# response.update(kwargs)
# return self.render_json_response(response)
#
# class AjaxView(LoginRequiredMixin, AjaxAnonymousView):
# raise_exception = True
#
# class TemplateAnonymousView(TemplateViewOriginal):
# pass
#
# Path: src/moviesapp/views/utils.py
# def add_movie_to_list(movie_id, list_id, user):
# record = user.get_records().filter(movie_id=movie_id)
# if record.exists():
# record = record[0]
# if record.list_id != list_id:
# ActionRecord(action_id=2, user=user, movie_id=movie_id, list_id=list_id).save()
# record.list_id = list_id
# record.date = datetime.today()
# record.save()
# else:
# record = Record(movie_id=movie_id, list_id=list_id, user=user)
# record.save()
# ActionRecord(action_id=1, user=user, movie_id=movie_id, list_id=list_id).save()
. Output only the next line. | add_movie_to_list(movie_id, list_id, user) |
Given the following code snippet before the placeholder: <|code_start|>
def logout_view(request):
logout(request)
return redirect("/")
@method_decorator(login_required, name="dispatch")
class PreferencesView(FormView):
template_name = "user/preferences.html"
form_class = UserForm
def get_form_kwargs(self):
result = super().get_form_kwargs()
result["instance"] = self.request.user
return result
def get_success_url(self):
return reverse("preferences")
def form_valid(self, form):
form.save()
return super().form_valid(form)
<|code_end|>
, predict the next line using imports from the current file:
from django.contrib.auth import logout
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect
from django.urls import reverse
from django.utils.decorators import method_decorator
from django.views.generic.edit import FormView
from moviesapp.forms import UserForm
from .mixins import TemplateAnonymousView
and context including class names, function names, and sometimes code from other files:
# Path: src/moviesapp/views/mixins.py
# class TemplateAnonymousView(TemplateViewOriginal):
# pass
. Output only the next line. | class LoginErrorView(TemplateAnonymousView): |
Next line prediction: <|code_start|>
@register(Movie)
class MovieTranslationOptions(TranslationOptions):
fields = ("title", "poster", "description", "trailers")
<|code_end|>
. Use current file imports:
(from modeltranslation.translator import TranslationOptions, register
from .models import Action, List, Movie)
and context including class names, function names, or small code snippets from other files:
# Path: src/moviesapp/models.py
# class Action(models.Model):
# ADDED_MOVIE = 1
# CHANGED_LIST = 2
# ADDED_RATING = 3
# ADDED_COMMENT = 4
# name = models.CharField(max_length=255)
#
# def __str__(self):
# return str(self.name)
#
# class List(models.Model):
# WATCHED = 1
# TO_WATCH = 2
# name = models.CharField(max_length=255)
# key_name = models.CharField(max_length=255)
#
# def __str__(self):
# return str(self.name)
#
# class Movie(models.Model):
# title = models.CharField(max_length=255)
# title_original = models.CharField(max_length=255)
# country = models.CharField(max_length=255, null=True, blank=True)
# description = models.TextField(null=True, blank=True)
# director = models.CharField(max_length=255, null=True, blank=True)
# writer = models.CharField(max_length=255, null=True, blank=True)
# genre = models.CharField(max_length=255, null=True, blank=True)
# actors = models.CharField(max_length=255, null=True, blank=True)
# imdb_id = models.CharField(max_length=15, unique=True, db_index=True)
# tmdb_id = models.IntegerField(unique=True)
# imdb_rating = models.DecimalField(max_digits=2, decimal_places=1, null=True)
# poster = models.CharField(max_length=255, null=True)
# release_date = models.DateField(null=True)
# runtime = models.TimeField(null=True, blank=True)
# homepage = models.URLField(null=True, blank=True)
# trailers = JSONField(null=True, blank=True)
#
# class Meta:
# ordering = ["pk"]
#
# def __str__(self):
# return str(self.title)
#
# def imdb_url(self):
# return settings.IMDB_BASE_URL + self.imdb_id + "/"
#
# def get_trailers(self):
# if self.trailers:
# return self.trailers
# return self.trailers_en
#
# def has_trailers(self):
# return bool(self.get_trailers())
#
# def _get_poster(self, size):
# return get_poster_url(size, self.poster)
#
# @property
# def poster_normal(self):
# return self._get_poster("normal")
#
# @property
# def poster_small(self):
# return self._get_poster("small")
#
# @property
# def poster_big(self):
# return self._get_poster("big")
#
# @property
# def id_title(self):
# return f"{self.pk} - {self}"
#
# def cli_string(self, last_movie_id):
# """
# Return string version for CLI.
#
# We need last_movie_id because we want to know how big is the number (in characters) to be able to make
# perfect formatting.
# We need to keep last_movie_id as a parameter because otherwise we hit the database every time we run the
# function.
# """
# MAX_CHARS = 40
# ENDING = ".."
# n = len(str(last_movie_id)) + 1
# id_format = f"{{0: < {n}}}"
# title = str(self)
# title = (title[:MAX_CHARS] + ENDING) if len(title) > MAX_CHARS else title
# id_ = id_format.format(self.pk)
# title_max_length = MAX_CHARS + len(ENDING)
# title_format = f"{{:{title_max_length}s}}"
# title = title_format.format(title) # pylint: disable=consider-using-f-string
# return f"{id_} - {title}"[1:]
. Output only the next line. | @register(Action) |
Next line prediction: <|code_start|>
@register(Movie)
class MovieTranslationOptions(TranslationOptions):
fields = ("title", "poster", "description", "trailers")
@register(Action)
class ActionTranslationOptions(TranslationOptions):
fields = ("name",)
<|code_end|>
. Use current file imports:
(from modeltranslation.translator import TranslationOptions, register
from .models import Action, List, Movie)
and context including class names, function names, or small code snippets from other files:
# Path: src/moviesapp/models.py
# class Action(models.Model):
# ADDED_MOVIE = 1
# CHANGED_LIST = 2
# ADDED_RATING = 3
# ADDED_COMMENT = 4
# name = models.CharField(max_length=255)
#
# def __str__(self):
# return str(self.name)
#
# class List(models.Model):
# WATCHED = 1
# TO_WATCH = 2
# name = models.CharField(max_length=255)
# key_name = models.CharField(max_length=255)
#
# def __str__(self):
# return str(self.name)
#
# class Movie(models.Model):
# title = models.CharField(max_length=255)
# title_original = models.CharField(max_length=255)
# country = models.CharField(max_length=255, null=True, blank=True)
# description = models.TextField(null=True, blank=True)
# director = models.CharField(max_length=255, null=True, blank=True)
# writer = models.CharField(max_length=255, null=True, blank=True)
# genre = models.CharField(max_length=255, null=True, blank=True)
# actors = models.CharField(max_length=255, null=True, blank=True)
# imdb_id = models.CharField(max_length=15, unique=True, db_index=True)
# tmdb_id = models.IntegerField(unique=True)
# imdb_rating = models.DecimalField(max_digits=2, decimal_places=1, null=True)
# poster = models.CharField(max_length=255, null=True)
# release_date = models.DateField(null=True)
# runtime = models.TimeField(null=True, blank=True)
# homepage = models.URLField(null=True, blank=True)
# trailers = JSONField(null=True, blank=True)
#
# class Meta:
# ordering = ["pk"]
#
# def __str__(self):
# return str(self.title)
#
# def imdb_url(self):
# return settings.IMDB_BASE_URL + self.imdb_id + "/"
#
# def get_trailers(self):
# if self.trailers:
# return self.trailers
# return self.trailers_en
#
# def has_trailers(self):
# return bool(self.get_trailers())
#
# def _get_poster(self, size):
# return get_poster_url(size, self.poster)
#
# @property
# def poster_normal(self):
# return self._get_poster("normal")
#
# @property
# def poster_small(self):
# return self._get_poster("small")
#
# @property
# def poster_big(self):
# return self._get_poster("big")
#
# @property
# def id_title(self):
# return f"{self.pk} - {self}"
#
# def cli_string(self, last_movie_id):
# """
# Return string version for CLI.
#
# We need last_movie_id because we want to know how big is the number (in characters) to be able to make
# perfect formatting.
# We need to keep last_movie_id as a parameter because otherwise we hit the database every time we run the
# function.
# """
# MAX_CHARS = 40
# ENDING = ".."
# n = len(str(last_movie_id)) + 1
# id_format = f"{{0: < {n}}}"
# title = str(self)
# title = (title[:MAX_CHARS] + ENDING) if len(title) > MAX_CHARS else title
# id_ = id_format.format(self.pk)
# title_max_length = MAX_CHARS + len(ENDING)
# title_format = f"{{:{title_max_length}s}}"
# title = title_format.format(title) # pylint: disable=consider-using-f-string
# return f"{id_} - {title}"[1:]
. Output only the next line. | @register(List) |
Given the code snippet: <|code_start|> ).save()
record.rating = rating
record.save()
return self.success()
class AddToListView(AjaxView):
def post(self, request, **kwargs):
try:
movie_id = int(kwargs["id"])
list_id = int(request.POST["listId"])
except (KeyError, ValueError):
return self.render_bad_request_response()
add_movie_to_list(movie_id, list_id, request.user)
return self.success()
class RemoveRecordView(AjaxView):
def delete(self, request, **kwargs):
try:
record_id = int(kwargs["id"])
except (KeyError, ValueError):
return self.render_bad_request_response()
try:
request.user.get_record(record_id).delete()
except Record.DoesNotExist as e:
raise Http404 from e
return self.success()
<|code_end|>
, generate the next line using the imports in this file:
import json
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.db.models import Q
from django.http import Http404
from moviesapp.models import Action, ActionRecord, List, Record, User
from .mixins import AjaxAnonymousView, AjaxView, TemplateAnonymousView, TemplateView
from .utils import add_movie_to_list, get_anothers_account, get_records, paginate, sort_by_rating
and context (functions, classes, or occasionally code) from other files:
# Path: src/moviesapp/views/mixins.py
# class AjaxAnonymousView(JsonRequestResponseMixin, View):
# def success(self, **kwargs):
# response = {"status": "success"}
# response.update(kwargs)
# return self.render_json_response(response)
#
# class AjaxView(LoginRequiredMixin, AjaxAnonymousView):
# raise_exception = True
#
# class TemplateAnonymousView(TemplateViewOriginal):
# pass
#
# class TemplateView(LoginRequiredMixin, TemplateViewOriginal):
# pass
#
# Path: src/moviesapp/views/utils.py
# def add_movie_to_list(movie_id, list_id, user):
# record = user.get_records().filter(movie_id=movie_id)
# if record.exists():
# record = record[0]
# if record.list_id != list_id:
# ActionRecord(action_id=2, user=user, movie_id=movie_id, list_id=list_id).save()
# record.list_id = list_id
# record.date = datetime.today()
# record.save()
# else:
# record = Record(movie_id=movie_id, list_id=list_id, user=user)
# record.save()
# ActionRecord(action_id=1, user=user, movie_id=movie_id, list_id=list_id).save()
#
# def get_anothers_account(username):
# if username:
# return get_object_or_404(User, username=username)
# return False
#
# def get_records(list_name, user, anothers_account):
# """Get records for certain user and list."""
# if anothers_account:
# user = anothers_account
# return user.get_records().filter(list__key_name=list_name).select_related("movie")
#
# def paginate(objects, page, objects_on_page):
# paginator = Paginator(objects, objects_on_page)
# try:
# objects = paginator.page(page)
# except PageNotAnInteger:
# # If page is not an integer, deliver first page.
# objects = paginator.page(1)
# except EmptyPage:
# # If page is out of range (e.g. 9999), deliver last page of results.
# objects = paginator.page(paginator.num_pages)
# return objects
#
# def sort_by_rating(records, username, list_name):
# if not username and list_name == "to-watch":
# # Sorting is changing here because there is no user rating yet.
# return records.order_by("-movie__imdb_rating", "-movie__release_date")
# return records.order_by("-rating", "-movie__release_date")
. Output only the next line. | class SaveSettingsView(AjaxAnonymousView): |
Next line prediction: <|code_start|> record.watched_in_theatre = options["theatre"]
record.watched_in_4k = options["4k"]
record.watched_in_hd = options["hd"]
record.watched_in_full_hd = options["fullHd"]
record.save()
return self.success()
class SaveCommentView(AjaxView):
def put(self, request, **kwargs):
try:
record_id = int(kwargs["id"])
except (KeyError, ValueError):
return self.render_bad_request_response()
record = request.user.get_record(record_id)
try:
comment = request.PUT["comment"]
except KeyError:
return self.render_bad_request_response()
if record.comment != comment:
if not record.comment:
ActionRecord(
action_id=Action.ADDED_COMMENT, user=request.user, movie=record.movie, comment=comment
).save()
record.comment = comment
record.save()
return self.success()
<|code_end|>
. Use current file imports:
(import json
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.db.models import Q
from django.http import Http404
from moviesapp.models import Action, ActionRecord, List, Record, User
from .mixins import AjaxAnonymousView, AjaxView, TemplateAnonymousView, TemplateView
from .utils import add_movie_to_list, get_anothers_account, get_records, paginate, sort_by_rating)
and context including class names, function names, or small code snippets from other files:
# Path: src/moviesapp/views/mixins.py
# class AjaxAnonymousView(JsonRequestResponseMixin, View):
# def success(self, **kwargs):
# response = {"status": "success"}
# response.update(kwargs)
# return self.render_json_response(response)
#
# class AjaxView(LoginRequiredMixin, AjaxAnonymousView):
# raise_exception = True
#
# class TemplateAnonymousView(TemplateViewOriginal):
# pass
#
# class TemplateView(LoginRequiredMixin, TemplateViewOriginal):
# pass
#
# Path: src/moviesapp/views/utils.py
# def add_movie_to_list(movie_id, list_id, user):
# record = user.get_records().filter(movie_id=movie_id)
# if record.exists():
# record = record[0]
# if record.list_id != list_id:
# ActionRecord(action_id=2, user=user, movie_id=movie_id, list_id=list_id).save()
# record.list_id = list_id
# record.date = datetime.today()
# record.save()
# else:
# record = Record(movie_id=movie_id, list_id=list_id, user=user)
# record.save()
# ActionRecord(action_id=1, user=user, movie_id=movie_id, list_id=list_id).save()
#
# def get_anothers_account(username):
# if username:
# return get_object_or_404(User, username=username)
# return False
#
# def get_records(list_name, user, anothers_account):
# """Get records for certain user and list."""
# if anothers_account:
# user = anothers_account
# return user.get_records().filter(list__key_name=list_name).select_related("movie")
#
# def paginate(objects, page, objects_on_page):
# paginator = Paginator(objects, objects_on_page)
# try:
# objects = paginator.page(page)
# except PageNotAnInteger:
# # If page is not an integer, deliver first page.
# objects = paginator.page(1)
# except EmptyPage:
# # If page is out of range (e.g. 9999), deliver last page of results.
# objects = paginator.page(paginator.num_pages)
# return objects
#
# def sort_by_rating(records, username, list_name):
# if not username and list_name == "to-watch":
# # Sorting is changing here because there is no user rating yet.
# return records.order_by("-movie__imdb_rating", "-movie__release_date")
# return records.order_by("-rating", "-movie__release_date")
. Output only the next line. | class ListView(TemplateAnonymousView): |
Continue the code snippet: <|code_start|>
if username and session["recommendation"]:
records = self._filter_records_for_recommendation(records, request.user)
if username:
list_data = self._get_list_data(records)
else:
list_data = None
if not username and list_name == "to-watch" and records:
comments_and_ratings = self._get_comments_and_ratings(records.values_list("id", "movie_id"), request.user)
else:
comments_and_ratings = None
records = paginate(records, request.GET.get("page"), settings.RECORDS_ON_PAGE)
return {
"records": records,
"reviews": comments_and_ratings,
"list_id": List.objects.get(key_name=list_name).id,
"list": list_name,
"anothers_account": anothers_account,
"list_data": json.dumps(list_data),
"sort": session["sort"],
"query": query,
}
def get(self, *args, **kwargs):
self._initialize_session_values()
return super().get(*args, **kwargs)
<|code_end|>
. Use current file imports:
import json
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.db.models import Q
from django.http import Http404
from moviesapp.models import Action, ActionRecord, List, Record, User
from .mixins import AjaxAnonymousView, AjaxView, TemplateAnonymousView, TemplateView
from .utils import add_movie_to_list, get_anothers_account, get_records, paginate, sort_by_rating
and context (classes, functions, or code) from other files:
# Path: src/moviesapp/views/mixins.py
# class AjaxAnonymousView(JsonRequestResponseMixin, View):
# def success(self, **kwargs):
# response = {"status": "success"}
# response.update(kwargs)
# return self.render_json_response(response)
#
# class AjaxView(LoginRequiredMixin, AjaxAnonymousView):
# raise_exception = True
#
# class TemplateAnonymousView(TemplateViewOriginal):
# pass
#
# class TemplateView(LoginRequiredMixin, TemplateViewOriginal):
# pass
#
# Path: src/moviesapp/views/utils.py
# def add_movie_to_list(movie_id, list_id, user):
# record = user.get_records().filter(movie_id=movie_id)
# if record.exists():
# record = record[0]
# if record.list_id != list_id:
# ActionRecord(action_id=2, user=user, movie_id=movie_id, list_id=list_id).save()
# record.list_id = list_id
# record.date = datetime.today()
# record.save()
# else:
# record = Record(movie_id=movie_id, list_id=list_id, user=user)
# record.save()
# ActionRecord(action_id=1, user=user, movie_id=movie_id, list_id=list_id).save()
#
# def get_anothers_account(username):
# if username:
# return get_object_or_404(User, username=username)
# return False
#
# def get_records(list_name, user, anothers_account):
# """Get records for certain user and list."""
# if anothers_account:
# user = anothers_account
# return user.get_records().filter(list__key_name=list_name).select_related("movie")
#
# def paginate(objects, page, objects_on_page):
# paginator = Paginator(objects, objects_on_page)
# try:
# objects = paginator.page(page)
# except PageNotAnInteger:
# # If page is not an integer, deliver first page.
# objects = paginator.page(1)
# except EmptyPage:
# # If page is out of range (e.g. 9999), deliver last page of results.
# objects = paginator.page(paginator.num_pages)
# return objects
#
# def sort_by_rating(records, username, list_name):
# if not username and list_name == "to-watch":
# # Sorting is changing here because there is no user rating yet.
# return records.order_by("-movie__imdb_rating", "-movie__release_date")
# return records.order_by("-rating", "-movie__release_date")
. Output only the next line. | class RecommendationsView(TemplateView, ListView): |
Given the following code snippet before the placeholder: <|code_start|>
class ChangeRatingView(AjaxView):
def put(self, request, **kwargs):
try:
id_ = kwargs["id"]
rating = request.PUT["rating"]
except KeyError:
return self.render_bad_request_response()
record = request.user.get_record(id_)
if record.rating != rating:
if not record.rating:
ActionRecord(
action_id=Action.ADDED_RATING, user=request.user, movie=record.movie, rating=rating
).save()
record.rating = rating
record.save()
return self.success()
class AddToListView(AjaxView):
def post(self, request, **kwargs):
try:
movie_id = int(kwargs["id"])
list_id = int(request.POST["listId"])
except (KeyError, ValueError):
return self.render_bad_request_response()
<|code_end|>
, predict the next line using imports from the current file:
import json
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.db.models import Q
from django.http import Http404
from moviesapp.models import Action, ActionRecord, List, Record, User
from .mixins import AjaxAnonymousView, AjaxView, TemplateAnonymousView, TemplateView
from .utils import add_movie_to_list, get_anothers_account, get_records, paginate, sort_by_rating
and context including class names, function names, and sometimes code from other files:
# Path: src/moviesapp/views/mixins.py
# class AjaxAnonymousView(JsonRequestResponseMixin, View):
# def success(self, **kwargs):
# response = {"status": "success"}
# response.update(kwargs)
# return self.render_json_response(response)
#
# class AjaxView(LoginRequiredMixin, AjaxAnonymousView):
# raise_exception = True
#
# class TemplateAnonymousView(TemplateViewOriginal):
# pass
#
# class TemplateView(LoginRequiredMixin, TemplateViewOriginal):
# pass
#
# Path: src/moviesapp/views/utils.py
# def add_movie_to_list(movie_id, list_id, user):
# record = user.get_records().filter(movie_id=movie_id)
# if record.exists():
# record = record[0]
# if record.list_id != list_id:
# ActionRecord(action_id=2, user=user, movie_id=movie_id, list_id=list_id).save()
# record.list_id = list_id
# record.date = datetime.today()
# record.save()
# else:
# record = Record(movie_id=movie_id, list_id=list_id, user=user)
# record.save()
# ActionRecord(action_id=1, user=user, movie_id=movie_id, list_id=list_id).save()
#
# def get_anothers_account(username):
# if username:
# return get_object_or_404(User, username=username)
# return False
#
# def get_records(list_name, user, anothers_account):
# """Get records for certain user and list."""
# if anothers_account:
# user = anothers_account
# return user.get_records().filter(list__key_name=list_name).select_related("movie")
#
# def paginate(objects, page, objects_on_page):
# paginator = Paginator(objects, objects_on_page)
# try:
# objects = paginator.page(page)
# except PageNotAnInteger:
# # If page is not an integer, deliver first page.
# objects = paginator.page(1)
# except EmptyPage:
# # If page is out of range (e.g. 9999), deliver last page of results.
# objects = paginator.page(paginator.num_pages)
# return objects
#
# def sort_by_rating(records, username, list_name):
# if not username and list_name == "to-watch":
# # Sorting is changing here because there is no user rating yet.
# return records.order_by("-movie__imdb_rating", "-movie__release_date")
# return records.order_by("-rating", "-movie__release_date")
. Output only the next line. | add_movie_to_list(movie_id, list_id, request.user) |
Predict the next line for this snippet: <|code_start|> movies = [x[1] for x in record_ids_and_movies]
return (movies, {x[0]: x[1] for x in record_ids_and_movies})
def _get_list_data(self, records):
movies, record_ids_and_movies_dict = self._get_record_movie_data(records.values_list("id", "movie_id"))
movie_ids_and_list_ids = (
self.request.user.get_records().filter(movie_id__in=movies).values_list("movie_id", "list_id")
)
movie_id_and_list_id_dict = {}
for movie_id_and_list_id in movie_ids_and_list_ids:
movie_id_and_list_id_dict[movie_id_and_list_id[0]] = movie_id_and_list_id[1]
list_data = {}
for record_id, value in record_ids_and_movies_dict.items():
list_data[record_id] = movie_id_and_list_id_dict.get(value, 0)
return list_data
def _initialize_session_values(self):
session = self.request.session
if "sort" not in session:
session["sort"] = "addition_date"
if "recommendation" not in session:
session["recommendation"] = False
if "mode" not in session:
session["mode"] = "full"
self.session = session
def get_context_data(self, list_name, username=None):
if username is None and self.request.user.is_anonymous:
raise Http404
<|code_end|>
with the help of current file imports:
import json
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.db.models import Q
from django.http import Http404
from moviesapp.models import Action, ActionRecord, List, Record, User
from .mixins import AjaxAnonymousView, AjaxView, TemplateAnonymousView, TemplateView
from .utils import add_movie_to_list, get_anothers_account, get_records, paginate, sort_by_rating
and context from other files:
# Path: src/moviesapp/views/mixins.py
# class AjaxAnonymousView(JsonRequestResponseMixin, View):
# def success(self, **kwargs):
# response = {"status": "success"}
# response.update(kwargs)
# return self.render_json_response(response)
#
# class AjaxView(LoginRequiredMixin, AjaxAnonymousView):
# raise_exception = True
#
# class TemplateAnonymousView(TemplateViewOriginal):
# pass
#
# class TemplateView(LoginRequiredMixin, TemplateViewOriginal):
# pass
#
# Path: src/moviesapp/views/utils.py
# def add_movie_to_list(movie_id, list_id, user):
# record = user.get_records().filter(movie_id=movie_id)
# if record.exists():
# record = record[0]
# if record.list_id != list_id:
# ActionRecord(action_id=2, user=user, movie_id=movie_id, list_id=list_id).save()
# record.list_id = list_id
# record.date = datetime.today()
# record.save()
# else:
# record = Record(movie_id=movie_id, list_id=list_id, user=user)
# record.save()
# ActionRecord(action_id=1, user=user, movie_id=movie_id, list_id=list_id).save()
#
# def get_anothers_account(username):
# if username:
# return get_object_or_404(User, username=username)
# return False
#
# def get_records(list_name, user, anothers_account):
# """Get records for certain user and list."""
# if anothers_account:
# user = anothers_account
# return user.get_records().filter(list__key_name=list_name).select_related("movie")
#
# def paginate(objects, page, objects_on_page):
# paginator = Paginator(objects, objects_on_page)
# try:
# objects = paginator.page(page)
# except PageNotAnInteger:
# # If page is not an integer, deliver first page.
# objects = paginator.page(1)
# except EmptyPage:
# # If page is out of range (e.g. 9999), deliver last page of results.
# objects = paginator.page(paginator.num_pages)
# return objects
#
# def sort_by_rating(records, username, list_name):
# if not username and list_name == "to-watch":
# # Sorting is changing here because there is no user rating yet.
# return records.order_by("-movie__imdb_rating", "-movie__release_date")
# return records.order_by("-rating", "-movie__release_date")
, which may contain function names, class names, or code. Output only the next line. | anothers_account = get_anothers_account(username) |
Predict the next line for this snippet: <|code_start|> if record.rating:
data["rating"] = record.rating
comments_and_ratings[record.movie.pk].append(data)
data = {}
for record_id, value in record_ids_and_movies_dict.items():
data[record_id] = comments_and_ratings.get(value, None)
return data
@staticmethod
def _filter_records(records, query):
return records.filter(Q(movie__title_en__icontains=query) | Q(movie__title_ru__icontains=query))
@staticmethod
def _sort_records(records, sort, username, list_name):
if sort == "release_date":
return records.order_by("-movie__release_date")
if sort == "rating":
return sort_by_rating(records, username, list_name)
if sort == "addition_date":
return records.order_by("-date")
raise Exception("Unsupported sort type")
@staticmethod
def _get_record_movie_data(record_ids_and_movies):
movies = [x[1] for x in record_ids_and_movies]
return (movies, {x[0]: x[1] for x in record_ids_and_movies})
def _get_list_data(self, records):
movies, record_ids_and_movies_dict = self._get_record_movie_data(records.values_list("id", "movie_id"))
movie_ids_and_list_ids = (
<|code_end|>
with the help of current file imports:
import json
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.db.models import Q
from django.http import Http404
from moviesapp.models import Action, ActionRecord, List, Record, User
from .mixins import AjaxAnonymousView, AjaxView, TemplateAnonymousView, TemplateView
from .utils import add_movie_to_list, get_anothers_account, get_records, paginate, sort_by_rating
and context from other files:
# Path: src/moviesapp/views/mixins.py
# class AjaxAnonymousView(JsonRequestResponseMixin, View):
# def success(self, **kwargs):
# response = {"status": "success"}
# response.update(kwargs)
# return self.render_json_response(response)
#
# class AjaxView(LoginRequiredMixin, AjaxAnonymousView):
# raise_exception = True
#
# class TemplateAnonymousView(TemplateViewOriginal):
# pass
#
# class TemplateView(LoginRequiredMixin, TemplateViewOriginal):
# pass
#
# Path: src/moviesapp/views/utils.py
# def add_movie_to_list(movie_id, list_id, user):
# record = user.get_records().filter(movie_id=movie_id)
# if record.exists():
# record = record[0]
# if record.list_id != list_id:
# ActionRecord(action_id=2, user=user, movie_id=movie_id, list_id=list_id).save()
# record.list_id = list_id
# record.date = datetime.today()
# record.save()
# else:
# record = Record(movie_id=movie_id, list_id=list_id, user=user)
# record.save()
# ActionRecord(action_id=1, user=user, movie_id=movie_id, list_id=list_id).save()
#
# def get_anothers_account(username):
# if username:
# return get_object_or_404(User, username=username)
# return False
#
# def get_records(list_name, user, anothers_account):
# """Get records for certain user and list."""
# if anothers_account:
# user = anothers_account
# return user.get_records().filter(list__key_name=list_name).select_related("movie")
#
# def paginate(objects, page, objects_on_page):
# paginator = Paginator(objects, objects_on_page)
# try:
# objects = paginator.page(page)
# except PageNotAnInteger:
# # If page is not an integer, deliver first page.
# objects = paginator.page(1)
# except EmptyPage:
# # If page is out of range (e.g. 9999), deliver last page of results.
# objects = paginator.page(paginator.num_pages)
# return objects
#
# def sort_by_rating(records, username, list_name):
# if not username and list_name == "to-watch":
# # Sorting is changing here because there is no user rating yet.
# return records.order_by("-movie__imdb_rating", "-movie__release_date")
# return records.order_by("-rating", "-movie__release_date")
, which may contain function names, class names, or code. Output only the next line. | self.request.user.get_records().filter(movie_id__in=movies).values_list("movie_id", "list_id") |
Using the snippet: <|code_start|>
def get_context_data(self, list_name, username=None):
if username is None and self.request.user.is_anonymous:
raise Http404
anothers_account = get_anothers_account(username)
if anothers_account:
if User.objects.get(username=username) not in self.request.user.get_users():
raise PermissionDenied
records = get_records(list_name, self.request.user, anothers_account)
request = self.request
session = self.session
query = request.GET.get("query", False)
if query:
query = query.strip()
records = self._filter_records(records, query)
records = self._sort_records(records, session["sort"], username, list_name)
if username and session["recommendation"]:
records = self._filter_records_for_recommendation(records, request.user)
if username:
list_data = self._get_list_data(records)
else:
list_data = None
if not username and list_name == "to-watch" and records:
comments_and_ratings = self._get_comments_and_ratings(records.values_list("id", "movie_id"), request.user)
else:
comments_and_ratings = None
<|code_end|>
, determine the next line of code. You have imports:
import json
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.db.models import Q
from django.http import Http404
from moviesapp.models import Action, ActionRecord, List, Record, User
from .mixins import AjaxAnonymousView, AjaxView, TemplateAnonymousView, TemplateView
from .utils import add_movie_to_list, get_anothers_account, get_records, paginate, sort_by_rating
and context (class names, function names, or code) available:
# Path: src/moviesapp/views/mixins.py
# class AjaxAnonymousView(JsonRequestResponseMixin, View):
# def success(self, **kwargs):
# response = {"status": "success"}
# response.update(kwargs)
# return self.render_json_response(response)
#
# class AjaxView(LoginRequiredMixin, AjaxAnonymousView):
# raise_exception = True
#
# class TemplateAnonymousView(TemplateViewOriginal):
# pass
#
# class TemplateView(LoginRequiredMixin, TemplateViewOriginal):
# pass
#
# Path: src/moviesapp/views/utils.py
# def add_movie_to_list(movie_id, list_id, user):
# record = user.get_records().filter(movie_id=movie_id)
# if record.exists():
# record = record[0]
# if record.list_id != list_id:
# ActionRecord(action_id=2, user=user, movie_id=movie_id, list_id=list_id).save()
# record.list_id = list_id
# record.date = datetime.today()
# record.save()
# else:
# record = Record(movie_id=movie_id, list_id=list_id, user=user)
# record.save()
# ActionRecord(action_id=1, user=user, movie_id=movie_id, list_id=list_id).save()
#
# def get_anothers_account(username):
# if username:
# return get_object_or_404(User, username=username)
# return False
#
# def get_records(list_name, user, anothers_account):
# """Get records for certain user and list."""
# if anothers_account:
# user = anothers_account
# return user.get_records().filter(list__key_name=list_name).select_related("movie")
#
# def paginate(objects, page, objects_on_page):
# paginator = Paginator(objects, objects_on_page)
# try:
# objects = paginator.page(page)
# except PageNotAnInteger:
# # If page is not an integer, deliver first page.
# objects = paginator.page(1)
# except EmptyPage:
# # If page is out of range (e.g. 9999), deliver last page of results.
# objects = paginator.page(paginator.num_pages)
# return objects
#
# def sort_by_rating(records, username, list_name):
# if not username and list_name == "to-watch":
# # Sorting is changing here because there is no user rating yet.
# return records.order_by("-movie__imdb_rating", "-movie__release_date")
# return records.order_by("-rating", "-movie__release_date")
. Output only the next line. | records = paginate(records, request.GET.get("page"), settings.RECORDS_ON_PAGE) |
Predict the next line for this snippet: <|code_start|> if friends is None:
records = []
else:
records = records.filter(user__in=friends)
comments_and_ratings = {}
for record in records:
if record.comment or record.rating:
data = {"user": record.user}
if record.movie.pk not in comments_and_ratings:
comments_and_ratings[record.movie.pk] = []
if record.comment:
data["comment"] = record.comment
if record.rating:
data["rating"] = record.rating
comments_and_ratings[record.movie.pk].append(data)
data = {}
for record_id, value in record_ids_and_movies_dict.items():
data[record_id] = comments_and_ratings.get(value, None)
return data
@staticmethod
def _filter_records(records, query):
return records.filter(Q(movie__title_en__icontains=query) | Q(movie__title_ru__icontains=query))
@staticmethod
def _sort_records(records, sort, username, list_name):
if sort == "release_date":
return records.order_by("-movie__release_date")
if sort == "rating":
<|code_end|>
with the help of current file imports:
import json
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.db.models import Q
from django.http import Http404
from moviesapp.models import Action, ActionRecord, List, Record, User
from .mixins import AjaxAnonymousView, AjaxView, TemplateAnonymousView, TemplateView
from .utils import add_movie_to_list, get_anothers_account, get_records, paginate, sort_by_rating
and context from other files:
# Path: src/moviesapp/views/mixins.py
# class AjaxAnonymousView(JsonRequestResponseMixin, View):
# def success(self, **kwargs):
# response = {"status": "success"}
# response.update(kwargs)
# return self.render_json_response(response)
#
# class AjaxView(LoginRequiredMixin, AjaxAnonymousView):
# raise_exception = True
#
# class TemplateAnonymousView(TemplateViewOriginal):
# pass
#
# class TemplateView(LoginRequiredMixin, TemplateViewOriginal):
# pass
#
# Path: src/moviesapp/views/utils.py
# def add_movie_to_list(movie_id, list_id, user):
# record = user.get_records().filter(movie_id=movie_id)
# if record.exists():
# record = record[0]
# if record.list_id != list_id:
# ActionRecord(action_id=2, user=user, movie_id=movie_id, list_id=list_id).save()
# record.list_id = list_id
# record.date = datetime.today()
# record.save()
# else:
# record = Record(movie_id=movie_id, list_id=list_id, user=user)
# record.save()
# ActionRecord(action_id=1, user=user, movie_id=movie_id, list_id=list_id).save()
#
# def get_anothers_account(username):
# if username:
# return get_object_or_404(User, username=username)
# return False
#
# def get_records(list_name, user, anothers_account):
# """Get records for certain user and list."""
# if anothers_account:
# user = anothers_account
# return user.get_records().filter(list__key_name=list_name).select_related("movie")
#
# def paginate(objects, page, objects_on_page):
# paginator = Paginator(objects, objects_on_page)
# try:
# objects = paginator.page(page)
# except PageNotAnInteger:
# # If page is not an integer, deliver first page.
# objects = paginator.page(1)
# except EmptyPage:
# # If page is out of range (e.g. 9999), deliver last page of results.
# objects = paginator.page(paginator.num_pages)
# return objects
#
# def sort_by_rating(records, username, list_name):
# if not username and list_name == "to-watch":
# # Sorting is changing here because there is no user rating yet.
# return records.order_by("-movie__imdb_rating", "-movie__release_date")
# return records.order_by("-rating", "-movie__release_date")
, which may contain function names, class names, or code. Output only the next line. | return sort_by_rating(records, username, list_name) |
Based on the snippet: <|code_start|>
def load_user_data(backend, user, **kwargs): # pylint: disable=unused-argument
if user.loaded_initial_data:
return None
if backend.name in settings.VK_BACKENDS:
# We don't need the username and email because they are already loaded.
FIELDS = (
"first_name",
"last_name",
"photo_100",
"photo_200",
)
vk = user.get_vk()
data = vk.get_data(FIELDS)
<|code_end|>
, predict the immediate next line with the help of imports:
from django.conf import settings
from .vk import get_vk_avatar
and context (classes, functions, sometimes code) from other files:
# Path: src/moviesapp/vk.py
# def get_vk_avatar(url):
# if url in settings.VK_NO_AVATAR:
# return None
# return url
. Output only the next line. | avatar_small = get_vk_avatar(data["photo_100"]) |
Given the following code snippet before the placeholder: <|code_start|>
def load_omdb_movie_data(imdb_id):
try:
response = requests.get(f"http://www.omdbapi.com/?i={imdb_id}&apikey={settings.OMDB_KEY}")
except RequestException as e:
if settings.DEBUG:
raise
capture_exception(e)
<|code_end|>
, predict the next line using imports from the current file:
import re
import requests
from datetime import datetime
from django.conf import settings
from requests.exceptions import RequestException
from sentry_sdk import capture_exception
from .exceptions import OmdbError, OmdbLimitReached, OmdbRequestError
from .models import Movie
from .tmdb import get_tmdb_movie_data
and context including class names, function names, and sometimes code from other files:
# Path: src/moviesapp/exceptions.py
# class OmdbError(Exception):
# """OMDb error."""
#
# class OmdbLimitReached(Exception):
# """OMDb limit reached."""
#
# class OmdbRequestError(Exception):
# """OMDb request error."""
#
# Path: src/moviesapp/models.py
# class Movie(models.Model):
# title = models.CharField(max_length=255)
# title_original = models.CharField(max_length=255)
# country = models.CharField(max_length=255, null=True, blank=True)
# description = models.TextField(null=True, blank=True)
# director = models.CharField(max_length=255, null=True, blank=True)
# writer = models.CharField(max_length=255, null=True, blank=True)
# genre = models.CharField(max_length=255, null=True, blank=True)
# actors = models.CharField(max_length=255, null=True, blank=True)
# imdb_id = models.CharField(max_length=15, unique=True, db_index=True)
# tmdb_id = models.IntegerField(unique=True)
# imdb_rating = models.DecimalField(max_digits=2, decimal_places=1, null=True)
# poster = models.CharField(max_length=255, null=True)
# release_date = models.DateField(null=True)
# runtime = models.TimeField(null=True, blank=True)
# homepage = models.URLField(null=True, blank=True)
# trailers = JSONField(null=True, blank=True)
#
# class Meta:
# ordering = ["pk"]
#
# def __str__(self):
# return str(self.title)
#
# def imdb_url(self):
# return settings.IMDB_BASE_URL + self.imdb_id + "/"
#
# def get_trailers(self):
# if self.trailers:
# return self.trailers
# return self.trailers_en
#
# def has_trailers(self):
# return bool(self.get_trailers())
#
# def _get_poster(self, size):
# return get_poster_url(size, self.poster)
#
# @property
# def poster_normal(self):
# return self._get_poster("normal")
#
# @property
# def poster_small(self):
# return self._get_poster("small")
#
# @property
# def poster_big(self):
# return self._get_poster("big")
#
# @property
# def id_title(self):
# return f"{self.pk} - {self}"
#
# def cli_string(self, last_movie_id):
# """
# Return string version for CLI.
#
# We need last_movie_id because we want to know how big is the number (in characters) to be able to make
# perfect formatting.
# We need to keep last_movie_id as a parameter because otherwise we hit the database every time we run the
# function.
# """
# MAX_CHARS = 40
# ENDING = ".."
# n = len(str(last_movie_id)) + 1
# id_format = f"{{0: < {n}}}"
# title = str(self)
# title = (title[:MAX_CHARS] + ENDING) if len(title) > MAX_CHARS else title
# id_ = id_format.format(self.pk)
# title_max_length = MAX_CHARS + len(ENDING)
# title_format = f"{{:{title_max_length}s}}"
# title = title_format.format(title) # pylint: disable=consider-using-f-string
# return f"{id_} - {title}"[1:]
#
# Path: src/moviesapp/tmdb.py
# def get_tmdb_movie_data(tmdb_id):
# def get_release_date(release_date):
# if release_date:
# return release_date
# return None
#
# def get_trailers(movie_data):
# trailers = []
# for trailer in movie_data.videos()["results"]:
# trailer_ = {"name": trailer["name"], "source": trailer["key"]}
# trailers.append(trailer_)
# return trailers
#
# def get_movie_data(tmdb_id, lang):
# tmdb = get_tmdb(lang=lang)
# return tmdb.Movies(tmdb_id)
#
# movie_data_en = get_movie_data(tmdb_id, "en")
# movie_info_en = movie_data_en.info()
# # We have to get all info in english first before we switch to russian or everything breaks.
# trailers_en = get_trailers(movie_data_en)
# movie_data_ru = get_movie_data(tmdb_id, "ru")
# movie_info_ru = movie_data_ru.info()
# trailers_ru = get_trailers(movie_data_ru)
# imdb_id = movie_info_en["imdb_id"]
# if imdb_id:
# return {
# "tmdb_id": tmdb_id,
# "imdb_id": imdb_id,
# "release_date": get_release_date(movie_info_en["release_date"]),
# "title_original": movie_info_en["original_title"],
# "poster_ru": get_poster_from_tmdb(movie_info_ru["poster_path"]),
# "poster_en": get_poster_from_tmdb(movie_info_en["poster_path"]),
# "homepage": movie_info_en["homepage"],
# "trailers_en": trailers_en,
# "trailers_ru": trailers_ru,
# "title_en": movie_info_en["title"],
# "title_ru": movie_info_ru["title"],
# "description_en": movie_info_en["overview"],
# "description_ru": movie_info_ru["overview"],
# }
# raise MovieNotInDb(tmdb_id)
. Output only the next line. | raise OmdbRequestError from e |
Here is a snippet: <|code_start|> i = 0
for action in actions:
action_ = {
"user": action.user,
"action": action,
"movie": action.movie,
"movie_poster": posters[i],
"movie_poster_2x": posters_2x[i],
"list": action.list,
"comment": action.comment,
"rating": action.rating,
"date": action.date,
}
actions_output.append(action_)
i += 1
return {"list_name": FEED_TITLE[list_name], "actions": actions_output}
class PeopleView(TemplateAnonymousView):
template_name = "social/people.html"
users = None
def get_context_data(self):
return {"users": paginate(self.users, self.request.GET.get("page"), settings.PEOPLE_ON_PAGE)}
def get(self, *args, **kwargs):
self.users = self.request.user.get_users(sort=True)
return super().get(*args, **kwargs)
<|code_end|>
. Write the next line using the current file imports:
from datetime import datetime
from dateutil.relativedelta import relativedelta
from django.conf import settings
from django.utils.translation import gettext_lazy as _
from moviesapp.models import ActionRecord
from .mixins import TemplateAnonymousView, TemplateView
from .utils import paginate
and context from other files:
# Path: src/moviesapp/views/mixins.py
# class TemplateAnonymousView(TemplateViewOriginal):
# pass
#
# class TemplateView(LoginRequiredMixin, TemplateViewOriginal):
# pass
#
# Path: src/moviesapp/views/utils.py
# def paginate(objects, page, objects_on_page):
# paginator = Paginator(objects, objects_on_page)
# try:
# objects = paginator.page(page)
# except PageNotAnInteger:
# # If page is not an integer, deliver first page.
# objects = paginator.page(1)
# except EmptyPage:
# # If page is out of range (e.g. 9999), deliver last page of results.
# objects = paginator.page(paginator.num_pages)
# return objects
, which may include functions, classes, or code. Output only the next line. | class FriendsView(TemplateView, PeopleView): |
Here is a snippet: <|code_start|>
users = self.request.user.get_users(friends=list_name == "friends")
actions = actions.filter(user__in=users)
posters = [action.movie.poster_small for action in actions]
posters_2x = [action.movie.poster_normal for action in actions]
actions_output = []
i = 0
for action in actions:
action_ = {
"user": action.user,
"action": action,
"movie": action.movie,
"movie_poster": posters[i],
"movie_poster_2x": posters_2x[i],
"list": action.list,
"comment": action.comment,
"rating": action.rating,
"date": action.date,
}
actions_output.append(action_)
i += 1
return {"list_name": FEED_TITLE[list_name], "actions": actions_output}
class PeopleView(TemplateAnonymousView):
template_name = "social/people.html"
users = None
def get_context_data(self):
<|code_end|>
. Write the next line using the current file imports:
from datetime import datetime
from dateutil.relativedelta import relativedelta
from django.conf import settings
from django.utils.translation import gettext_lazy as _
from moviesapp.models import ActionRecord
from .mixins import TemplateAnonymousView, TemplateView
from .utils import paginate
and context from other files:
# Path: src/moviesapp/views/mixins.py
# class TemplateAnonymousView(TemplateViewOriginal):
# pass
#
# class TemplateView(LoginRequiredMixin, TemplateViewOriginal):
# pass
#
# Path: src/moviesapp/views/utils.py
# def paginate(objects, page, objects_on_page):
# paginator = Paginator(objects, objects_on_page)
# try:
# objects = paginator.page(page)
# except PageNotAnInteger:
# # If page is not an integer, deliver first page.
# objects = paginator.page(1)
# except EmptyPage:
# # If page is out of range (e.g. 9999), deliver last page of results.
# objects = paginator.page(paginator.num_pages)
# return objects
, which may include functions, classes, or code. Output only the next line. | return {"users": paginate(self.users, self.request.GET.get("page"), settings.PEOPLE_ON_PAGE)} |
Using the snippet: <|code_start|> comodel_name="res.partner.bank", string="Bank account", ondelete="restrict"
)
invoice_message_ids = fields.One2many(
comodel_name="paynet.invoice.message",
inverse_name="service_id",
string="Invoice Messages",
readonly=True,
)
ebill_payment_contract_ids = fields.One2many(
comodel_name="ebill.payment.contract",
inverse_name="paynet_service_id",
string="Contracts",
readonly=True,
)
active = fields.Boolean(default=True)
@api.depends("use_test_service")
def _compute_url(self):
for record in self:
if record.use_test_service:
record.url = SYSTEM_TEST_URL
else:
record.url = SYSTEM_PROD_URL
def take_shipment(self, content):
"""Send a shipment via DWS to the Paynet System
Return value is the shipment id
"""
self.ensure_one()
<|code_end|>
, determine the next line of code. You have imports:
import logging
import zeep
from lxml import etree
from odoo import api, fields, models
from odoo.exceptions import UserError
from ..components.api import PayNetDWS
and context (class names, function names, or code) available:
# Path: ebill_paynet/components/api.py
# class PayNetDWS:
# """PayNet DWS web services."""
#
# def __init__(self, url, test_service):
# settings = zeep.Settings(xml_huge_tree=True)
# session = requests.Session()
# if test_service:
# session.verify = SSL_TEST_CERTIFICATE
# else:
# session.verify = SSL_PROD_CERTIFICATE
# transport = zeep.transports.Transport(session=session)
# self.client = zeep.Client(WSDL_DOC, transport=transport, settings=settings)
# if url:
# self.service = self.client.create_service(
# "{http://www.sap.com/DWS}DWSBinding", url
# )
# else:
# self.service = self.client.service
#
# @staticmethod
# def authorization(userid, password):
# """Generate Authorization node."""
# return {"UserName": userid, "Password": password}
#
# @staticmethod
# def handle_fault(fault):
# msg = ("{}\n" "code: {} -> {}\n" "actor: {}\n" "detail: {}\n").format(
# fault.message.upper(),
# fault.code,
# fault.subcodes,
# fault.actor,
# html.tostring(fault.detail),
# )
# _logger.info("Paynet DWS fault : {}".format(msg))
# return msg
. Output only the next line. | dws = PayNetDWS(self.url, self.use_test_service) |
Based on the snippet: <|code_start|> ("error", "Error"),
],
default="draft",
)
ic_ref = fields.Char(
string="IC Ref", size=14, help="Document interchange reference"
)
# Set with invoice_id.number but also with returned data from server ?
ref = fields.Char("Reference No.", size=35)
ebill_account_number = fields.Char("Paynet Id", size=20)
payload = fields.Text("Payload sent")
response = fields.Text("Response recieved")
shipment_id = fields.Char(size=24, help="Shipment Id on Paynet service")
payment_type = fields.Selection(
selection=[("qr", "QR"), ("isr", "ISR"), ("esp", "ESP"), ("npy", "NPY")],
default="qr",
readonly=True,
)
def _get_ic_ref(self):
return "SA%012d" % self.id
def send_to_paynet(self):
for message in self:
message.payload = message._generate_payload()
try:
shipment_id = message.service_id.take_shipment(message.payload)
message.shipment_id = shipment_id
message.state = "sent"
except zeep.exceptions.Fault as e:
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import zeep # isort:skip
from datetime import datetime
from jinja2 import Environment, FileSystemLoader, select_autoescape
from odoo import fields, models
from odoo.modules.module import get_module_root
from odoo.addons.base.models.res_bank import sanitize_account_number
from ..components.api import PayNetDWS
and context (classes, functions, sometimes code) from other files:
# Path: ebill_paynet/components/api.py
# class PayNetDWS:
# """PayNet DWS web services."""
#
# def __init__(self, url, test_service):
# settings = zeep.Settings(xml_huge_tree=True)
# session = requests.Session()
# if test_service:
# session.verify = SSL_TEST_CERTIFICATE
# else:
# session.verify = SSL_PROD_CERTIFICATE
# transport = zeep.transports.Transport(session=session)
# self.client = zeep.Client(WSDL_DOC, transport=transport, settings=settings)
# if url:
# self.service = self.client.create_service(
# "{http://www.sap.com/DWS}DWSBinding", url
# )
# else:
# self.service = self.client.service
#
# @staticmethod
# def authorization(userid, password):
# """Generate Authorization node."""
# return {"UserName": userid, "Password": password}
#
# @staticmethod
# def handle_fault(fault):
# msg = ("{}\n" "code: {} -> {}\n" "actor: {}\n" "detail: {}\n").format(
# fault.message.upper(),
# fault.code,
# fault.subcodes,
# fault.actor,
# html.tostring(fault.detail),
# )
# _logger.info("Paynet DWS fault : {}".format(msg))
# return msg
. Output only the next line. | message.response = PayNetDWS.handle_fault(e) |
Using the snippet: <|code_start|>
class TestEbillPaynet(SingleTransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True))
# Invoice and account should be the same company
cls.env.user.company_id = cls.env.ref("l10n_ch.demo_company_ch").id
cls.bank = cls.env.ref("base.res_bank_1")
cls.bank.clearing = 777
cls.partner_bank = cls.env["res.partner.bank"].create(
{
"bank_id": cls.bank.id,
"acc_number": "300.300.300",
"acc_holder_name": "AccountHolderName",
"partner_id": cls.env.user.partner_id.id,
"l10n_ch_qr_iban": "CH21 3080 8001 2345 6782 7",
}
)
cls.paynet = cls.env["paynet.service"].create(
{
"name": "Paynet Test Service",
"use_test_service": True,
"client_pid": os.getenv("PAYNET_ID", "123456789"),
"service_type": "b2b",
}
)
<|code_end|>
, determine the next line of code. You have imports:
import os
from odoo.tests.common import SingleTransactionCase
from ..components.api import PayNetDWS
from .common import recorder
and context (class names, function names, or code) available:
# Path: ebill_paynet/components/api.py
# class PayNetDWS:
# """PayNet DWS web services."""
#
# def __init__(self, url, test_service):
# settings = zeep.Settings(xml_huge_tree=True)
# session = requests.Session()
# if test_service:
# session.verify = SSL_TEST_CERTIFICATE
# else:
# session.verify = SSL_PROD_CERTIFICATE
# transport = zeep.transports.Transport(session=session)
# self.client = zeep.Client(WSDL_DOC, transport=transport, settings=settings)
# if url:
# self.service = self.client.create_service(
# "{http://www.sap.com/DWS}DWSBinding", url
# )
# else:
# self.service = self.client.service
#
# @staticmethod
# def authorization(userid, password):
# """Generate Authorization node."""
# return {"UserName": userid, "Password": password}
#
# @staticmethod
# def handle_fault(fault):
# msg = ("{}\n" "code: {} -> {}\n" "actor: {}\n" "detail: {}\n").format(
# fault.message.upper(),
# fault.code,
# fault.subcodes,
# fault.actor,
# html.tostring(fault.detail),
# )
# _logger.info("Paynet DWS fault : {}".format(msg))
# return msg
#
# Path: ebill_paynet/tests/common.py
# class CommonCase(SavepointCase, XmlTestMixin):
# def setUpClass(cls):
# def compare_xml_line_by_line(content, expected):
# def get_recorder(base_path=None, **kw):
. Output only the next line. | cls.dws = PayNetDWS(cls.paynet.url, True) |
Predict the next line for this snippet: <|code_start|> "reconcile": True,
}
)
cls.product = cls.env["product.template"].create(
{"name": "Product One", "list_price": 100.00}
)
cls.invoice_1 = cls.env["account.move"].create(
{
"partner_id": cls.customer.id,
# 'account_id': cls.account.id,
"move_type": "out_invoice",
"transmit_method_id": cls.env.ref(
"ebill_paynet.paynet_transmit_method"
).id,
"invoice_line_ids": [
(
0,
0,
{
"account_id": cls.account.id,
"product_id": cls.product.product_variant_ids[:1].id,
"name": "Product 1",
"quantity": 1.0,
"price_unit": 100.00,
},
)
],
}
)
<|code_end|>
with the help of current file imports:
import os
from odoo.tests.common import SingleTransactionCase
from ..components.api import PayNetDWS
from .common import recorder
and context from other files:
# Path: ebill_paynet/components/api.py
# class PayNetDWS:
# """PayNet DWS web services."""
#
# def __init__(self, url, test_service):
# settings = zeep.Settings(xml_huge_tree=True)
# session = requests.Session()
# if test_service:
# session.verify = SSL_TEST_CERTIFICATE
# else:
# session.verify = SSL_PROD_CERTIFICATE
# transport = zeep.transports.Transport(session=session)
# self.client = zeep.Client(WSDL_DOC, transport=transport, settings=settings)
# if url:
# self.service = self.client.create_service(
# "{http://www.sap.com/DWS}DWSBinding", url
# )
# else:
# self.service = self.client.service
#
# @staticmethod
# def authorization(userid, password):
# """Generate Authorization node."""
# return {"UserName": userid, "Password": password}
#
# @staticmethod
# def handle_fault(fault):
# msg = ("{}\n" "code: {} -> {}\n" "actor: {}\n" "detail: {}\n").format(
# fault.message.upper(),
# fault.code,
# fault.subcodes,
# fault.actor,
# html.tostring(fault.detail),
# )
# _logger.info("Paynet DWS fault : {}".format(msg))
# return msg
#
# Path: ebill_paynet/tests/common.py
# class CommonCase(SavepointCase, XmlTestMixin):
# def setUpClass(cls):
# def compare_xml_line_by_line(content, expected):
# def get_recorder(base_path=None, **kw):
, which may contain function names, class names, or code. Output only the next line. | @recorder.use_cassette |
Using the snippet: <|code_start|>
class Plugin(Process): # pragma: no cover
def __repr__(self):
return "<Plugin {}>".format(self.name)
def execute(self, **kwargs):
raise NotImplementedError()
<|code_end|>
, determine the next line of code. You have imports:
from therapist.collection import Collection
from therapist.exc import Error
from therapist.process import Process
and context (class names, function names, or code) available:
# Path: therapist/collection.py
# class Collection(object):
# """A generic iterable set of objects."""
#
# class Meta:
# pass
#
# def __init__(self, objects=None):
# self._objects = []
#
# if objects:
# for obj in objects:
# self.append(obj)
#
# def __iter__(self):
# return iter(self._objects)
#
# def __getitem__(self, item):
# return self._objects[item]
#
# def __str__(self): # pragma: no cover
# return str(self._objects)
#
# def __repr__(self): # pragma: no cover
# return "<{}>".format(self.__class__.__name__)
#
# def __bool__(self):
# return bool(self._objects)
#
# __nonzero__ = __bool__
#
# @property
# def objects(self):
# return self._objects
#
# def append(self, v):
# object_class = getattr(self.Meta, "object_class", object)
#
# if not isinstance(v, object_class):
# raise TypeError("Expected an instance of `{}`.".format(object_class.__name__))
#
# self._objects.append(v)
#
# Path: therapist/exc.py
# class Error(Exception):
# def __init__(self, message=None, *args, **kwargs):
# self.message = message
# super(Error, self).__init__(*args, **kwargs)
#
# Path: therapist/process.py
# class Process(object):
# def __init__(self, name, **kwargs):
# self.name = name
# self.description = kwargs.pop("description", None)
#
# self._include = None
# self.include = kwargs.pop("include", None)
#
# self._exclude = None
# self.exclude = kwargs.pop("exclude", None)
#
# self.config = kwargs
#
# def __call__(self, **kwargs):
# return self.execute(**kwargs)
#
# def __str__(self):
# return self.description if self.description else self.name
#
# def __repr__(self):
# return "<{} {}>".format(self.__class__.__name__, self.name)
#
# @property
# def include(self):
# return self._include
#
# @include.setter
# def include(self, value):
# if value is None:
# self._include = []
# else:
# self._include = value if isinstance(value, list) else [value]
#
# @property
# def exclude(self):
# return self._exclude
#
# @exclude.setter
# def exclude(self, value):
# if value is None:
# self._exclude = []
# else:
# self._exclude = value if isinstance(value, list) else [value]
#
# def filter_files(self, files):
# if self.include:
# spec = PathSpec(map(GitWildMatchPattern, self.include))
# files = list(spec.match_files(files))
#
# if self.exclude:
# spec = PathSpec(map(GitWildMatchPattern, self.exclude))
# exclude = list(spec.match_files(files))
# files = list(filter(lambda f: f not in exclude, files))
#
# return files
#
# def execute(self, **kwargs):
# raise NotImplementedError() # pragma: no cover
. Output only the next line. | class PluginCollection(Collection): |
Next line prediction: <|code_start|>
class Plugin(Process): # pragma: no cover
def __repr__(self):
return "<Plugin {}>".format(self.name)
def execute(self, **kwargs):
raise NotImplementedError()
class PluginCollection(Collection):
class Meta:
object_class = Plugin
<|code_end|>
. Use current file imports:
(from therapist.collection import Collection
from therapist.exc import Error
from therapist.process import Process)
and context including class names, function names, or small code snippets from other files:
# Path: therapist/collection.py
# class Collection(object):
# """A generic iterable set of objects."""
#
# class Meta:
# pass
#
# def __init__(self, objects=None):
# self._objects = []
#
# if objects:
# for obj in objects:
# self.append(obj)
#
# def __iter__(self):
# return iter(self._objects)
#
# def __getitem__(self, item):
# return self._objects[item]
#
# def __str__(self): # pragma: no cover
# return str(self._objects)
#
# def __repr__(self): # pragma: no cover
# return "<{}>".format(self.__class__.__name__)
#
# def __bool__(self):
# return bool(self._objects)
#
# __nonzero__ = __bool__
#
# @property
# def objects(self):
# return self._objects
#
# def append(self, v):
# object_class = getattr(self.Meta, "object_class", object)
#
# if not isinstance(v, object_class):
# raise TypeError("Expected an instance of `{}`.".format(object_class.__name__))
#
# self._objects.append(v)
#
# Path: therapist/exc.py
# class Error(Exception):
# def __init__(self, message=None, *args, **kwargs):
# self.message = message
# super(Error, self).__init__(*args, **kwargs)
#
# Path: therapist/process.py
# class Process(object):
# def __init__(self, name, **kwargs):
# self.name = name
# self.description = kwargs.pop("description", None)
#
# self._include = None
# self.include = kwargs.pop("include", None)
#
# self._exclude = None
# self.exclude = kwargs.pop("exclude", None)
#
# self.config = kwargs
#
# def __call__(self, **kwargs):
# return self.execute(**kwargs)
#
# def __str__(self):
# return self.description if self.description else self.name
#
# def __repr__(self):
# return "<{} {}>".format(self.__class__.__name__, self.name)
#
# @property
# def include(self):
# return self._include
#
# @include.setter
# def include(self, value):
# if value is None:
# self._include = []
# else:
# self._include = value if isinstance(value, list) else [value]
#
# @property
# def exclude(self):
# return self._exclude
#
# @exclude.setter
# def exclude(self, value):
# if value is None:
# self._exclude = []
# else:
# self._exclude = value if isinstance(value, list) else [value]
#
# def filter_files(self, files):
# if self.include:
# spec = PathSpec(map(GitWildMatchPattern, self.include))
# files = list(spec.match_files(files))
#
# if self.exclude:
# spec = PathSpec(map(GitWildMatchPattern, self.exclude))
# exclude = list(spec.match_files(files))
# files = list(filter(lambda f: f not in exclude, files))
#
# return files
#
# def execute(self, **kwargs):
# raise NotImplementedError() # pragma: no cover
. Output only the next line. | class DoesNotExist(Error): |
Next line prediction: <|code_start|>
def list_plugins():
return [
entry_point.name
for entry_point in pkg_resources.iter_entry_points(group="therapist.plugin")
]
def load_plugin(name):
for entry_point in pkg_resources.iter_entry_points(group="therapist.plugin", name=name):
plugin = entry_point.load()
<|code_end|>
. Use current file imports:
(import pkg_resources
from therapist.plugins import Plugin
from therapist.plugins.exc import InvalidPlugin, PluginNotInstalled)
and context including class names, function names, or small code snippets from other files:
# Path: therapist/plugins/plugin.py
# class Plugin(Process): # pragma: no cover
# def __repr__(self):
# return "<Plugin {}>".format(self.name)
#
# def execute(self, **kwargs):
# raise NotImplementedError()
#
# Path: therapist/plugins/exc.py
# class InvalidPlugin(Error):
# pass
#
# class PluginNotInstalled(Error):
# pass
. Output only the next line. | if issubclass(plugin, Plugin): |
Given snippet: <|code_start|>
def list_plugins():
return [
entry_point.name
for entry_point in pkg_resources.iter_entry_points(group="therapist.plugin")
]
def load_plugin(name):
for entry_point in pkg_resources.iter_entry_points(group="therapist.plugin", name=name):
plugin = entry_point.load()
if issubclass(plugin, Plugin):
return plugin
else:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pkg_resources
from therapist.plugins import Plugin
from therapist.plugins.exc import InvalidPlugin, PluginNotInstalled
and context:
# Path: therapist/plugins/plugin.py
# class Plugin(Process): # pragma: no cover
# def __repr__(self):
# return "<Plugin {}>".format(self.name)
#
# def execute(self, **kwargs):
# raise NotImplementedError()
#
# Path: therapist/plugins/exc.py
# class InvalidPlugin(Error):
# pass
#
# class PluginNotInstalled(Error):
# pass
which might include code, classes, or functions. Output only the next line. | raise InvalidPlugin("Plugin must inherit from `Plugin`.") |
Here is a snippet: <|code_start|>
def list_plugins():
return [
entry_point.name
for entry_point in pkg_resources.iter_entry_points(group="therapist.plugin")
]
def load_plugin(name):
for entry_point in pkg_resources.iter_entry_points(group="therapist.plugin", name=name):
plugin = entry_point.load()
if issubclass(plugin, Plugin):
return plugin
else:
raise InvalidPlugin("Plugin must inherit from `Plugin`.")
<|code_end|>
. Write the next line using the current file imports:
import pkg_resources
from therapist.plugins import Plugin
from therapist.plugins.exc import InvalidPlugin, PluginNotInstalled
and context from other files:
# Path: therapist/plugins/plugin.py
# class Plugin(Process): # pragma: no cover
# def __repr__(self):
# return "<Plugin {}>".format(self.name)
#
# def execute(self, **kwargs):
# raise NotImplementedError()
#
# Path: therapist/plugins/exc.py
# class InvalidPlugin(Error):
# pass
#
# class PluginNotInstalled(Error):
# pass
, which may include functions, classes, or code. Output only the next line. | raise PluginNotInstalled("Plugin `{}` has not been installed.".format(name)) |
Next line prediction: <|code_start|> def is_failure(self):
return self.status == self.FAILURE
@property
def is_error(self):
return self.status == self.ERROR
@property
def is_skip(self):
return not (self.is_success or self.is_failure or self.is_error)
@property
def execution_time(self):
return self.end_time - self.start_time
def mark_complete(self, status=None, output=None, error=None):
if status is not None:
self.status = status
self.output = output
self.error = error
self.end_time = time.time()
@property
def has_modified_files(self):
return len(self.modified_files) > 0
def add_modified_file(self, path):
self.modified_files.append(path)
<|code_end|>
. Use current file imports:
(import time
from xml.etree import ElementTree
from therapist.collection import Collection
from therapist.process import Process)
and context including class names, function names, or small code snippets from other files:
# Path: therapist/collection.py
# class Collection(object):
# """A generic iterable set of objects."""
#
# class Meta:
# pass
#
# def __init__(self, objects=None):
# self._objects = []
#
# if objects:
# for obj in objects:
# self.append(obj)
#
# def __iter__(self):
# return iter(self._objects)
#
# def __getitem__(self, item):
# return self._objects[item]
#
# def __str__(self): # pragma: no cover
# return str(self._objects)
#
# def __repr__(self): # pragma: no cover
# return "<{}>".format(self.__class__.__name__)
#
# def __bool__(self):
# return bool(self._objects)
#
# __nonzero__ = __bool__
#
# @property
# def objects(self):
# return self._objects
#
# def append(self, v):
# object_class = getattr(self.Meta, "object_class", object)
#
# if not isinstance(v, object_class):
# raise TypeError("Expected an instance of `{}`.".format(object_class.__name__))
#
# self._objects.append(v)
#
# Path: therapist/process.py
# class Process(object):
# def __init__(self, name, **kwargs):
# self.name = name
# self.description = kwargs.pop("description", None)
#
# self._include = None
# self.include = kwargs.pop("include", None)
#
# self._exclude = None
# self.exclude = kwargs.pop("exclude", None)
#
# self.config = kwargs
#
# def __call__(self, **kwargs):
# return self.execute(**kwargs)
#
# def __str__(self):
# return self.description if self.description else self.name
#
# def __repr__(self):
# return "<{} {}>".format(self.__class__.__name__, self.name)
#
# @property
# def include(self):
# return self._include
#
# @include.setter
# def include(self, value):
# if value is None:
# self._include = []
# else:
# self._include = value if isinstance(value, list) else [value]
#
# @property
# def exclude(self):
# return self._exclude
#
# @exclude.setter
# def exclude(self, value):
# if value is None:
# self._exclude = []
# else:
# self._exclude = value if isinstance(value, list) else [value]
#
# def filter_files(self, files):
# if self.include:
# spec = PathSpec(map(GitWildMatchPattern, self.include))
# files = list(spec.match_files(files))
#
# if self.exclude:
# spec = PathSpec(map(GitWildMatchPattern, self.exclude))
# exclude = list(spec.match_files(files))
# files = list(filter(lambda f: f not in exclude, files))
#
# return files
#
# def execute(self, **kwargs):
# raise NotImplementedError() # pragma: no cover
. Output only the next line. | class ResultCollection(Collection): |
Predict the next line for this snippet: <|code_start|>
def __init__(self, process, status=None):
self._process = None
self.process = process
self.status = status
self.output = None
self.error = None
self.start_time = time.time()
self.end_time = self.start_time
self.modified_files = []
def __str__(self):
if self.is_success:
return "SUCCESS"
elif self.is_failure:
return "FAILURE"
elif self.is_error:
return "ERROR"
else:
return "SKIP"
def __repr__(self): # pragma: no cover
return "<Result {}>".format(self.process)
@property
def process(self):
return self._process
@process.setter
def process(self, value):
<|code_end|>
with the help of current file imports:
import time
from xml.etree import ElementTree
from therapist.collection import Collection
from therapist.process import Process
and context from other files:
# Path: therapist/collection.py
# class Collection(object):
# """A generic iterable set of objects."""
#
# class Meta:
# pass
#
# def __init__(self, objects=None):
# self._objects = []
#
# if objects:
# for obj in objects:
# self.append(obj)
#
# def __iter__(self):
# return iter(self._objects)
#
# def __getitem__(self, item):
# return self._objects[item]
#
# def __str__(self): # pragma: no cover
# return str(self._objects)
#
# def __repr__(self): # pragma: no cover
# return "<{}>".format(self.__class__.__name__)
#
# def __bool__(self):
# return bool(self._objects)
#
# __nonzero__ = __bool__
#
# @property
# def objects(self):
# return self._objects
#
# def append(self, v):
# object_class = getattr(self.Meta, "object_class", object)
#
# if not isinstance(v, object_class):
# raise TypeError("Expected an instance of `{}`.".format(object_class.__name__))
#
# self._objects.append(v)
#
# Path: therapist/process.py
# class Process(object):
# def __init__(self, name, **kwargs):
# self.name = name
# self.description = kwargs.pop("description", None)
#
# self._include = None
# self.include = kwargs.pop("include", None)
#
# self._exclude = None
# self.exclude = kwargs.pop("exclude", None)
#
# self.config = kwargs
#
# def __call__(self, **kwargs):
# return self.execute(**kwargs)
#
# def __str__(self):
# return self.description if self.description else self.name
#
# def __repr__(self):
# return "<{} {}>".format(self.__class__.__name__, self.name)
#
# @property
# def include(self):
# return self._include
#
# @include.setter
# def include(self, value):
# if value is None:
# self._include = []
# else:
# self._include = value if isinstance(value, list) else [value]
#
# @property
# def exclude(self):
# return self._exclude
#
# @exclude.setter
# def exclude(self, value):
# if value is None:
# self._exclude = []
# else:
# self._exclude = value if isinstance(value, list) else [value]
#
# def filter_files(self, files):
# if self.include:
# spec = PathSpec(map(GitWildMatchPattern, self.include))
# files = list(spec.match_files(files))
#
# if self.exclude:
# spec = PathSpec(map(GitWildMatchPattern, self.exclude))
# exclude = list(spec.match_files(files))
# files = list(filter(lambda f: f not in exclude, files))
#
# return files
#
# def execute(self, **kwargs):
# raise NotImplementedError() # pragma: no cover
, which may contain function names, class names, or code. Output only the next line. | if not (isinstance(value, Process)): |
Given the code snippet: <|code_start|> self._options[key.replace("-", "_")] = value[key]
else:
self.options = {value.replace("-", "_"): True}
@property
def flags(self):
return self._flags
@flags.setter
def flags(self, value):
if value is None:
self._flags = set()
elif isinstance(value, set):
self._flags = value
elif isinstance(value, list):
self._flags = set(value)
else:
self._flags = set([value])
def extend(self, apply):
options = {}
options.update(self.options)
options.update(apply.options)
flags = self.flags
flags = flags.union(apply.flags)
return Shortcut(apply.name, extends=self.extends, options=options, flags=flags)
<|code_end|>
, generate the next line using the imports in this file:
from therapist.collection import Collection
from therapist.exc import Error
and context (functions, classes, or occasionally code) from other files:
# Path: therapist/collection.py
# class Collection(object):
# """A generic iterable set of objects."""
#
# class Meta:
# pass
#
# def __init__(self, objects=None):
# self._objects = []
#
# if objects:
# for obj in objects:
# self.append(obj)
#
# def __iter__(self):
# return iter(self._objects)
#
# def __getitem__(self, item):
# return self._objects[item]
#
# def __str__(self): # pragma: no cover
# return str(self._objects)
#
# def __repr__(self): # pragma: no cover
# return "<{}>".format(self.__class__.__name__)
#
# def __bool__(self):
# return bool(self._objects)
#
# __nonzero__ = __bool__
#
# @property
# def objects(self):
# return self._objects
#
# def append(self, v):
# object_class = getattr(self.Meta, "object_class", object)
#
# if not isinstance(v, object_class):
# raise TypeError("Expected an instance of `{}`.".format(object_class.__name__))
#
# self._objects.append(v)
#
# Path: therapist/exc.py
# class Error(Exception):
# def __init__(self, message=None, *args, **kwargs):
# self.message = message
# super(Error, self).__init__(*args, **kwargs)
. Output only the next line. | class ShortcutCollection(Collection): |
Here is a snippet: <|code_start|> @property
def flags(self):
return self._flags
@flags.setter
def flags(self, value):
if value is None:
self._flags = set()
elif isinstance(value, set):
self._flags = value
elif isinstance(value, list):
self._flags = set(value)
else:
self._flags = set([value])
def extend(self, apply):
options = {}
options.update(self.options)
options.update(apply.options)
flags = self.flags
flags = flags.union(apply.flags)
return Shortcut(apply.name, extends=self.extends, options=options, flags=flags)
class ShortcutCollection(Collection):
class Meta:
object_class = Shortcut
<|code_end|>
. Write the next line using the current file imports:
from therapist.collection import Collection
from therapist.exc import Error
and context from other files:
# Path: therapist/collection.py
# class Collection(object):
# """A generic iterable set of objects."""
#
# class Meta:
# pass
#
# def __init__(self, objects=None):
# self._objects = []
#
# if objects:
# for obj in objects:
# self.append(obj)
#
# def __iter__(self):
# return iter(self._objects)
#
# def __getitem__(self, item):
# return self._objects[item]
#
# def __str__(self): # pragma: no cover
# return str(self._objects)
#
# def __repr__(self): # pragma: no cover
# return "<{}>".format(self.__class__.__name__)
#
# def __bool__(self):
# return bool(self._objects)
#
# __nonzero__ = __bool__
#
# @property
# def objects(self):
# return self._objects
#
# def append(self, v):
# object_class = getattr(self.Meta, "object_class", object)
#
# if not isinstance(v, object_class):
# raise TypeError("Expected an instance of `{}`.".format(object_class.__name__))
#
# self._objects.append(v)
#
# Path: therapist/exc.py
# class Error(Exception):
# def __init__(self, message=None, *args, **kwargs):
# self.message = message
# super(Error, self).__init__(*args, **kwargs)
, which may include functions, classes, or code. Output only the next line. | class DoesNotExist(Error): |
Based on the snippet: <|code_start|>
class Runner(object):
def __init__(self, cwd, files=None, **kwargs):
# Options from kwargs:
fix = kwargs.get("fix", False)
# Git related options
enable_git = kwargs.get("enable_git", False)
include_unstaged = kwargs.get("include_unstaged", False)
include_untracked = kwargs.get("include_untracked", False)
include_unstaged_changes = kwargs.get("include_unstaged_changes", False)
stage_modified_files = kwargs.get("stage_modified_files", False)
self.cwd = os.path.abspath(cwd)
self.unstaged_changes = False
<|code_end|>
, predict the immediate next line with the help of imports:
import os
from therapist.utils.git import Git, Status
and context (classes, functions, sometimes code) from other files:
# Path: therapist/utils/git/git.py
# class Git(object):
# def __init__(self, cmd=None, repo_path=None):
# self.repo_path = repo_path
# self.current = list(cmd) if cmd else ["git"]
#
# def __call__(self, *args, **kwargs):
# cmd = self.current + to_cli_args(*args, **kwargs)
#
# subprocess_kwargs = {"stdout": subprocess.PIPE, "stderr": subprocess.PIPE}
#
# if self.repo_path:
# subprocess_kwargs["cwd"] = self.repo_path
#
# pipes = subprocess.Popen(cmd, **subprocess_kwargs)
# out, err = pipes.communicate()
# return out.decode("utf-8"), err.decode("utf-8"), pipes.returncode
#
# def __getattr__(self, name):
# name = name.replace("_", "-")
# return Git(self.current + [name], repo_path=self.repo_path)
#
# def __str__(self): # pragma: no cover
# return str(self.current)
#
# def __repr__(self): # pragma: no cover
# return "<Git {}>".format(str(self))
#
# Path: therapist/utils/git/status.py
# class Status(object):
# def __init__(self, status):
# matches = re.search(r"^([MADRCU ?!]{2}) (.+?)(?: -> (.+?))?$", status)
# self.x = matches[1][0]
# self.y = matches[1][1]
# self.path = matches[3] if matches[3] else matches[2]
# self.original_path = matches[2] if matches[3] else None
#
# def __str__(self):
# status = "{}{}".format(self.x, self.y)
# if self.original_path:
# status = "{} {} -> {}".format(status, self.original_path, self.path)
# else:
# status = "{} {}".format(status, self.path)
# return status
#
# def __repr__(self): # pragma: no cover
# return "<Status {}>".format(self.path)
#
# @property
# def is_staged(self):
# return self.x not in (" ", "?", "!")
#
# @property
# def is_untracked(self):
# return self.x == "?"
#
# @property
# def is_ignored(self):
# return self.x == "!"
. Output only the next line. | self.git = Git(repo_path=self.cwd) if enable_git else None |
Given the code snippet: <|code_start|>
class Runner(object):
def __init__(self, cwd, files=None, **kwargs):
# Options from kwargs:
fix = kwargs.get("fix", False)
# Git related options
enable_git = kwargs.get("enable_git", False)
include_unstaged = kwargs.get("include_unstaged", False)
include_untracked = kwargs.get("include_untracked", False)
include_unstaged_changes = kwargs.get("include_unstaged_changes", False)
stage_modified_files = kwargs.get("stage_modified_files", False)
self.cwd = os.path.abspath(cwd)
self.unstaged_changes = False
self.git = Git(repo_path=self.cwd) if enable_git else None
self.include_unstaged_changes = include_unstaged_changes or include_unstaged
self.fix = fix
self.stage_modified_files = stage_modified_files
self.file_mtimes = {}
if files is None:
files = []
if self.git:
untracked_files = "all" if include_untracked else "no"
out, err, code = self.git.status(porcelain=True, untracked_files=untracked_files)
for line in out.splitlines():
<|code_end|>
, generate the next line using the imports in this file:
import os
from therapist.utils.git import Git, Status
and context (functions, classes, or occasionally code) from other files:
# Path: therapist/utils/git/git.py
# class Git(object):
# def __init__(self, cmd=None, repo_path=None):
# self.repo_path = repo_path
# self.current = list(cmd) if cmd else ["git"]
#
# def __call__(self, *args, **kwargs):
# cmd = self.current + to_cli_args(*args, **kwargs)
#
# subprocess_kwargs = {"stdout": subprocess.PIPE, "stderr": subprocess.PIPE}
#
# if self.repo_path:
# subprocess_kwargs["cwd"] = self.repo_path
#
# pipes = subprocess.Popen(cmd, **subprocess_kwargs)
# out, err = pipes.communicate()
# return out.decode("utf-8"), err.decode("utf-8"), pipes.returncode
#
# def __getattr__(self, name):
# name = name.replace("_", "-")
# return Git(self.current + [name], repo_path=self.repo_path)
#
# def __str__(self): # pragma: no cover
# return str(self.current)
#
# def __repr__(self): # pragma: no cover
# return "<Git {}>".format(str(self))
#
# Path: therapist/utils/git/status.py
# class Status(object):
# def __init__(self, status):
# matches = re.search(r"^([MADRCU ?!]{2}) (.+?)(?: -> (.+?))?$", status)
# self.x = matches[1][0]
# self.y = matches[1][1]
# self.path = matches[3] if matches[3] else matches[2]
# self.original_path = matches[2] if matches[3] else None
#
# def __str__(self):
# status = "{}{}".format(self.x, self.y)
# if self.original_path:
# status = "{} {} -> {}".format(status, self.original_path, self.path)
# else:
# status = "{} {}".format(status, self.path)
# return status
#
# def __repr__(self): # pragma: no cover
# return "<Status {}>".format(self.path)
#
# @property
# def is_staged(self):
# return self.x not in (" ", "?", "!")
#
# @property
# def is_untracked(self):
# return self.x == "?"
#
# @property
# def is_ignored(self):
# return self.x == "!"
. Output only the next line. | file_status = Status(line) |
Predict the next line for this snippet: <|code_start|> # open the camera
camera = self.get_camera()
# clear latest image
latest_image = None
while True:
# constantly get the image from the webcam
success_flag, image=camera.read()
# if successful overwrite our latest image
if success_flag:
latest_image = image
# check if the parent wants the image
if imgcap_connection.poll():
recv_obj = imgcap_connection.recv()
# if -1 is received we exit
if recv_obj == -1:
break
# otherwise we return the latest image
imgcap_connection.send(latest_image)
# release camera when exiting
camera.release()
# start_background_capture - starts background image capture
def start_background_capture(self):
# create pipe
<|code_end|>
with the help of current file imports:
import sys
import time
import math
import cv2
import sc_config
from os.path import expanduser
from MAVProxy.modules.lib import multiproc
and context from other files:
# Path: MAVProxy/modules/lib/multiproc.py
# class PipeQueue(object):
# def __init__(self):
# def close(self):
# def put(self, *args):
# def fill(self):
# def get(self):
# def qsize(self):
# def empty(self):
, which may contain function names, class names, or code. Output only the next line. | self.parent_conn, imgcap_conn = multiproc.Pipe() |
Using the snippet: <|code_start|>
class MPMenuCallTextDialog(object):
'''used to create a value dialog callback'''
def __init__(self, title='Enter Value', default=''):
self.title = title
self.default = default
def call(self):
'''show a value dialog'''
try:
dlg = wx.TextEntryDialog(None, self.title, self.title, defaultValue=str(self.default))
except TypeError:
dlg = wx.TextEntryDialog(None, self.title, self.title, value=str(self.default))
if dlg.ShowModal() != wx.ID_OK:
return None
return dlg.GetValue()
class MPMenuChildMessageDialog(object):
'''used to create a message dialog in a child process'''
def __init__(self, title='Information', message='', font_size=18):
self.title = title
self.message = message
self.font_size = font_size
def show(self):
t = multiproc.Process(target=self.call)
t.start()
def call(self):
'''show the dialog as a child process'''
<|code_end|>
, determine the next line of code. You have imports:
from MAVProxy.modules.lib import mp_util
from MAVProxy.modules.lib import multiproc
from MAVProxy.modules.lib.wx_loader import wx
from MAVProxy.modules.lib.wx_loader import wx
from MAVProxy.modules.lib.wx_loader import wx
from MAVProxy.modules.lib.wx_loader import wx
from MAVProxy.modules.lib.wx_loader import wx
from MAVProxy.modules.lib import wx_processguard
from MAVProxy.modules.lib.wx_loader import wx
from wx.lib.agw.genericmessagedialog import GenericMessageDialog
from MAVProxy.modules.lib.mp_image import MPImage
import platform
import webbrowser
import time
and context (class names, function names, or code) available:
# Path: MAVProxy/modules/lib/mp_util.py
# def wrap_360(angle):
# def wrap_180(angle):
# def gps_distance(lat1, lon1, lat2, lon2):
# def gps_bearing(lat1, lon1, lat2, lon2):
# def wrap_valid_longitude(lon):
# def constrain(v, minv, maxv):
# def constrain_latlon(latlon):
# def gps_newpos(lat, lon, bearing, distance):
# def gps_offset(lat, lon, east, north):
# def mkdir_p(dir):
# def polygon_load(filename):
# def polygon_bounds(points):
# def bounds_overlap(bound1, bound2):
# def __init__(self, object, debug=False):
# def degrees_to_dms(degrees):
# def __init__(self, zone, easting, northing, hemisphere='S'):
# def __str__(self):
# def latlon(self):
# def latlon_to_grid(latlon):
# def latlon_round(latlon, spacing=1000):
# def wxToPIL(wimg):
# def PILTowx(pimg):
# def dot_mavproxy(name=None):
# def download_url(url):
# def download_files(files):
# def child_close_fds():
# def child_fd_list_add(fd):
# def child_fd_list_remove(fd):
# def quaternion_to_axis_angle(q):
# def null_term(str):
# def decode_devid(devid, pname):
# def decode_flight_sw_version(flight_sw_version):
# class object_container:
# class UTMGrid:
#
# Path: MAVProxy/modules/lib/multiproc.py
# class PipeQueue(object):
# def __init__(self):
# def close(self):
# def put(self, *args):
# def fill(self):
# def get(self):
# def qsize(self):
# def empty(self):
. Output only the next line. | mp_util.child_close_fds() |
Here is a snippet: <|code_start|> else:
dlg = wx.FileDialog(None, self.title, '', "", self.wildcard, flagsMapped[0]|flagsMapped[1])
if dlg.ShowModal() != wx.ID_OK:
return None
return "\"" + dlg.GetPath() + "\""
class MPMenuCallTextDialog(object):
'''used to create a value dialog callback'''
def __init__(self, title='Enter Value', default=''):
self.title = title
self.default = default
def call(self):
'''show a value dialog'''
try:
dlg = wx.TextEntryDialog(None, self.title, self.title, defaultValue=str(self.default))
except TypeError:
dlg = wx.TextEntryDialog(None, self.title, self.title, value=str(self.default))
if dlg.ShowModal() != wx.ID_OK:
return None
return dlg.GetValue()
class MPMenuChildMessageDialog(object):
'''used to create a message dialog in a child process'''
def __init__(self, title='Information', message='', font_size=18):
self.title = title
self.message = message
self.font_size = font_size
def show(self):
<|code_end|>
. Write the next line using the current file imports:
from MAVProxy.modules.lib import mp_util
from MAVProxy.modules.lib import multiproc
from MAVProxy.modules.lib.wx_loader import wx
from MAVProxy.modules.lib.wx_loader import wx
from MAVProxy.modules.lib.wx_loader import wx
from MAVProxy.modules.lib.wx_loader import wx
from MAVProxy.modules.lib.wx_loader import wx
from MAVProxy.modules.lib import wx_processguard
from MAVProxy.modules.lib.wx_loader import wx
from wx.lib.agw.genericmessagedialog import GenericMessageDialog
from MAVProxy.modules.lib.mp_image import MPImage
import platform
import webbrowser
import time
and context from other files:
# Path: MAVProxy/modules/lib/mp_util.py
# def wrap_360(angle):
# def wrap_180(angle):
# def gps_distance(lat1, lon1, lat2, lon2):
# def gps_bearing(lat1, lon1, lat2, lon2):
# def wrap_valid_longitude(lon):
# def constrain(v, minv, maxv):
# def constrain_latlon(latlon):
# def gps_newpos(lat, lon, bearing, distance):
# def gps_offset(lat, lon, east, north):
# def mkdir_p(dir):
# def polygon_load(filename):
# def polygon_bounds(points):
# def bounds_overlap(bound1, bound2):
# def __init__(self, object, debug=False):
# def degrees_to_dms(degrees):
# def __init__(self, zone, easting, northing, hemisphere='S'):
# def __str__(self):
# def latlon(self):
# def latlon_to_grid(latlon):
# def latlon_round(latlon, spacing=1000):
# def wxToPIL(wimg):
# def PILTowx(pimg):
# def dot_mavproxy(name=None):
# def download_url(url):
# def download_files(files):
# def child_close_fds():
# def child_fd_list_add(fd):
# def child_fd_list_remove(fd):
# def quaternion_to_axis_angle(q):
# def null_term(str):
# def decode_devid(devid, pname):
# def decode_flight_sw_version(flight_sw_version):
# class object_container:
# class UTMGrid:
#
# Path: MAVProxy/modules/lib/multiproc.py
# class PipeQueue(object):
# def __init__(self):
# def close(self):
# def put(self, *args):
# def fill(self):
# def get(self):
# def qsize(self):
# def empty(self):
, which may include functions, classes, or code. Output only the next line. | t = multiproc.Process(target=self.call) |
Predict the next line for this snippet: <|code_start|> self.display_list.SetCellValue(row_changed, PE_VALUE, str(round(newval, 4)))
elif event.Col == PE_VALUE:
newval = float(self.display_list.GetCellValue(row_changed, PE_VALUE))
celleditor = self.display_list.GetCellEditor(row_changed, PE_OPTION)
try:
celleditor.set_checked(newval)
except Exception:
pass
if float(self.oldval) != newval:
self.display_list.SetCellBackgroundColour(row_changed, PE_VALUE,
wx.Colour(152, 251, 152))
self.modified_param[self.display_list.GetCellValue(
row_changed, PE_PARAM)] = newval
self.param_received[self.display_list.GetCellValue(
row_changed, PE_PARAM)] = newval
event.Skip()
def param_help_download(self):
'''download XML files for parameters'''
files = []
for vehicle in ['APMrover2', 'ArduCopter', 'ArduPlane', 'ArduSub', 'AntennaTracker']:
url = 'http://autotest.ardupilot.org/Parameters/%s/apm.pdef.xml' % vehicle
path = mp_util.dot_mavproxy("%s.xml" % vehicle)
files.append((url, path))
url = 'http://autotest.ardupilot.org/%s-defaults.parm' % vehicle
if vehicle != 'AntennaTracker':
# defaults not generated for AntennaTracker ATM
path = mp_util.dot_mavproxy("%s-defaults.parm" % vehicle)
files.append((url, path))
try:
<|code_end|>
with the help of current file imports:
import wx
import wx.grid
import os
import sys
import time
import math
from MAVProxy.modules.lib import multiproc
from MAVProxy.modules.mavproxy_paramedit import checklisteditor as cle
from MAVProxy.modules.lib import mp_util
from MAVProxy.modules.mavproxy_paramedit import ph_event
from lxml import objectify
and context from other files:
# Path: MAVProxy/modules/lib/multiproc.py
# class PipeQueue(object):
# def __init__(self):
# def close(self):
# def put(self, *args):
# def fill(self):
# def get(self):
# def qsize(self):
# def empty(self):
#
# Path: MAVProxy/modules/mavproxy_paramedit/checklisteditor.py
# class GridCheckListEditor(gridlib.PyGridCellEditor):
# class GridDropListEditor(gridlib.PyGridCellEditor):
# class GridScrollEditor(gridlib.PyGridCellEditor):
# def __init__(self, choice, pvalcol, start):
# def set_checked(self, selected):
# def get_checked(self):
# def Create(self, parent, id, evtHandler):
# def SetSize(self, rect):
# def Show(self, show, attr):
# def BeginEdit(self, row, col, grid):
# def EndEdit(self, row, col, grid, oldVal):
# def get_pvalue(self):
# def ApplyEdit(self, row, col, grid):
# def Reset(self):
# def StartingKey(self, evt):
# def Destroy(self):
# def Clone(self):
# def __init__(self, choice, pvalcol, start=0):
# def set_checked(self, selected):
# def get_checked(self):
# def Create(self, parent, id, evtHandler):
# def Show(self, show, attr):
# def SetSize(self, rect):
# def BeginEdit(self, row, col, grid):
# def EndEdit(self, row, col, grid, oldVal):
# def ApplyEdit(self, row, col, grid):
# def Reset(self):
# def StartingKey(self, evt):
# def Destroy(self):
# def Clone(self):
# def __init__(self, Range, pvalcol, start):
# def set_checked(self, selected):
# def SetSize(self, rect):
# def get_checked(self):
# def Create(self, parent, id, evtHandler):
# def Show(self, show, attr):
# def BeginEdit(self, row, col, grid):
# def EndEdit(self, row, col, grid, oldVal):
# def ApplyEdit(self, row, col, grid):
# def Reset(self):
# def StartingKey(self, evt):
# def Destroy(self):
# def Clone(self):
#
# Path: MAVProxy/modules/lib/mp_util.py
# def wrap_360(angle):
# def wrap_180(angle):
# def gps_distance(lat1, lon1, lat2, lon2):
# def gps_bearing(lat1, lon1, lat2, lon2):
# def wrap_valid_longitude(lon):
# def constrain(v, minv, maxv):
# def constrain_latlon(latlon):
# def gps_newpos(lat, lon, bearing, distance):
# def gps_offset(lat, lon, east, north):
# def mkdir_p(dir):
# def polygon_load(filename):
# def polygon_bounds(points):
# def bounds_overlap(bound1, bound2):
# def __init__(self, object, debug=False):
# def degrees_to_dms(degrees):
# def __init__(self, zone, easting, northing, hemisphere='S'):
# def __str__(self):
# def latlon(self):
# def latlon_to_grid(latlon):
# def latlon_round(latlon, spacing=1000):
# def wxToPIL(wimg):
# def PILTowx(pimg):
# def dot_mavproxy(name=None):
# def download_url(url):
# def download_files(files):
# def child_close_fds():
# def child_fd_list_add(fd):
# def child_fd_list_remove(fd):
# def quaternion_to_axis_angle(q):
# def null_term(str):
# def decode_devid(devid, pname):
# def decode_flight_sw_version(flight_sw_version):
# class object_container:
# class UTMGrid:
#
# Path: MAVProxy/modules/mavproxy_paramedit/ph_event.py
# PEE_READ_KEY = 0
# PEE_LOAD_FILE = 1
# PEE_SAVE_FILE = 2
# PEE_READ_PARAM = 3
# PEE_WRITE_PARAM = 4
# PEE_TIME_TO_QUIT = 5
# PEE_RESET = 6
# PEE_FETCH = 7
# PEGE_READ_PARAM = 0
# PEGE_REFRESH_PARAM = 1
# PEGE_WRITE_SUCC = 2
# PEGE_RCIN = 3
# class ParamEditorEvent:
# def __init__(self, type, **kwargs):
# def get_type(self):
# def get_arg(self, key):
, which may contain function names, class names, or code. Output only the next line. | child = multiproc.Process(target=mp_util.download_files, args=(files,)) |
Based on the snippet: <|code_start|> if (self.display_list.GetNumberRows() > 0):
self.display_list.DeleteRows(0, self.display_list.GetNumberRows())
self.display_list.AppendRows(len(datalist))
row = 0
for paramname, paramvalue in sorted(datalist.items()):
self.add_new_row(row, paramname, paramvalue)
row = row + 1
self.display_list.ForceRefresh()
self.last_grid_update = time.time()
def add_new_row(self, row, name, pvalue):
self.display_list.SetCellValue(row, PE_PARAM, str(name))
if self.vehicle_name == 'APMrover2':
fltmode = "MODE"
else:
fltmode = "FLTMODE"
if name == (fltmode + str(self.selected_fltmode)):
self.display_list.SetCellBackgroundColour(row, PE_PARAM, wx.Colour(152, 251, 152))
self.display_list.SetCellValue(row, PE_VALUE, str(round(pvalue, 4)))
unit, option, desc = self.getinfo(name)
self.display_list.SetCellValue(row, PE_UNITS, unit)
self.display_list.SetCellValue(row, PE_DESC, desc)
if (name in [keys for keys, va in self.modified_param.items()]):
self.display_list.SetCellBackgroundColour(row, PE_VALUE,
wx.Colour(152, 251, 152))
self.set_row_size(row)
try:
for f in self.htree[name].field:
if f.get('name') == "Bitmask":
bits = str(f).split(',')
<|code_end|>
, predict the immediate next line with the help of imports:
import wx
import wx.grid
import os
import sys
import time
import math
from MAVProxy.modules.lib import multiproc
from MAVProxy.modules.mavproxy_paramedit import checklisteditor as cle
from MAVProxy.modules.lib import mp_util
from MAVProxy.modules.mavproxy_paramedit import ph_event
from lxml import objectify
and context (classes, functions, sometimes code) from other files:
# Path: MAVProxy/modules/lib/multiproc.py
# class PipeQueue(object):
# def __init__(self):
# def close(self):
# def put(self, *args):
# def fill(self):
# def get(self):
# def qsize(self):
# def empty(self):
#
# Path: MAVProxy/modules/mavproxy_paramedit/checklisteditor.py
# class GridCheckListEditor(gridlib.PyGridCellEditor):
# class GridDropListEditor(gridlib.PyGridCellEditor):
# class GridScrollEditor(gridlib.PyGridCellEditor):
# def __init__(self, choice, pvalcol, start):
# def set_checked(self, selected):
# def get_checked(self):
# def Create(self, parent, id, evtHandler):
# def SetSize(self, rect):
# def Show(self, show, attr):
# def BeginEdit(self, row, col, grid):
# def EndEdit(self, row, col, grid, oldVal):
# def get_pvalue(self):
# def ApplyEdit(self, row, col, grid):
# def Reset(self):
# def StartingKey(self, evt):
# def Destroy(self):
# def Clone(self):
# def __init__(self, choice, pvalcol, start=0):
# def set_checked(self, selected):
# def get_checked(self):
# def Create(self, parent, id, evtHandler):
# def Show(self, show, attr):
# def SetSize(self, rect):
# def BeginEdit(self, row, col, grid):
# def EndEdit(self, row, col, grid, oldVal):
# def ApplyEdit(self, row, col, grid):
# def Reset(self):
# def StartingKey(self, evt):
# def Destroy(self):
# def Clone(self):
# def __init__(self, Range, pvalcol, start):
# def set_checked(self, selected):
# def SetSize(self, rect):
# def get_checked(self):
# def Create(self, parent, id, evtHandler):
# def Show(self, show, attr):
# def BeginEdit(self, row, col, grid):
# def EndEdit(self, row, col, grid, oldVal):
# def ApplyEdit(self, row, col, grid):
# def Reset(self):
# def StartingKey(self, evt):
# def Destroy(self):
# def Clone(self):
#
# Path: MAVProxy/modules/lib/mp_util.py
# def wrap_360(angle):
# def wrap_180(angle):
# def gps_distance(lat1, lon1, lat2, lon2):
# def gps_bearing(lat1, lon1, lat2, lon2):
# def wrap_valid_longitude(lon):
# def constrain(v, minv, maxv):
# def constrain_latlon(latlon):
# def gps_newpos(lat, lon, bearing, distance):
# def gps_offset(lat, lon, east, north):
# def mkdir_p(dir):
# def polygon_load(filename):
# def polygon_bounds(points):
# def bounds_overlap(bound1, bound2):
# def __init__(self, object, debug=False):
# def degrees_to_dms(degrees):
# def __init__(self, zone, easting, northing, hemisphere='S'):
# def __str__(self):
# def latlon(self):
# def latlon_to_grid(latlon):
# def latlon_round(latlon, spacing=1000):
# def wxToPIL(wimg):
# def PILTowx(pimg):
# def dot_mavproxy(name=None):
# def download_url(url):
# def download_files(files):
# def child_close_fds():
# def child_fd_list_add(fd):
# def child_fd_list_remove(fd):
# def quaternion_to_axis_angle(q):
# def null_term(str):
# def decode_devid(devid, pname):
# def decode_flight_sw_version(flight_sw_version):
# class object_container:
# class UTMGrid:
#
# Path: MAVProxy/modules/mavproxy_paramedit/ph_event.py
# PEE_READ_KEY = 0
# PEE_LOAD_FILE = 1
# PEE_SAVE_FILE = 2
# PEE_READ_PARAM = 3
# PEE_WRITE_PARAM = 4
# PEE_TIME_TO_QUIT = 5
# PEE_RESET = 6
# PEE_FETCH = 7
# PEGE_READ_PARAM = 0
# PEGE_REFRESH_PARAM = 1
# PEGE_WRITE_SUCC = 2
# PEGE_RCIN = 3
# class ParamEditorEvent:
# def __init__(self, type, **kwargs):
# def get_type(self):
# def get_arg(self, key):
. Output only the next line. | self.display_list.SetCellEditor(row, PE_OPTION, cle.GridCheckListEditor(bits, PE_VALUE, pvalue)) |
Continue the code snippet: <|code_start|> if param in temp:
temp[param] = value
self.redraw_grid(temp)
def ParamChanged(self, event): # wxGlade: ParamEditor.<event_handler>
row_changed = event.GetRow()
if event.Col == PE_OPTION:
newval = float(self.display_list.GetCellValue(row_changed, PE_VALUE))
self.display_list.SetCellValue(row_changed, PE_VALUE, str(round(newval, 4)))
elif event.Col == PE_VALUE:
newval = float(self.display_list.GetCellValue(row_changed, PE_VALUE))
celleditor = self.display_list.GetCellEditor(row_changed, PE_OPTION)
try:
celleditor.set_checked(newval)
except Exception:
pass
if float(self.oldval) != newval:
self.display_list.SetCellBackgroundColour(row_changed, PE_VALUE,
wx.Colour(152, 251, 152))
self.modified_param[self.display_list.GetCellValue(
row_changed, PE_PARAM)] = newval
self.param_received[self.display_list.GetCellValue(
row_changed, PE_PARAM)] = newval
event.Skip()
def param_help_download(self):
'''download XML files for parameters'''
files = []
for vehicle in ['APMrover2', 'ArduCopter', 'ArduPlane', 'ArduSub', 'AntennaTracker']:
url = 'http://autotest.ardupilot.org/Parameters/%s/apm.pdef.xml' % vehicle
<|code_end|>
. Use current file imports:
import wx
import wx.grid
import os
import sys
import time
import math
from MAVProxy.modules.lib import multiproc
from MAVProxy.modules.mavproxy_paramedit import checklisteditor as cle
from MAVProxy.modules.lib import mp_util
from MAVProxy.modules.mavproxy_paramedit import ph_event
from lxml import objectify
and context (classes, functions, or code) from other files:
# Path: MAVProxy/modules/lib/multiproc.py
# class PipeQueue(object):
# def __init__(self):
# def close(self):
# def put(self, *args):
# def fill(self):
# def get(self):
# def qsize(self):
# def empty(self):
#
# Path: MAVProxy/modules/mavproxy_paramedit/checklisteditor.py
# class GridCheckListEditor(gridlib.PyGridCellEditor):
# class GridDropListEditor(gridlib.PyGridCellEditor):
# class GridScrollEditor(gridlib.PyGridCellEditor):
# def __init__(self, choice, pvalcol, start):
# def set_checked(self, selected):
# def get_checked(self):
# def Create(self, parent, id, evtHandler):
# def SetSize(self, rect):
# def Show(self, show, attr):
# def BeginEdit(self, row, col, grid):
# def EndEdit(self, row, col, grid, oldVal):
# def get_pvalue(self):
# def ApplyEdit(self, row, col, grid):
# def Reset(self):
# def StartingKey(self, evt):
# def Destroy(self):
# def Clone(self):
# def __init__(self, choice, pvalcol, start=0):
# def set_checked(self, selected):
# def get_checked(self):
# def Create(self, parent, id, evtHandler):
# def Show(self, show, attr):
# def SetSize(self, rect):
# def BeginEdit(self, row, col, grid):
# def EndEdit(self, row, col, grid, oldVal):
# def ApplyEdit(self, row, col, grid):
# def Reset(self):
# def StartingKey(self, evt):
# def Destroy(self):
# def Clone(self):
# def __init__(self, Range, pvalcol, start):
# def set_checked(self, selected):
# def SetSize(self, rect):
# def get_checked(self):
# def Create(self, parent, id, evtHandler):
# def Show(self, show, attr):
# def BeginEdit(self, row, col, grid):
# def EndEdit(self, row, col, grid, oldVal):
# def ApplyEdit(self, row, col, grid):
# def Reset(self):
# def StartingKey(self, evt):
# def Destroy(self):
# def Clone(self):
#
# Path: MAVProxy/modules/lib/mp_util.py
# def wrap_360(angle):
# def wrap_180(angle):
# def gps_distance(lat1, lon1, lat2, lon2):
# def gps_bearing(lat1, lon1, lat2, lon2):
# def wrap_valid_longitude(lon):
# def constrain(v, minv, maxv):
# def constrain_latlon(latlon):
# def gps_newpos(lat, lon, bearing, distance):
# def gps_offset(lat, lon, east, north):
# def mkdir_p(dir):
# def polygon_load(filename):
# def polygon_bounds(points):
# def bounds_overlap(bound1, bound2):
# def __init__(self, object, debug=False):
# def degrees_to_dms(degrees):
# def __init__(self, zone, easting, northing, hemisphere='S'):
# def __str__(self):
# def latlon(self):
# def latlon_to_grid(latlon):
# def latlon_round(latlon, spacing=1000):
# def wxToPIL(wimg):
# def PILTowx(pimg):
# def dot_mavproxy(name=None):
# def download_url(url):
# def download_files(files):
# def child_close_fds():
# def child_fd_list_add(fd):
# def child_fd_list_remove(fd):
# def quaternion_to_axis_angle(q):
# def null_term(str):
# def decode_devid(devid, pname):
# def decode_flight_sw_version(flight_sw_version):
# class object_container:
# class UTMGrid:
#
# Path: MAVProxy/modules/mavproxy_paramedit/ph_event.py
# PEE_READ_KEY = 0
# PEE_LOAD_FILE = 1
# PEE_SAVE_FILE = 2
# PEE_READ_PARAM = 3
# PEE_WRITE_PARAM = 4
# PEE_TIME_TO_QUIT = 5
# PEE_RESET = 6
# PEE_FETCH = 7
# PEGE_READ_PARAM = 0
# PEGE_REFRESH_PARAM = 1
# PEGE_WRITE_SUCC = 2
# PEGE_RCIN = 3
# class ParamEditorEvent:
# def __init__(self, type, **kwargs):
# def get_type(self):
# def get_arg(self, key):
. Output only the next line. | path = mp_util.dot_mavproxy("%s.xml" % vehicle) |
Continue the code snippet: <|code_start|>
class ParamHelp:
def __init__(self):
self.xml_filepath = None
self.vehicle_name = None
self.last_pair = (None,None)
self.last_htree = None
def param_help_download(self):
'''download XML files for parameters'''
files = []
for vehicle in ['Rover', 'ArduCopter', 'ArduPlane', 'ArduSub', 'AntennaTracker']:
url = 'http://autotest.ardupilot.org/Parameters/%s/apm.pdef.xml.gz' % vehicle
<|code_end|>
. Use current file imports:
import time, os
from pymavlink import mavutil, mavparm
from MAVProxy.modules.lib import mp_util
from MAVProxy.modules.lib import multiproc
from lxml import objectify
and context (classes, functions, or code) from other files:
# Path: MAVProxy/modules/lib/mp_util.py
# def wrap_360(angle):
# def wrap_180(angle):
# def gps_distance(lat1, lon1, lat2, lon2):
# def gps_bearing(lat1, lon1, lat2, lon2):
# def wrap_valid_longitude(lon):
# def constrain(v, minv, maxv):
# def constrain_latlon(latlon):
# def gps_newpos(lat, lon, bearing, distance):
# def gps_offset(lat, lon, east, north):
# def mkdir_p(dir):
# def polygon_load(filename):
# def polygon_bounds(points):
# def bounds_overlap(bound1, bound2):
# def __init__(self, object, debug=False):
# def degrees_to_dms(degrees):
# def __init__(self, zone, easting, northing, hemisphere='S'):
# def __str__(self):
# def latlon(self):
# def latlon_to_grid(latlon):
# def latlon_round(latlon, spacing=1000):
# def wxToPIL(wimg):
# def PILTowx(pimg):
# def dot_mavproxy(name=None):
# def download_url(url):
# def download_files(files):
# def child_close_fds():
# def child_fd_list_add(fd):
# def child_fd_list_remove(fd):
# def quaternion_to_axis_angle(q):
# def null_term(str):
# def decode_devid(devid, pname):
# def decode_flight_sw_version(flight_sw_version):
# class object_container:
# class UTMGrid:
#
# Path: MAVProxy/modules/lib/multiproc.py
# class PipeQueue(object):
# def __init__(self):
# def close(self):
# def put(self, *args):
# def fill(self):
# def get(self):
# def qsize(self):
# def empty(self):
. Output only the next line. | path = mp_util.dot_mavproxy("%s.xml" % vehicle) |
Given the code snippet: <|code_start|>
class ParamHelp:
def __init__(self):
self.xml_filepath = None
self.vehicle_name = None
self.last_pair = (None,None)
self.last_htree = None
def param_help_download(self):
'''download XML files for parameters'''
files = []
for vehicle in ['Rover', 'ArduCopter', 'ArduPlane', 'ArduSub', 'AntennaTracker']:
url = 'http://autotest.ardupilot.org/Parameters/%s/apm.pdef.xml.gz' % vehicle
path = mp_util.dot_mavproxy("%s.xml" % vehicle)
files.append((url, path))
url = 'http://autotest.ardupilot.org/%s-defaults.parm' % vehicle
if vehicle != 'AntennaTracker':
# defaults not generated for AntennaTracker ATM
path = mp_util.dot_mavproxy("%s-defaults.parm" % vehicle)
files.append((url, path))
try:
<|code_end|>
, generate the next line using the imports in this file:
import time, os
from pymavlink import mavutil, mavparm
from MAVProxy.modules.lib import mp_util
from MAVProxy.modules.lib import multiproc
from lxml import objectify
and context (functions, classes, or occasionally code) from other files:
# Path: MAVProxy/modules/lib/mp_util.py
# def wrap_360(angle):
# def wrap_180(angle):
# def gps_distance(lat1, lon1, lat2, lon2):
# def gps_bearing(lat1, lon1, lat2, lon2):
# def wrap_valid_longitude(lon):
# def constrain(v, minv, maxv):
# def constrain_latlon(latlon):
# def gps_newpos(lat, lon, bearing, distance):
# def gps_offset(lat, lon, east, north):
# def mkdir_p(dir):
# def polygon_load(filename):
# def polygon_bounds(points):
# def bounds_overlap(bound1, bound2):
# def __init__(self, object, debug=False):
# def degrees_to_dms(degrees):
# def __init__(self, zone, easting, northing, hemisphere='S'):
# def __str__(self):
# def latlon(self):
# def latlon_to_grid(latlon):
# def latlon_round(latlon, spacing=1000):
# def wxToPIL(wimg):
# def PILTowx(pimg):
# def dot_mavproxy(name=None):
# def download_url(url):
# def download_files(files):
# def child_close_fds():
# def child_fd_list_add(fd):
# def child_fd_list_remove(fd):
# def quaternion_to_axis_angle(q):
# def null_term(str):
# def decode_devid(devid, pname):
# def decode_flight_sw_version(flight_sw_version):
# class object_container:
# class UTMGrid:
#
# Path: MAVProxy/modules/lib/multiproc.py
# class PipeQueue(object):
# def __init__(self):
# def close(self):
# def put(self, *args):
# def fill(self):
# def get(self):
# def qsize(self):
# def empty(self):
. Output only the next line. | child = multiproc.Process(target=mp_util.download_files, args=(files,)) |
Continue the code snippet: <|code_start|>
def __getitem__(self, a):
return str(getattr(self, a))
class TileInfo:
'''description of a tile'''
def __init__(self, tile, zoom, service, offset=(0,0)):
self.tile = tile
(self.x, self.y) = tile
self.zoom = zoom
self.service = service
(self.offsetx, self.offsety) = offset
self.refresh_time()
def key(self):
'''tile cache key'''
return (self.tile, self.zoom, self.service)
def refresh_time(self):
'''reset the request time'''
self.request_time = time.time()
def coord(self, offset=(0,0)):
'''return lat,lon within a tile given (offsetx,offsety)'''
(tilex, tiley) = self.tile
(offsetx, offsety) = offset
world_tiles = 1<<self.zoom
x = ( tilex + 1.0*offsetx/TILES_WIDTH ) / (world_tiles/2.) - 1
y = ( tiley + 1.0*offsety/TILES_HEIGHT) / (world_tiles/2.) - 1
<|code_end|>
. Use current file imports:
import collections
import errno
import hashlib
import sys
import math
import threading
import os
import string
import time
import cv2
import numpy as np
import tempfile
import ordereddict
import pkg_resources
import pkgutil
from math import log, tan, radians, degrees, sin, cos, exp, pi, asin, atan
from urllib2 import Request as url_request
from urllib2 import urlopen as url_open
from urllib2 import URLError as url_error
from urllib.request import Request as url_request
from urllib.request import urlopen as url_open
from urllib.error import URLError as url_error
from MAVProxy.modules.lib import mp_util
from optparse import OptionParser
and context (classes, functions, or code) from other files:
# Path: MAVProxy/modules/lib/mp_util.py
# def wrap_360(angle):
# def wrap_180(angle):
# def gps_distance(lat1, lon1, lat2, lon2):
# def gps_bearing(lat1, lon1, lat2, lon2):
# def wrap_valid_longitude(lon):
# def constrain(v, minv, maxv):
# def constrain_latlon(latlon):
# def gps_newpos(lat, lon, bearing, distance):
# def gps_offset(lat, lon, east, north):
# def mkdir_p(dir):
# def polygon_load(filename):
# def polygon_bounds(points):
# def bounds_overlap(bound1, bound2):
# def __init__(self, object, debug=False):
# def degrees_to_dms(degrees):
# def __init__(self, zone, easting, northing, hemisphere='S'):
# def __str__(self):
# def latlon(self):
# def latlon_to_grid(latlon):
# def latlon_round(latlon, spacing=1000):
# def wxToPIL(wimg):
# def PILTowx(pimg):
# def dot_mavproxy(name=None):
# def download_url(url):
# def download_files(files):
# def child_close_fds():
# def child_fd_list_add(fd):
# def child_fd_list_remove(fd):
# def quaternion_to_axis_angle(q):
# def null_term(str):
# def decode_devid(devid, pname):
# def decode_flight_sw_version(flight_sw_version):
# class object_container:
# class UTMGrid:
. Output only the next line. | lon = mp_util.wrap_180(x * 180.0) |
Next line prediction: <|code_start|>def set_wx_window_layout(wx_window, layout):
'''set a WinLayout for a wx window'''
try:
wx_window.SetSize(layout.size)
wx_window.SetPosition(layout.pos)
except Exception as ex:
print(ex)
def set_layout(wlayout, callback):
'''set window layout'''
global display_size
global window_list
global loaded_layout
global pending_load
global vehiclename
#if not wlayout.name in window_list:
# print("layout %s" % wlayout)
if not wlayout.name in window_list and loaded_layout is not None and wlayout.name in loaded_layout:
callback(loaded_layout[wlayout.name])
window_list[wlayout.name] = ManagedWindow(wlayout, callback)
display_size = wlayout.dsize
if pending_load:
pending_load = False
load_layout(vehiclename)
def layout_filename(fallback):
'''get location of layout file'''
global display_size
global vehiclename
(dw,dh) = display_size
<|code_end|>
. Use current file imports:
(import os, wx, pickle
from MAVProxy.modules.lib import mp_util)
and context including class names, function names, or small code snippets from other files:
# Path: MAVProxy/modules/lib/mp_util.py
# def wrap_360(angle):
# def wrap_180(angle):
# def gps_distance(lat1, lon1, lat2, lon2):
# def gps_bearing(lat1, lon1, lat2, lon2):
# def wrap_valid_longitude(lon):
# def constrain(v, minv, maxv):
# def constrain_latlon(latlon):
# def gps_newpos(lat, lon, bearing, distance):
# def gps_offset(lat, lon, east, north):
# def mkdir_p(dir):
# def polygon_load(filename):
# def polygon_bounds(points):
# def bounds_overlap(bound1, bound2):
# def __init__(self, object, debug=False):
# def degrees_to_dms(degrees):
# def __init__(self, zone, easting, northing, hemisphere='S'):
# def __str__(self):
# def latlon(self):
# def latlon_to_grid(latlon):
# def latlon_round(latlon, spacing=1000):
# def wxToPIL(wimg):
# def PILTowx(pimg):
# def dot_mavproxy(name=None):
# def download_url(url):
# def download_files(files):
# def child_close_fds():
# def child_fd_list_add(fd):
# def child_fd_list_remove(fd):
# def quaternion_to_axis_angle(q):
# def null_term(str):
# def decode_devid(devid, pname):
# def decode_flight_sw_version(flight_sw_version):
# class object_container:
# class UTMGrid:
. Output only the next line. | dirname = mp_util.dot_mavproxy() |
Given snippet: <|code_start|> """
def __init__(self,resultsdir,**kwargs):
self.resultsdir = resultsdir
self.plotlist = {} #collections.OrderedDict
self.error = {}
self.name = self.resultsdir.split('/')[-2]
# Check directory exists before instantiating object and check
# which files associated with plots are in directory
self.potentialfiles = ( "continuum_vbins", "continuum_tau_xx",
"continuum_tau_xy","continuum_tau_yx",
"continuum_tau_yy")
if (not os.path.isdir(self.resultsdir)):
print(("Directory " + self.resultsdir + " not found"))
raise IOError
self.fields_present = []
for fname in self.potentialfiles:
if (glob.glob(self.resultsdir+fname)):
self.fields_present.append(fname)
if (glob.glob(self.resultsdir+fname+'.*')):
self.fields_present.append(fname.strip().split('.')[0])
self.fieldfiles1 = list(set(self.fields_present) & set(self.potentialfiles))
try:
Header1 = Serial_CFD_HeaderData(self.resultsdir)
except IOError:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import numpy as np
import sys
import math as maths
import glob
from .serial_cfdfields import *
from .headerdata import *
from .postproc import PostProc
from .pplexceptions import NoResultsInDir
and context:
# Path: postproclib/postproc.py
# class PostProc:
#
# def __str__(self):
# string = ('\nAvailable outputs in ' + self.resultsdir + ' include:\n\n')
# string += ('\t{0:^24s}\t{1:>10s}\n'.format('field', 'records'))
# #string += ('\t{0:^24s}\t{1:^10s}\n'.format('-'*24, '-'*10))
# for key,field in sorted(self.plotlist.items()):
# line = '\t{0:<24s}=\t{1:>10f},\n'.format(key, field.maxrec)
# string += line
# return string
#
# Path: postproclib/pplexceptions.py
# class NoResultsInDir(Exception):
# pass
which might include code, classes, or functions. Output only the next line. | raise NoResultsInDir |
Predict the next line after this snippet: <|code_start|>
This will instantiate a velocity field (see MDFields for details of
the complex inheritance and containment), read and store the data
from multiple files to construct a velocity profile, and finally
will plot the x-component of velocity against the y-axis.
In line with RawData readers, axes correspond to:
[ spatial ax1, spatial ax2, spatial ax3, record, component ]
[ 0 , 1 , 2 , 3 , 4 (&-1) ]
"""
def __init__(self, RawDataObj):
self.Raw = RawDataObj
self.fdir = self.Raw.fdir
self.grid = self.Raw.grid
self.maxrec = self.Raw.maxrec
def read(self,startrec,endrec,**kwargs):
"""
TO BE OVERRIDDEN IN COMPLICATED FIELDS.
Method that returns grid data that is read by Raw.
"""
if (endrec > self.maxrec):
print(('Record ' + str(endrec) + ' is greater than the maximum '
'available (' + str(self.maxrec) + ').'))
<|code_end|>
using the current file's imports:
import numpy as np
import sys
import scipy.interpolate as interp
import matplotlib.pyplot as plt
import scipy.interpolate as interp
import scipy.ndimage
from .pplexceptions import OutsideRecRange
from scipy.interpolate import RegularGridInterpolator
and any relevant context from other files:
# Path: postproclib/pplexceptions.py
# class OutsideRecRange(Exception):
# pass
. Output only the next line. | raise OutsideRecRange |
Predict the next line for this snippet: <|code_start|> os.chdir(self.savedPath )
class VmdReformat:
def __init__(self, fdir, fname, scriptdir):
self.fdir = fdir
self.fname = fname
self.scriptdir = scriptdir
self.Reformatted = False
headerfile = self.fdir + 'simulation_header'
# Extract np from header
fobj = open(headerfile,'r')
self.np = 0
while self.np==0:
line = fobj.readline().split(';')
if (line[1].strip() == 'globalnp'):
self.np = int(line[2].strip())
self.domain = [0, 0, 0]
for ixyz in range(3):
while self.domain[ixyz]==0:
line = fobj.readline().split(';')
if (line[1].strip() == 'globaldomain(' + str(ixyz+1) + ')'):
self.domain[ixyz] = float(line[2].strip())
if not os.path.isfile(self.scriptdir + 'vmd_reformat.f90'):
print('Error -- vmd_reformat.f90 is missing from ' + self.scriptdir)
<|code_end|>
with the help of current file imports:
import os
from .pplexceptions import ScriptMissing
and context from other files:
# Path: postproclib/pplexceptions.py
# class ScriptMissing(Exception):
# pass
, which may contain function names, class names, or code. Output only the next line. | raise ScriptMissing |
Given snippet: <|code_start|>
class channelflow_PostProc(PostProc):
"""
Post processing class for channelflow runs
"""
def __init__(self,resultsdir,**kwargs):
self.resultsdir = resultsdir
self.plotlist = {}
# Check directory exists before instantiating object and check
# which files associated with plots are in directory
if (not os.path.isdir(self.resultsdir)):
print(("Directory " + self.resultsdir + " not found"))
raise IOError
possibles = {'channelflow Velocity': Channelflow_vField,
'Channelflow strain': Channelflow_strainField,
'Channelflow uu': Channelflow_uuField,
'Channelflow vorticity': Channelflow_vortField,
'Channelflow Dissipation': Channelflow_dissipField}
if (not glob.glob(self.resultsdir+'*.h5')):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import glob
from .channelflowfields import *
from .postproc import PostProc
from .pplexceptions import NoResultsInDir
and context:
# Path: postproclib/postproc.py
# class PostProc:
#
# def __str__(self):
# string = ('\nAvailable outputs in ' + self.resultsdir + ' include:\n\n')
# string += ('\t{0:^24s}\t{1:>10s}\n'.format('field', 'records'))
# #string += ('\t{0:^24s}\t{1:^10s}\n'.format('-'*24, '-'*10))
# for key,field in sorted(self.plotlist.items()):
# line = '\t{0:<24s}=\t{1:>10f},\n'.format(key, field.maxrec)
# string += line
# return string
#
# Path: postproclib/pplexceptions.py
# class NoResultsInDir(Exception):
# pass
which might include code, classes, or functions. Output only the next line. | raise NoResultsInDir |
Next line prediction: <|code_start|> 'Density': LAMMPS_dField,
'Velocity': LAMMPS_vField,
'Momentum': LAMMPS_momField,
'Temperature': LAMMPS_TField,
'Pressure': LAMMPS_PressureField,
'Shear Stess': LAMMPS_ShearStressField,
'Kinetic Energy': LAMMPS_KineticEnergyField,
'Potential Energy': LAMMPS_PotentialEnergyField,
'Total Energy': LAMMPS_TotalEnergyField
}
#Try to get fnames from log.lammps
fname = ""
logfile = self.resultsdir + "/log.lammps"
if (os.path.isfile(logfile)):
with open(logfile, "r") as f:
n = "3dgrid"
for l in f:
if ("chunk/atom bin/3d") in l:
n=l.split()[1]
if n in l and "ave/chunk" in l:
indx = l.find("file")
if indx != -1:
fname = l[indx:].split()[1]
else:
print(("logfile ", logfile, " appears to be corrupted " +
"so cannot determine output filename"))
else:
#print(("logfile ", logfile, " not found"))
<|code_end|>
. Use current file imports:
(import os
from .lammpsfields import *
from .postproc import PostProc
from .pplexceptions import NoResultsInDir )
and context including class names, function names, or small code snippets from other files:
# Path: postproclib/postproc.py
# class PostProc:
#
# def __str__(self):
# string = ('\nAvailable outputs in ' + self.resultsdir + ' include:\n\n')
# string += ('\t{0:^24s}\t{1:>10s}\n'.format('field', 'records'))
# #string += ('\t{0:^24s}\t{1:^10s}\n'.format('-'*24, '-'*10))
# for key,field in sorted(self.plotlist.items()):
# line = '\t{0:<24s}=\t{1:>10f},\n'.format(key, field.maxrec)
# string += line
# return string
#
# Path: postproclib/pplexceptions.py
# class NoResultsInDir(Exception):
# pass
. Output only the next line. | raise NoResultsInDir |
Predict the next line for this snippet: <|code_start|>
class CFD_PostProc(PostProc):
"""
Post processing class for CFD runs
"""
def __init__(self,resultsdir,**kwargs):
self.resultsdir = resultsdir
self.plotlist = {}
# Check directory exists before instantiating object and check
# which files associated with plots are in directory
if (not os.path.isdir(self.resultsdir)):
print(("Directory " + self.resultsdir + " not found"))
raise IOError
try:
fobj = open(self.resultsdir + 'report','r')
except IOError:
<|code_end|>
with the help of current file imports:
import os
from .cfdfields import *
from .postproc import PostProc
from .pplexceptions import NoResultsInDir
and context from other files:
# Path: postproclib/postproc.py
# class PostProc:
#
# def __str__(self):
# string = ('\nAvailable outputs in ' + self.resultsdir + ' include:\n\n')
# string += ('\t{0:^24s}\t{1:>10s}\n'.format('field', 'records'))
# #string += ('\t{0:^24s}\t{1:^10s}\n'.format('-'*24, '-'*10))
# for key,field in sorted(self.plotlist.items()):
# line = '\t{0:<24s}=\t{1:>10f},\n'.format(key, field.maxrec)
# string += line
# return string
#
# Path: postproclib/pplexceptions.py
# class NoResultsInDir(Exception):
# pass
, which may contain function names, class names, or code. Output only the next line. | raise NoResultsInDir |
Given the code snippet: <|code_start|> if ("controlDict" in files):
controlDictfound = True
with open(root+"/controlDict") as f:
for line in f:
try:
if "writeControl" in line:
writecontrol = (line.replace("\t"," ")
.replace(";","")
.replace("\n","")
.split(" ")[-1])
if "writeInterval" in line:
writeInterval = float(line.replace("\t"," ")
.replace(";","")
.replace("\n","")
.split(" ")[-1])
if "deltaT" in line:
deltaT = float(line.replace("\t"," ")
.replace(";","")
.replace("\n","")
.split(" ")[-1])
except ValueError:
print(("Convert failed in OpenFOAM_reader", line))
if "processor" in root and not parallel_run:
parallel_run = True
print(("Assuming parallel run as processor folder found in " + self.resultsdir))
#Check if data files exist
if not controlDictfound:
<|code_end|>
, generate the next line using the imports in this file:
import os
import glob
from .openfoamfields import *
from .postproc import PostProc
from .pplexceptions import NoResultsInDir
and context (functions, classes, or occasionally code) from other files:
# Path: postproclib/postproc.py
# class PostProc:
#
# def __str__(self):
# string = ('\nAvailable outputs in ' + self.resultsdir + ' include:\n\n')
# string += ('\t{0:^24s}\t{1:>10s}\n'.format('field', 'records'))
# #string += ('\t{0:^24s}\t{1:^10s}\n'.format('-'*24, '-'*10))
# for key,field in sorted(self.plotlist.items()):
# line = '\t{0:<24s}=\t{1:>10f},\n'.format(key, field.maxrec)
# string += line
# return string
#
# Path: postproclib/pplexceptions.py
# class NoResultsInDir(Exception):
# pass
. Output only the next line. | raise NoResultsInDir |
Here is a snippet: <|code_start|> #First two records are positions in y and z
rec_ = rec+3
# plot ! note the parent parameter
x = []; y = []; z = []
for i in range(nz):
if (i%2 == 0):
d = -1
else:
d = 1
x.append(r[rec_,::d,i])
y.append(r[0,::d,i])
z.append(r[1,::d,i])
for j in range(ny):
if (j%2 == 0):
d = -1
else:
d = 1
x.append(r[rec_,j,::d])
y.append(r[0,j,::d])
z.append(r[1,j,::d,])
x = np.array(x)#.ravel()
y = np.array(y)#.ravel()
z = np.array(z)#.ravel()
return x, y, z
<|code_end|>
. Write the next line using the current file imports:
import numpy as np
import os
import struct
import glob
import matplotlib.pyplot as plt
from scipy.io import FortranFile
from .headerdata import *
from .postproc import PostProc
from .pplexceptions import NoResultsInDir
from mpl_toolkits import mplot3d
and context from other files:
# Path: postproclib/postproc.py
# class PostProc:
#
# def __str__(self):
# string = ('\nAvailable outputs in ' + self.resultsdir + ' include:\n\n')
# string += ('\t{0:^24s}\t{1:>10s}\n'.format('field', 'records'))
# #string += ('\t{0:^24s}\t{1:^10s}\n'.format('-'*24, '-'*10))
# for key,field in sorted(self.plotlist.items()):
# line = '\t{0:<24s}=\t{1:>10f},\n'.format(key, field.maxrec)
# string += line
# return string
#
# Path: postproclib/pplexceptions.py
# class NoResultsInDir(Exception):
# pass
, which may include functions, classes, or code. Output only the next line. | class MolAllPostProc(PostProc): |
Next line prediction: <|code_start|>class MolAllPostProc(PostProc):
def __init__(self, resultsdir, **kwargs):
self.resultsdir = resultsdir
self.plotlist = {} #collections.OrderedDict
self.error = {}
self.name = self.resultsdir.split('/')[-2]
# Check directory exists before instantiating object and check
# which files associated with plots are in directory
self.potentialfiles = ( "final_state", "initial_state",
"vmd_out.dcd","vmd_temp.dcd",
"all_cluster.xyz", "surface.xyz")
if (not os.path.isdir(self.resultsdir)):
print(("Directory " + self.resultsdir + " not found"))
raise IOError
self.fields_present = []
for fname in self.potentialfiles:
if (glob.glob(self.resultsdir+fname)):
self.fields_present.append(fname)
if (glob.glob(self.resultsdir+fname+'.*')):
self.fields_present.append(fname.strip().split('.')[0])
self.fieldfiles1 = list(set(self.fields_present) & set(self.potentialfiles))
try:
Header1 = MDHeaderData(self.resultsdir)
except IOError:
<|code_end|>
. Use current file imports:
(import numpy as np
import os
import struct
import glob
import matplotlib.pyplot as plt
from scipy.io import FortranFile
from .headerdata import *
from .postproc import PostProc
from .pplexceptions import NoResultsInDir
from mpl_toolkits import mplot3d)
and context including class names, function names, or small code snippets from other files:
# Path: postproclib/postproc.py
# class PostProc:
#
# def __str__(self):
# string = ('\nAvailable outputs in ' + self.resultsdir + ' include:\n\n')
# string += ('\t{0:^24s}\t{1:>10s}\n'.format('field', 'records'))
# #string += ('\t{0:^24s}\t{1:^10s}\n'.format('-'*24, '-'*10))
# for key,field in sorted(self.plotlist.items()):
# line = '\t{0:<24s}=\t{1:>10f},\n'.format(key, field.maxrec)
# string += line
# return string
#
# Path: postproclib/pplexceptions.py
# class NoResultsInDir(Exception):
# pass
. Output only the next line. | raise NoResultsInDir |
Given the code snippet: <|code_start|> self.error = {}
self.name = self.resultsdir.split('/')[-2]
# Check directory exists before instantiating object and check
# which files associated with plots are in directory
self.potentialfiles = ( "mslice", "mbins", "msnap","vslice", "vbins",
"vsnap","pvirial", "pVA", "pVA_k","pVA_c",
"visc", "mflux","vflux", "pplane", "psurface",
"esnap", "eflux", "eplane","esurface", "Fvext",
"viscometrics", "rdf", "rdf3d", "ssf", "Fext",
"Tbins", "vPDF", "msolv", "mpoly", "vsolv",
"vpoly", "ebins","hfVA","hfVA_k","hfVA_c",
"msurf", "dsurf_mflux", "dsurf_vflux", "combin", "P")
if (not os.path.isdir(self.resultsdir)):
print(("Directory " + self.resultsdir + " not found"))
raise IOError
self.fields_present = []
for fname in self.potentialfiles:
if (glob.glob(self.resultsdir+fname)):
self.fields_present.append(fname)
if (glob.glob(self.resultsdir+fname+'.*')):
self.fields_present.append(fname.strip().split('.')[0])
self.fieldfiles1 = list(set(self.fields_present) & set(self.potentialfiles))
try:
Header1 = MDHeaderData(self.resultsdir)
except IOError:
<|code_end|>
, generate the next line using the imports in this file:
import os
import numpy as np
import sys
import math as maths
import glob
from .mdfields import *
from .headerdata import *
from .postproc import PostProc
from .pplexceptions import NoResultsInDir, DataMismatch
and context (functions, classes, or occasionally code) from other files:
# Path: postproclib/postproc.py
# class PostProc:
#
# def __str__(self):
# string = ('\nAvailable outputs in ' + self.resultsdir + ' include:\n\n')
# string += ('\t{0:^24s}\t{1:>10s}\n'.format('field', 'records'))
# #string += ('\t{0:^24s}\t{1:^10s}\n'.format('-'*24, '-'*10))
# for key,field in sorted(self.plotlist.items()):
# line = '\t{0:<24s}=\t{1:>10f},\n'.format(key, field.maxrec)
# string += line
# return string
#
# Path: postproclib/pplexceptions.py
# class NoResultsInDir(Exception):
# pass
#
# class DataMismatch(Exception):
# pass
. Output only the next line. | raise NoResultsInDir |
Given the code snippet: <|code_start|> P1 = MD_hfVAField(self.resultsdir,fname='hfVA_c', **kwargs)
self.plotlist.update({'hfVA_c':P1})
except DataNotAvailable:
pass
if (('hfVA' in self.fieldfiles1) or
('hfVA_k' in self.fieldfiles1 and
'hfVA_c' in self.fieldfiles1 )):
try:
P1 = MD_heatfluxVAField(self.resultsdir,fname='hfVA', **kwargs)
self.plotlist.update({'q':P1})
except DataNotAvailable:
pass
#CV fluxes
if 'mflux' in (self.fieldfiles1):
flux1 = MD_mfluxField(self.resultsdir,'mflux', **kwargs)
self.plotlist.update({'mflux':flux1})
rhouCV = MD_CVmomField(self.resultsdir)
self.plotlist.update({'rhou CV':rhouCV})
if (('mflux' in self.fieldfiles1) and
('vbins' in self.fieldfiles1) ):
rhouuCV = MD_rhouuCVField(self.resultsdir)
self.plotlist.update({'rhouu CV':rhouuCV})
if (('mflux' in self.fieldfiles1) and
('msurf' in self.fieldfiles1) ):
try:
uCV = MD_CVvField(self.resultsdir)
self.plotlist.update({'u CV':uCV})
<|code_end|>
, generate the next line using the imports in this file:
import os
import numpy as np
import sys
import math as maths
import glob
from .mdfields import *
from .headerdata import *
from .postproc import PostProc
from .pplexceptions import NoResultsInDir, DataMismatch
and context (functions, classes, or occasionally code) from other files:
# Path: postproclib/postproc.py
# class PostProc:
#
# def __str__(self):
# string = ('\nAvailable outputs in ' + self.resultsdir + ' include:\n\n')
# string += ('\t{0:^24s}\t{1:>10s}\n'.format('field', 'records'))
# #string += ('\t{0:^24s}\t{1:^10s}\n'.format('-'*24, '-'*10))
# for key,field in sorted(self.plotlist.items()):
# line = '\t{0:<24s}=\t{1:>10f},\n'.format(key, field.maxrec)
# string += line
# return string
#
# Path: postproclib/pplexceptions.py
# class NoResultsInDir(Exception):
# pass
#
# class DataMismatch(Exception):
# pass
. Output only the next line. | except DataMismatch: |
Based on the snippet: <|code_start|> lines.append(' # OPTIONAL: add posts to your organizaion using this format,')
lines.append(' # where label is a human-readable description of the post '
'(eg "Ward 8 councilmember")')
lines.append(' # and role is the position type (eg councilmember, alderman, mayor...)')
lines.append(' # skip entirely if you\'re not writing a people scraper.')
lines.append(' org.add_post(label="position_description", role="position_type")')
lines.append('')
lines.append(' #REQUIRED: yield the organization')
lines.append(' yield org')
lines.append('')
with open(os.path.join(dirname, '__init__.py'), 'w') as of:
of.write('\n'.join(lines))
# write scraper files
for stype in scraper_types:
lines = ['from pupa.scrape import Scraper']
lines.append('from pupa.scrape import {}'.format(CLASS_DICT[stype]))
lines.append('')
lines.append('')
lines.append('class {}{}Scraper(Scraper):'.format(camel_case, CLASS_DICT[stype]))
lines.append('')
lines.append(' def scrape(self):')
lines.append(' # needs to be implemented')
lines.append(' pass')
lines.append('')
with open(os.path.join(dirname, stype + '.py'), 'w') as of:
of.write('\n'.join(lines))
<|code_end|>
, predict the immediate next line with the help of imports:
import os
from .base import BaseCommand
from pupa.exceptions import CommandError
from opencivicdata.common import JURISDICTION_CLASSIFICATIONS
from opencivicdata.divisions import Division
and context (classes, functions, sometimes code) from other files:
# Path: pupa/cli/commands/base.py
# class BaseCommand(object):
#
# def __init__(self, subparsers):
# self.subparser = subparsers.add_parser(self.name, description=self.help)
# self.add_args()
#
# def add_args(self):
# pass
#
# def add_argument(self, *args, **kwargs):
# self.subparser.add_argument(*args, **kwargs)
#
# def handle(self, args):
# raise NotImplementedError('commands must implement handle(args)')
#
# Path: pupa/exceptions.py
# class CommandError(PupaError):
# """ Errors from within pupa CLI """
. Output only the next line. | class Command(BaseCommand): |
Continue the code snippet: <|code_start|> lines.append('')
with open(os.path.join(dirname, '__init__.py'), 'w') as of:
of.write('\n'.join(lines))
# write scraper files
for stype in scraper_types:
lines = ['from pupa.scrape import Scraper']
lines.append('from pupa.scrape import {}'.format(CLASS_DICT[stype]))
lines.append('')
lines.append('')
lines.append('class {}{}Scraper(Scraper):'.format(camel_case, CLASS_DICT[stype]))
lines.append('')
lines.append(' def scrape(self):')
lines.append(' # needs to be implemented')
lines.append(' pass')
lines.append('')
with open(os.path.join(dirname, stype + '.py'), 'w') as of:
of.write('\n'.join(lines))
class Command(BaseCommand):
name = 'init'
help = 'start a new pupa scraper'
def add_args(self):
self.add_argument('module', type=str, help='name of the new scraper module')
def handle(self, args, other):
if os.path.exists(args.module):
<|code_end|>
. Use current file imports:
import os
from .base import BaseCommand
from pupa.exceptions import CommandError
from opencivicdata.common import JURISDICTION_CLASSIFICATIONS
from opencivicdata.divisions import Division
and context (classes, functions, or code) from other files:
# Path: pupa/cli/commands/base.py
# class BaseCommand(object):
#
# def __init__(self, subparsers):
# self.subparser = subparsers.add_parser(self.name, description=self.help)
# self.add_args()
#
# def add_args(self):
# pass
#
# def add_argument(self, *args, **kwargs):
# self.subparser.add_argument(*args, **kwargs)
#
# def handle(self, args):
# raise NotImplementedError('commands must implement handle(args)')
#
# Path: pupa/exceptions.py
# class CommandError(PupaError):
# """ Errors from within pupa CLI """
. Output only the next line. | raise CommandError('Directory {} already exists'.format(repr(args.module))) |
Predict the next line for this snippet: <|code_start|>
"related_entities": {
"items": {
"properties": {
"entity_type": {
"type": "string",
"minLength": 1,
},
"name": {
"type": "string",
"minLength": 1,
},
"note": {
"type": ["string", "null", ],
"minLength": 1,
},
},
"type": "object",
},
"minItems": 0,
"type": "array",
},
},
"type": "object"
},
"minItems": 0,
"type": "array"
},
<|code_end|>
with the help of current file imports:
from .common import sources, extras, fuzzy_date_blank, fuzzy_datetime, fuzzy_datetime_blank
and context from other files:
# Path: pupa/scrape/schemas/common.py
, which may contain function names, class names, or code. Output only the next line. | "sources": sources, |
Continue the code snippet: <|code_start|> "related_entities": {
"items": {
"properties": {
"entity_type": {
"type": "string",
"minLength": 1,
},
"name": {
"type": "string",
"minLength": 1,
},
"note": {
"type": ["string", "null", ],
"minLength": 1,
},
},
"type": "object",
},
"minItems": 0,
"type": "array",
},
},
"type": "object"
},
"minItems": 0,
"type": "array"
},
"sources": sources,
<|code_end|>
. Use current file imports:
from .common import sources, extras, fuzzy_date_blank, fuzzy_datetime, fuzzy_datetime_blank
and context (classes, functions, or code) from other files:
# Path: pupa/scrape/schemas/common.py
. Output only the next line. | "extras": extras, |
Predict the next line after this snippet: <|code_start|>"""
Schema for event objects.
"""
media_schema = {
"items": {
"properties": {
"name": {"type": "string", "minLength": 1},
"type": {"type": "string", "minLength": 1},
<|code_end|>
using the current file's imports:
from .common import sources, extras, fuzzy_date_blank, fuzzy_datetime, fuzzy_datetime_blank
and any relevant context from other files:
# Path: pupa/scrape/schemas/common.py
. Output only the next line. | "date": fuzzy_date_blank, |
Predict the next line after this snippet: <|code_start|>"""
media_schema = {
"items": {
"properties": {
"name": {"type": "string", "minLength": 1},
"type": {"type": "string", "minLength": 1},
"date": fuzzy_date_blank,
"offset": {"type": ["number", "null"]},
"links": {
"items": {
"properties": {
"media_type": {"type": "string"},
"url": {"type": "string", "format": "uri"},
},
"type": "object"
},
"type": "array"
},
},
"type": "object"
},
"type": "array"
}
schema = {
"properties": {
"name": {"type": "string", "minLength": 1},
"all_day": {"type": "boolean"},
<|code_end|>
using the current file's imports:
from .common import sources, extras, fuzzy_date_blank, fuzzy_datetime, fuzzy_datetime_blank
and any relevant context from other files:
# Path: pupa/scrape/schemas/common.py
. Output only the next line. | 'start_date': fuzzy_datetime, |
Here is a snippet: <|code_start|>
media_schema = {
"items": {
"properties": {
"name": {"type": "string", "minLength": 1},
"type": {"type": "string", "minLength": 1},
"date": fuzzy_date_blank,
"offset": {"type": ["number", "null"]},
"links": {
"items": {
"properties": {
"media_type": {"type": "string"},
"url": {"type": "string", "format": "uri"},
},
"type": "object"
},
"type": "array"
},
},
"type": "object"
},
"type": "array"
}
schema = {
"properties": {
"name": {"type": "string", "minLength": 1},
"all_day": {"type": "boolean"},
'start_date': fuzzy_datetime,
<|code_end|>
. Write the next line using the current file imports:
from .common import sources, extras, fuzzy_date_blank, fuzzy_datetime, fuzzy_datetime_blank
and context from other files:
# Path: pupa/scrape/schemas/common.py
, which may include functions, classes, or code. Output only the next line. | 'end_date': fuzzy_datetime_blank, |
Given the code snippet: <|code_start|>
def create_jurisdiction():
Division.objects.create(id='ocd-division/country:us', name='USA')
Jurisdiction.objects.create(id='jid', division_id='ocd-division/country:us')
@pytest.mark.django_db
def test_full_person():
<|code_end|>
, generate the next line using the imports in this file:
import pytest
from pupa.scrape import Person as ScrapePerson
from pupa.importers import PersonImporter
from opencivicdata.core.models import Person, Organization, Membership, Division, Jurisdiction
from pupa.exceptions import UnresolvedIdError, SameNameError
and context (functions, classes, or occasionally code) from other files:
# Path: pupa/scrape/popolo.py
# class Person(BaseModel, SourceMixin, ContactDetailMixin, LinkMixin, IdentifierMixin,
# OtherNameMixin):
# """
# Details for a Person in Popolo format.
# """
#
# _type = 'person'
# _schema = person_schema
#
# def __init__(self, name, *, birth_date='', death_date='', biography='', summary='', image='',
# gender='', national_identity='',
# # specialty fields
# district=None, party=None, primary_org='', role='',
# start_date='', end_date='', primary_org_name=None):
# super(Person, self).__init__()
# self.name = name
# self.birth_date = birth_date
# self.death_date = death_date
# self.biography = biography
# self.summary = summary
# self.image = image
# self.gender = gender
# self.national_identity = national_identity
# if primary_org:
# self.add_term(role, primary_org, district=district,
# start_date=start_date, end_date=end_date,
# org_name=primary_org_name)
# if party:
# self.add_party(party)
#
# def add_membership(self, name_or_org, role='member', **kwargs):
# """
# add a membership in an organization and return the membership
# object in case there are more details to add
# """
# if isinstance(name_or_org, Organization):
# membership = Membership(person_id=self._id,
# person_name=self.name,
# organization_id=name_or_org._id,
# role=role, **kwargs)
# else:
# membership = Membership(person_id=self._id,
# person_name=self.name,
# organization_id=_make_pseudo_id(name=name_or_org),
# role=role, **kwargs)
# self._related.append(membership)
# return membership
#
# def add_party(self, party, **kwargs):
# membership = Membership(
# person_id=self._id,
# person_name=self.name,
# organization_id=_make_pseudo_id(classification="party", name=party),
# role='member', **kwargs)
# self._related.append(membership)
#
# def add_term(self, role, org_classification, *, district=None,
# start_date='', end_date='', label='', org_name=None,
# appointment=False):
# if org_name:
# org_id = _make_pseudo_id(classification=org_classification,
# name=org_name)
# else:
# org_id = _make_pseudo_id(classification=org_classification)
#
# if district:
# if role:
# post_id = _make_pseudo_id(label=district,
# role=role,
# organization__classification=org_classification)
# else:
# post_id = _make_pseudo_id(label=district,
# organization__classification=org_classification)
# elif appointment:
# post_id = _make_pseudo_id(role=role,
# organization__classification=org_classification)
# else:
# post_id = None
# membership = Membership(person_id=self._id, person_name=self.name,
# organization_id=org_id, post_id=post_id,
# role=role, start_date=start_date, end_date=end_date, label=label)
# self._related.append(membership)
# return membership
#
# def __str__(self):
# return self.name
#
# Path: pupa/exceptions.py
# class UnresolvedIdError(DataImportError):
# """ Attempt was made to resolve an id that has no result. """
#
# class SameNameError(DataImportError):
# """ Attempt was made to import two people with the same name. """
#
# def __init__(self, name):
# super(SameNameError, self).__init__('multiple people with same name "{}" in Jurisdiction '
# '- must provide birth_date to disambiguate'
# .format(name))
. Output only the next line. | person = ScrapePerson('Tom Sawyer') |
Here is a snippet: <|code_start|>
@pytest.mark.django_db
def test_resolve_json_id():
create_jurisdiction()
o = Organization.objects.create(name='WWE', jurisdiction_id='jid')
p = Person.objects.create(name='Dwayne Johnson', family_name='Johnson')
p.other_names.create(name='Rock')
p.memberships.create(organization=o)
pi = PersonImporter('jid')
assert pi.resolve_json_id('~{"name": "Dwayne Johnson"}') == p.id
assert pi.resolve_json_id('~{"name": "Rock"}') == p.id
assert pi.resolve_json_id('~{"name": "Johnson"}') == p.id
@pytest.mark.django_db
def test_resolve_json_id_multiple_family_name():
create_jurisdiction()
o = Organization.objects.create(name='WWE', jurisdiction_id='jid')
p1 = Person.objects.create(name='Dwayne Johnson', family_name='Johnson')
p1.other_names.create(name='Rock')
p2 = Person.objects.create(name='Adam Johnson', family_name='Johnson')
for p in Person.objects.all():
Membership.objects.create(person=p, organization=o)
# If there are multiple people with a family name, full name/other name
# lookups should work but family name lookups should fail.
pi = PersonImporter('jid')
assert pi.resolve_json_id('~{"name": "Dwayne Johnson"}') == p1.id
assert pi.resolve_json_id('~{"name": "Adam Johnson"}') == p2.id
<|code_end|>
. Write the next line using the current file imports:
import pytest
from pupa.scrape import Person as ScrapePerson
from pupa.importers import PersonImporter
from opencivicdata.core.models import Person, Organization, Membership, Division, Jurisdiction
from pupa.exceptions import UnresolvedIdError, SameNameError
and context from other files:
# Path: pupa/scrape/popolo.py
# class Person(BaseModel, SourceMixin, ContactDetailMixin, LinkMixin, IdentifierMixin,
# OtherNameMixin):
# """
# Details for a Person in Popolo format.
# """
#
# _type = 'person'
# _schema = person_schema
#
# def __init__(self, name, *, birth_date='', death_date='', biography='', summary='', image='',
# gender='', national_identity='',
# # specialty fields
# district=None, party=None, primary_org='', role='',
# start_date='', end_date='', primary_org_name=None):
# super(Person, self).__init__()
# self.name = name
# self.birth_date = birth_date
# self.death_date = death_date
# self.biography = biography
# self.summary = summary
# self.image = image
# self.gender = gender
# self.national_identity = national_identity
# if primary_org:
# self.add_term(role, primary_org, district=district,
# start_date=start_date, end_date=end_date,
# org_name=primary_org_name)
# if party:
# self.add_party(party)
#
# def add_membership(self, name_or_org, role='member', **kwargs):
# """
# add a membership in an organization and return the membership
# object in case there are more details to add
# """
# if isinstance(name_or_org, Organization):
# membership = Membership(person_id=self._id,
# person_name=self.name,
# organization_id=name_or_org._id,
# role=role, **kwargs)
# else:
# membership = Membership(person_id=self._id,
# person_name=self.name,
# organization_id=_make_pseudo_id(name=name_or_org),
# role=role, **kwargs)
# self._related.append(membership)
# return membership
#
# def add_party(self, party, **kwargs):
# membership = Membership(
# person_id=self._id,
# person_name=self.name,
# organization_id=_make_pseudo_id(classification="party", name=party),
# role='member', **kwargs)
# self._related.append(membership)
#
# def add_term(self, role, org_classification, *, district=None,
# start_date='', end_date='', label='', org_name=None,
# appointment=False):
# if org_name:
# org_id = _make_pseudo_id(classification=org_classification,
# name=org_name)
# else:
# org_id = _make_pseudo_id(classification=org_classification)
#
# if district:
# if role:
# post_id = _make_pseudo_id(label=district,
# role=role,
# organization__classification=org_classification)
# else:
# post_id = _make_pseudo_id(label=district,
# organization__classification=org_classification)
# elif appointment:
# post_id = _make_pseudo_id(role=role,
# organization__classification=org_classification)
# else:
# post_id = None
# membership = Membership(person_id=self._id, person_name=self.name,
# organization_id=org_id, post_id=post_id,
# role=role, start_date=start_date, end_date=end_date, label=label)
# self._related.append(membership)
# return membership
#
# def __str__(self):
# return self.name
#
# Path: pupa/exceptions.py
# class UnresolvedIdError(DataImportError):
# """ Attempt was made to resolve an id that has no result. """
#
# class SameNameError(DataImportError):
# """ Attempt was made to import two people with the same name. """
#
# def __init__(self, name):
# super(SameNameError, self).__init__('multiple people with same name "{}" in Jurisdiction '
# '- must provide birth_date to disambiguate'
# .format(name))
, which may include functions, classes, or code. Output only the next line. | with pytest.raises(UnresolvedIdError): |
Given snippet: <|code_start|> assert Person.objects.all().count() == 2
@pytest.mark.django_db
def test_multiple_memberships():
create_jurisdiction()
# there was a bug where two or more memberships to the same jurisdiction
# would cause an ORM error, this test ensures that it is fixed
p = Person.objects.create(name='Dwayne Johnson')
o = Organization.objects.create(name='WWE', jurisdiction_id='jid')
Membership.objects.create(person=p, organization=o)
o = Organization.objects.create(name='WWF', jurisdiction_id='jid')
Membership.objects.create(person=p, organization=o)
person = ScrapePerson('Dwayne Johnson')
pd = person.as_dict()
PersonImporter('jid').import_data([pd])
# deduplication should still work
assert Person.objects.all().count() == 1
@pytest.mark.django_db
def test_same_name_people():
create_jurisdiction()
o = Organization.objects.create(name='WWE', jurisdiction_id='jid')
# importing two people with the same name to a pristine database should error
p1 = ScrapePerson('Dwayne Johnson', image='http://example.com/1')
p2 = ScrapePerson('Dwayne Johnson', image='http://example.com/2')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pytest
from pupa.scrape import Person as ScrapePerson
from pupa.importers import PersonImporter
from opencivicdata.core.models import Person, Organization, Membership, Division, Jurisdiction
from pupa.exceptions import UnresolvedIdError, SameNameError
and context:
# Path: pupa/scrape/popolo.py
# class Person(BaseModel, SourceMixin, ContactDetailMixin, LinkMixin, IdentifierMixin,
# OtherNameMixin):
# """
# Details for a Person in Popolo format.
# """
#
# _type = 'person'
# _schema = person_schema
#
# def __init__(self, name, *, birth_date='', death_date='', biography='', summary='', image='',
# gender='', national_identity='',
# # specialty fields
# district=None, party=None, primary_org='', role='',
# start_date='', end_date='', primary_org_name=None):
# super(Person, self).__init__()
# self.name = name
# self.birth_date = birth_date
# self.death_date = death_date
# self.biography = biography
# self.summary = summary
# self.image = image
# self.gender = gender
# self.national_identity = national_identity
# if primary_org:
# self.add_term(role, primary_org, district=district,
# start_date=start_date, end_date=end_date,
# org_name=primary_org_name)
# if party:
# self.add_party(party)
#
# def add_membership(self, name_or_org, role='member', **kwargs):
# """
# add a membership in an organization and return the membership
# object in case there are more details to add
# """
# if isinstance(name_or_org, Organization):
# membership = Membership(person_id=self._id,
# person_name=self.name,
# organization_id=name_or_org._id,
# role=role, **kwargs)
# else:
# membership = Membership(person_id=self._id,
# person_name=self.name,
# organization_id=_make_pseudo_id(name=name_or_org),
# role=role, **kwargs)
# self._related.append(membership)
# return membership
#
# def add_party(self, party, **kwargs):
# membership = Membership(
# person_id=self._id,
# person_name=self.name,
# organization_id=_make_pseudo_id(classification="party", name=party),
# role='member', **kwargs)
# self._related.append(membership)
#
# def add_term(self, role, org_classification, *, district=None,
# start_date='', end_date='', label='', org_name=None,
# appointment=False):
# if org_name:
# org_id = _make_pseudo_id(classification=org_classification,
# name=org_name)
# else:
# org_id = _make_pseudo_id(classification=org_classification)
#
# if district:
# if role:
# post_id = _make_pseudo_id(label=district,
# role=role,
# organization__classification=org_classification)
# else:
# post_id = _make_pseudo_id(label=district,
# organization__classification=org_classification)
# elif appointment:
# post_id = _make_pseudo_id(role=role,
# organization__classification=org_classification)
# else:
# post_id = None
# membership = Membership(person_id=self._id, person_name=self.name,
# organization_id=org_id, post_id=post_id,
# role=role, start_date=start_date, end_date=end_date, label=label)
# self._related.append(membership)
# return membership
#
# def __str__(self):
# return self.name
#
# Path: pupa/exceptions.py
# class UnresolvedIdError(DataImportError):
# """ Attempt was made to resolve an id that has no result. """
#
# class SameNameError(DataImportError):
# """ Attempt was made to import two people with the same name. """
#
# def __init__(self, name):
# super(SameNameError, self).__init__('multiple people with same name "{}" in Jurisdiction '
# '- must provide birth_date to disambiguate'
# .format(name))
which might include code, classes, or functions. Output only the next line. | with pytest.raises(SameNameError): |
Based on the snippet: <|code_start|>
def create_jurisdiction():
Division.objects.create(id='ocd-division/country:us', name='USA')
j = Jurisdiction.objects.create(id='jid', division_id='ocd-division/country:us')
return j
def create_other_jurisdiction():
Division.objects.create(id='ocd-division/country:ca', name='USA')
j = Jurisdiction.objects.create(id='ojid', division_id='ocd-division/country:ca')
return j
def ge():
<|code_end|>
, predict the immediate next line with the help of imports:
import pytest
from pupa.scrape import Event as ScrapeEvent
from pupa.importers import (EventImporter, OrganizationImporter, PersonImporter, BillImporter,
VoteEventImporter)
from opencivicdata.legislative.models import VoteEvent, Bill, Event
from opencivicdata.core.models import (Person, Membership, Organization, Jurisdiction, Division)
and context (classes, functions, sometimes code) from other files:
# Path: pupa/scrape/event.py
# class Event(BaseModel, SourceMixin, AssociatedLinkMixin, LinkMixin):
# """
# Details for an event in .format
# """
# _type = 'event'
# _schema = schema
#
# def __init__(self, name, start_date, *,
# location_name=None,
# all_day=False, description="", end_date="",
# status="confirmed", classification="event"
# ):
# super(Event, self).__init__()
# self.start_date = start_date
# self.all_day = all_day
# self.end_date = end_date
# self.name = name
# self.description = description
# self.status = status
# self.classification = classification
# if location_name:
# self.location = {"name": location_name, "note": "", "coordinates": None}
# else:
# self.location = None
# self.documents = []
# self.participants = []
# self.media = []
# self.agenda = []
#
# def __str__(self):
# return '{} {}'.format(self.start_date, self.name.strip())
#
# def set_location(self, name, *, note="", url="", coordinates=None):
# self.location = {"name": name, "note": note, "url": url, "coordinates": coordinates}
#
# def add_participant(self, name, type, *, id=None, note='participant'):
# p = {
# "name": name,
# "entity_type": type,
# "note": note
# }
# if id:
# p['id'] = id
# elif type:
# id = _make_pseudo_id(name=name)
# p[type + '_id'] = id
#
# self.participants.append(p)
#
# def add_person(self, name, *, id=None, note='participant'):
# return self.add_participant(name=name, type='person', id=id, note=note)
#
# def add_committee(self, name, *, id=None, note='participant'):
# return self.add_participant(name=name, type='organization', id=id, note=note)
#
# def add_agenda_item(self, description):
# obj = EventAgendaItem(description, self)
# self.agenda.append(obj)
# return obj
#
# def add_media_link(self, note, url, media_type, *, text='',
# type='media', on_duplicate='error', date=''):
# return self._add_associated_link(collection='media',
# note=note,
# url=url,
# text=text,
# media_type=media_type,
# on_duplicate=on_duplicate,
# date=date)
#
# def add_document(self, note, url, *, text='', media_type='', on_duplicate='error', date=''):
# return self._add_associated_link(collection='documents',
# note=note, url=url,
# text=text,
# media_type=media_type,
# on_duplicate=on_duplicate,
# date=date)
. Output only the next line. | event = ScrapeEvent( |
Given the following code snippet before the placeholder: <|code_start|>
def create_data():
Division.objects.create(id='ocd-division/country:us', name='USA')
j = Jurisdiction.objects.create(id='jid', division_id='ocd-division/country:us')
org = Organization.objects.create(jurisdiction=j, name='House', classification='lower')
person = Person.objects.create(name='Roy')
j.legislative_sessions.create(identifier='1899', name='1899')
session = j.legislative_sessions.create(identifier='1900', name='1900').id
return session, org, person
@pytest.mark.django_db
def test_bills_missing_actions():
session, org, person = create_data()
Bill.objects.create(identifier='HB1', title='One', legislative_session_id=session)
b = Bill.objects.create(identifier='HB2', title='Two', legislative_session_id=session)
<|code_end|>
, predict the next line using imports from the current file:
import pytest
import django
from opencivicdata.core.models import Jurisdiction, Division, Organization, Person
from opencivicdata.legislative.models import Bill, VoteEvent
from pupa.reports import generate_session_report
and context including class names, function names, and sometimes code from other files:
# Path: pupa/reports/session.py
# def generate_session_report(session):
# report = {
# 'bills_missing_actions': _simple_count(Bill, session, actions__isnull=True),
# 'bills_missing_sponsors': _simple_count(Bill, session, sponsorships__isnull=True),
# 'bills_missing_versions': _simple_count(Bill, session, versions__isnull=True),
# 'votes_missing_bill': _simple_count(VoteEvent, session, bill__isnull=True),
# 'votes_missing_voters': _simple_count(VoteEvent, session, votes__isnull=True),
# 'votes_missing_yes_count': 0,
# 'votes_missing_no_count': 0,
# 'votes_with_bad_counts': 0,
# }
#
# voteevents = VoteEvent.objects.filter(legislative_session_id=session)
# queryset = voteevents.annotate(
# yes_sum=Count('pk', filter=Q(votes__option='yes')),
# no_sum=Count('pk', filter=Q(votes__option='no')),
# other_sum=Count('pk', filter=Q(votes__option='other')),
# yes_count=Subquery(VoteCount.objects.filter(vote_event=OuterRef('pk'),
# option='yes').values('value')),
# no_count=Subquery(VoteCount.objects.filter(vote_event=OuterRef('pk'),
# option='no').values('value')),
# other_count=Subquery(VoteCount.objects.filter(vote_event=OuterRef('pk'),
# option='other').values('value')),
# )
#
# for vote in queryset:
# if vote.yes_count is None:
# report['votes_missing_yes_count'] += 1
# vote.yes_count = 0
# if vote.no_count is None:
# report['votes_missing_no_count'] += 1
# vote.no_count = 0
# if vote.other_count is None:
# vote.other_count = 0
# if (vote.yes_sum != vote.yes_count or
# vote.no_sum != vote.no_count or
# vote.other_sum != vote.other_count):
# report['votes_with_bad_counts'] += 1
#
# # handle unmatched
# queryset = BillSponsorship.objects.filter(bill__legislative_session_id=session,
# entity_type='person', person_id=None
# ).values('name').annotate(num=Count('name'))
# report['unmatched_sponsor_people'] = {item['name']: item['num'] for item in queryset}
# queryset = BillSponsorship.objects.filter(bill__legislative_session_id=session,
# entity_type='organization', person_id=None
# ).values('name').annotate(num=Count('name'))
# report['unmatched_sponsor_organizations'] = {item['name']: item['num'] for item in queryset}
# queryset = PersonVote.objects.filter(vote_event__legislative_session_id=session,
# voter__isnull=True).values(name=F('voter_name')).annotate(
# num=Count('voter_name')
# )
# report['unmatched_voters'] = {item['name']: item['num'] for item in queryset}
#
# return SessionDataQualityReport(legislative_session_id=session, **report)
. Output only the next line. | report = generate_session_report(session) |
Based on the snippet: <|code_start|>class BaseImporter(object):
""" BaseImporter
Override:
get_object(data)
limit_spec(spec) [optional, required if pseudo_ids are used]
prepare_for_db(data) [optional]
postimport() [optional]
"""
_type = None
model_class = None
related_models = {}
preserve_order = set()
merge_related = {}
cached_transformers = {}
def __init__(self, jurisdiction_id):
self.jurisdiction_id = jurisdiction_id
self.json_to_db_id = {}
self.duplicates = {}
self.pseudo_id_cache = {}
self.session_cache = {}
self.logger = logging.getLogger("pupa")
self.info = self.logger.info
self.debug = self.logger.debug
self.warning = self.logger.warning
self.error = self.logger.error
self.critical = self.logger.critical
# load transformers from appropriate setting
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import copy
import glob
import json
import logging
from django.db.models import Q
from django.db.models.signals import post_save
from django.contrib.contenttypes.models import ContentType
from opencivicdata.legislative.models import LegislativeSession
from pupa import settings
from pupa.exceptions import DuplicateItemError
from pupa.utils import get_pseudo_id, utcnow
from pupa.exceptions import UnresolvedIdError, DataImportError
from pupa.models import Identifier
and context (classes, functions, sometimes code) from other files:
# Path: pupa/settings.py
# DATABASE_URL = os.environ.get('DATABASE_URL', 'postgis://pupa:pupa@localhost/opencivicdata')
# SECRET_KEY = 'non-secret'
# INSTALLED_APPS = ('django.contrib.contenttypes',
# 'opencivicdata.core.apps.BaseConfig',
# 'opencivicdata.legislative.apps.BaseConfig',
# 'pupa')
# SCRAPELIB_RPM = 60
# SCRAPELIB_TIMEOUT = 60
# SCRAPELIB_RETRY_ATTEMPTS = 3
# SCRAPELIB_RETRY_WAIT_SECONDS = 10
# SCRAPELIB_VERIFY = True
# CACHE_DIR = os.path.join(os.getcwd(), '_cache')
# SCRAPED_DATA_DIR = os.path.join(os.getcwd(), '_data')
# ENABLE_PEOPLE_AND_ORGS = True
# ENABLE_BILLS = True
# ENABLE_VOTES = True
# ENABLE_EVENTS = True
# IMPORT_TRANSFORMERS = {
# 'bill': []
# }
# DEBUG = False
# TEMPLATE_DEBUG = False
# MIDDLEWARE_CLASSES = ()
# LOGGING = {
# 'version': 1,
# 'disable_existing_loggers': False,
# 'formatters': {
# 'standard': {
# 'format': "%(asctime)s %(levelname)s %(name)s: %(message)s",
# 'datefmt': '%H:%M:%S'
# }
# },
# 'handlers': {
# 'default': {'level': 'DEBUG',
# 'class': 'pupa.ext.ansistrm.ColorizingStreamHandler',
# 'formatter': 'standard'},
# },
# 'loggers': {
# '': {
# 'handlers': ['default'], 'level': 'DEBUG', 'propagate': True
# },
# 'scrapelib': {
# 'handlers': ['default'], 'level': 'INFO', 'propagate': False
# },
# 'requests': {
# 'handlers': ['default'], 'level': 'WARN', 'propagate': False
# },
# 'boto': {
# 'handlers': ['default'], 'level': 'WARN', 'propagate': False
# },
# },
# }
# DATABASES = {'default': dj_database_url.parse(DATABASE_URL)}
#
# Path: pupa/exceptions.py
# class DuplicateItemError(DataImportError):
# """ Attempt was made to import items that resolve to the same database item. """
#
# def __init__(self, data, obj, data_sources=None):
# super(DuplicateItemError, self).__init__(
# 'attempt to import data that would conflict with '
# 'data already in the import: {} '
# '(already imported as {})\n'
# 'obj1 sources: {}\nobj2 sources: {}'.format(
# data,
# obj,
# list(obj.sources.values_list('url', flat=True)
# if hasattr(obj, 'sources') else []),
# [s['url'] for s in data_sources or []]
# ))
#
# Path: pupa/utils/generic.py
# def get_pseudo_id(pid):
# if pid[0] != '~':
# raise ValueError("pseudo id doesn't start with ~")
# return json.loads(pid[1:])
#
# def utcnow():
# return datetime.datetime.now(datetime.timezone.utc)
#
# Path: pupa/exceptions.py
# class UnresolvedIdError(DataImportError):
# """ Attempt was made to resolve an id that has no result. """
#
# class DataImportError(PupaError):
# """ A generic error related to the import process. """
#
# Path: pupa/models.py
# class Identifier(models.Model):
# identifier = models.CharField(max_length=300)
# jurisdiction = models.ForeignKey(Jurisdiction,
# related_name='pupa_ids',
# on_delete=models.CASCADE,
# )
# content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
# object_id = models.CharField(max_length=300)
# content_object = GenericForeignKey('content_type', 'object_id')
#
# def __str__(self): # __unicode__ on Python 2
# return self.identifier
. Output only the next line. | if settings.IMPORT_TRANSFORMERS.get(self._type): |
Using the snippet: <|code_start|>
return {self._type: record}
def import_item(self, data):
""" function used by import_data """
what = 'noop'
# remove the JSON _id (may still be there if called directly)
data.pop('_id', None)
# add fields/etc.
data = self.apply_transformers(data)
data = self.prepare_for_db(data)
try:
obj = self.get_object(data)
except self.model_class.DoesNotExist:
obj = None
# remove pupa_id which does not belong in the OCD data models
pupa_id = data.pop('pupa_id', None)
# pull related fields off
related = {}
for field in self.related_models:
related[field] = data.pop(field)
# obj existed, check if we need to do an update
if obj:
if obj.id in self.json_to_db_id.values():
<|code_end|>
, determine the next line of code. You have imports:
import os
import copy
import glob
import json
import logging
from django.db.models import Q
from django.db.models.signals import post_save
from django.contrib.contenttypes.models import ContentType
from opencivicdata.legislative.models import LegislativeSession
from pupa import settings
from pupa.exceptions import DuplicateItemError
from pupa.utils import get_pseudo_id, utcnow
from pupa.exceptions import UnresolvedIdError, DataImportError
from pupa.models import Identifier
and context (class names, function names, or code) available:
# Path: pupa/settings.py
# DATABASE_URL = os.environ.get('DATABASE_URL', 'postgis://pupa:pupa@localhost/opencivicdata')
# SECRET_KEY = 'non-secret'
# INSTALLED_APPS = ('django.contrib.contenttypes',
# 'opencivicdata.core.apps.BaseConfig',
# 'opencivicdata.legislative.apps.BaseConfig',
# 'pupa')
# SCRAPELIB_RPM = 60
# SCRAPELIB_TIMEOUT = 60
# SCRAPELIB_RETRY_ATTEMPTS = 3
# SCRAPELIB_RETRY_WAIT_SECONDS = 10
# SCRAPELIB_VERIFY = True
# CACHE_DIR = os.path.join(os.getcwd(), '_cache')
# SCRAPED_DATA_DIR = os.path.join(os.getcwd(), '_data')
# ENABLE_PEOPLE_AND_ORGS = True
# ENABLE_BILLS = True
# ENABLE_VOTES = True
# ENABLE_EVENTS = True
# IMPORT_TRANSFORMERS = {
# 'bill': []
# }
# DEBUG = False
# TEMPLATE_DEBUG = False
# MIDDLEWARE_CLASSES = ()
# LOGGING = {
# 'version': 1,
# 'disable_existing_loggers': False,
# 'formatters': {
# 'standard': {
# 'format': "%(asctime)s %(levelname)s %(name)s: %(message)s",
# 'datefmt': '%H:%M:%S'
# }
# },
# 'handlers': {
# 'default': {'level': 'DEBUG',
# 'class': 'pupa.ext.ansistrm.ColorizingStreamHandler',
# 'formatter': 'standard'},
# },
# 'loggers': {
# '': {
# 'handlers': ['default'], 'level': 'DEBUG', 'propagate': True
# },
# 'scrapelib': {
# 'handlers': ['default'], 'level': 'INFO', 'propagate': False
# },
# 'requests': {
# 'handlers': ['default'], 'level': 'WARN', 'propagate': False
# },
# 'boto': {
# 'handlers': ['default'], 'level': 'WARN', 'propagate': False
# },
# },
# }
# DATABASES = {'default': dj_database_url.parse(DATABASE_URL)}
#
# Path: pupa/exceptions.py
# class DuplicateItemError(DataImportError):
# """ Attempt was made to import items that resolve to the same database item. """
#
# def __init__(self, data, obj, data_sources=None):
# super(DuplicateItemError, self).__init__(
# 'attempt to import data that would conflict with '
# 'data already in the import: {} '
# '(already imported as {})\n'
# 'obj1 sources: {}\nobj2 sources: {}'.format(
# data,
# obj,
# list(obj.sources.values_list('url', flat=True)
# if hasattr(obj, 'sources') else []),
# [s['url'] for s in data_sources or []]
# ))
#
# Path: pupa/utils/generic.py
# def get_pseudo_id(pid):
# if pid[0] != '~':
# raise ValueError("pseudo id doesn't start with ~")
# return json.loads(pid[1:])
#
# def utcnow():
# return datetime.datetime.now(datetime.timezone.utc)
#
# Path: pupa/exceptions.py
# class UnresolvedIdError(DataImportError):
# """ Attempt was made to resolve an id that has no result. """
#
# class DataImportError(PupaError):
# """ A generic error related to the import process. """
#
# Path: pupa/models.py
# class Identifier(models.Model):
# identifier = models.CharField(max_length=300)
# jurisdiction = models.ForeignKey(Jurisdiction,
# related_name='pupa_ids',
# on_delete=models.CASCADE,
# )
# content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
# object_id = models.CharField(max_length=300)
# content_object = GenericForeignKey('content_type', 'object_id')
#
# def __str__(self): # __unicode__ on Python 2
# return self.identifier
. Output only the next line. | raise DuplicateItemError(data, obj, related.get('sources', [])) |
Continue the code snippet: <|code_start|> identifier=identifier, jurisdiction_id=self.jurisdiction_id).id
return self.session_cache[identifier]
# no-ops to be overriden
def prepare_for_db(self, data):
return data
def postimport(self):
pass
def resolve_json_id(self, json_id, allow_no_match=False):
"""
Given an id found in scraped JSON, return a DB id for the object.
params:
json_id: id from json
allow_no_match: just return None if id can't be resolved
returns:
database id
raises:
ValueError if id couldn't be resolved
"""
if not json_id:
return None
if json_id.startswith('~'):
# keep caches of all the pseudo-ids to avoid doing 1000s of lookups during import
if json_id not in self.pseudo_id_cache:
<|code_end|>
. Use current file imports:
import os
import copy
import glob
import json
import logging
from django.db.models import Q
from django.db.models.signals import post_save
from django.contrib.contenttypes.models import ContentType
from opencivicdata.legislative.models import LegislativeSession
from pupa import settings
from pupa.exceptions import DuplicateItemError
from pupa.utils import get_pseudo_id, utcnow
from pupa.exceptions import UnresolvedIdError, DataImportError
from pupa.models import Identifier
and context (classes, functions, or code) from other files:
# Path: pupa/settings.py
# DATABASE_URL = os.environ.get('DATABASE_URL', 'postgis://pupa:pupa@localhost/opencivicdata')
# SECRET_KEY = 'non-secret'
# INSTALLED_APPS = ('django.contrib.contenttypes',
# 'opencivicdata.core.apps.BaseConfig',
# 'opencivicdata.legislative.apps.BaseConfig',
# 'pupa')
# SCRAPELIB_RPM = 60
# SCRAPELIB_TIMEOUT = 60
# SCRAPELIB_RETRY_ATTEMPTS = 3
# SCRAPELIB_RETRY_WAIT_SECONDS = 10
# SCRAPELIB_VERIFY = True
# CACHE_DIR = os.path.join(os.getcwd(), '_cache')
# SCRAPED_DATA_DIR = os.path.join(os.getcwd(), '_data')
# ENABLE_PEOPLE_AND_ORGS = True
# ENABLE_BILLS = True
# ENABLE_VOTES = True
# ENABLE_EVENTS = True
# IMPORT_TRANSFORMERS = {
# 'bill': []
# }
# DEBUG = False
# TEMPLATE_DEBUG = False
# MIDDLEWARE_CLASSES = ()
# LOGGING = {
# 'version': 1,
# 'disable_existing_loggers': False,
# 'formatters': {
# 'standard': {
# 'format': "%(asctime)s %(levelname)s %(name)s: %(message)s",
# 'datefmt': '%H:%M:%S'
# }
# },
# 'handlers': {
# 'default': {'level': 'DEBUG',
# 'class': 'pupa.ext.ansistrm.ColorizingStreamHandler',
# 'formatter': 'standard'},
# },
# 'loggers': {
# '': {
# 'handlers': ['default'], 'level': 'DEBUG', 'propagate': True
# },
# 'scrapelib': {
# 'handlers': ['default'], 'level': 'INFO', 'propagate': False
# },
# 'requests': {
# 'handlers': ['default'], 'level': 'WARN', 'propagate': False
# },
# 'boto': {
# 'handlers': ['default'], 'level': 'WARN', 'propagate': False
# },
# },
# }
# DATABASES = {'default': dj_database_url.parse(DATABASE_URL)}
#
# Path: pupa/exceptions.py
# class DuplicateItemError(DataImportError):
# """ Attempt was made to import items that resolve to the same database item. """
#
# def __init__(self, data, obj, data_sources=None):
# super(DuplicateItemError, self).__init__(
# 'attempt to import data that would conflict with '
# 'data already in the import: {} '
# '(already imported as {})\n'
# 'obj1 sources: {}\nobj2 sources: {}'.format(
# data,
# obj,
# list(obj.sources.values_list('url', flat=True)
# if hasattr(obj, 'sources') else []),
# [s['url'] for s in data_sources or []]
# ))
#
# Path: pupa/utils/generic.py
# def get_pseudo_id(pid):
# if pid[0] != '~':
# raise ValueError("pseudo id doesn't start with ~")
# return json.loads(pid[1:])
#
# def utcnow():
# return datetime.datetime.now(datetime.timezone.utc)
#
# Path: pupa/exceptions.py
# class UnresolvedIdError(DataImportError):
# """ Attempt was made to resolve an id that has no result. """
#
# class DataImportError(PupaError):
# """ A generic error related to the import process. """
#
# Path: pupa/models.py
# class Identifier(models.Model):
# identifier = models.CharField(max_length=300)
# jurisdiction = models.ForeignKey(Jurisdiction,
# related_name='pupa_ids',
# on_delete=models.CASCADE,
# )
# content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
# object_id = models.CharField(max_length=300)
# content_object = GenericForeignKey('content_type', 'object_id')
#
# def __str__(self): # __unicode__ on Python 2
# return self.identifier
. Output only the next line. | spec = get_pseudo_id(json_id) |
Given the following code snippet before the placeholder: <|code_start|> yield json.load(f)
return self.import_data(json_stream())
def _prepare_imports(self, dicts):
""" filters the import stream to remove duplicates
also serves as a good place to override if anything special has to be done to the
order of the import stream (see OrganizationImporter)
"""
# hash(json): id
seen_hashes = {}
for data in dicts:
json_id = data.pop('_id')
# map duplicates (using omnihash to tell if json dicts are identical-ish)
objhash = omnihash(data)
if objhash not in seen_hashes:
seen_hashes[objhash] = json_id
yield json_id, data
else:
self.duplicates[json_id] = seen_hashes[objhash]
def import_data(self, data_items):
""" import a bunch of dicts together """
# keep counts of all actions
record = {
'insert': 0, 'update': 0, 'noop': 0,
<|code_end|>
, predict the next line using imports from the current file:
import os
import copy
import glob
import json
import logging
from django.db.models import Q
from django.db.models.signals import post_save
from django.contrib.contenttypes.models import ContentType
from opencivicdata.legislative.models import LegislativeSession
from pupa import settings
from pupa.exceptions import DuplicateItemError
from pupa.utils import get_pseudo_id, utcnow
from pupa.exceptions import UnresolvedIdError, DataImportError
from pupa.models import Identifier
and context including class names, function names, and sometimes code from other files:
# Path: pupa/settings.py
# DATABASE_URL = os.environ.get('DATABASE_URL', 'postgis://pupa:pupa@localhost/opencivicdata')
# SECRET_KEY = 'non-secret'
# INSTALLED_APPS = ('django.contrib.contenttypes',
# 'opencivicdata.core.apps.BaseConfig',
# 'opencivicdata.legislative.apps.BaseConfig',
# 'pupa')
# SCRAPELIB_RPM = 60
# SCRAPELIB_TIMEOUT = 60
# SCRAPELIB_RETRY_ATTEMPTS = 3
# SCRAPELIB_RETRY_WAIT_SECONDS = 10
# SCRAPELIB_VERIFY = True
# CACHE_DIR = os.path.join(os.getcwd(), '_cache')
# SCRAPED_DATA_DIR = os.path.join(os.getcwd(), '_data')
# ENABLE_PEOPLE_AND_ORGS = True
# ENABLE_BILLS = True
# ENABLE_VOTES = True
# ENABLE_EVENTS = True
# IMPORT_TRANSFORMERS = {
# 'bill': []
# }
# DEBUG = False
# TEMPLATE_DEBUG = False
# MIDDLEWARE_CLASSES = ()
# LOGGING = {
# 'version': 1,
# 'disable_existing_loggers': False,
# 'formatters': {
# 'standard': {
# 'format': "%(asctime)s %(levelname)s %(name)s: %(message)s",
# 'datefmt': '%H:%M:%S'
# }
# },
# 'handlers': {
# 'default': {'level': 'DEBUG',
# 'class': 'pupa.ext.ansistrm.ColorizingStreamHandler',
# 'formatter': 'standard'},
# },
# 'loggers': {
# '': {
# 'handlers': ['default'], 'level': 'DEBUG', 'propagate': True
# },
# 'scrapelib': {
# 'handlers': ['default'], 'level': 'INFO', 'propagate': False
# },
# 'requests': {
# 'handlers': ['default'], 'level': 'WARN', 'propagate': False
# },
# 'boto': {
# 'handlers': ['default'], 'level': 'WARN', 'propagate': False
# },
# },
# }
# DATABASES = {'default': dj_database_url.parse(DATABASE_URL)}
#
# Path: pupa/exceptions.py
# class DuplicateItemError(DataImportError):
# """ Attempt was made to import items that resolve to the same database item. """
#
# def __init__(self, data, obj, data_sources=None):
# super(DuplicateItemError, self).__init__(
# 'attempt to import data that would conflict with '
# 'data already in the import: {} '
# '(already imported as {})\n'
# 'obj1 sources: {}\nobj2 sources: {}'.format(
# data,
# obj,
# list(obj.sources.values_list('url', flat=True)
# if hasattr(obj, 'sources') else []),
# [s['url'] for s in data_sources or []]
# ))
#
# Path: pupa/utils/generic.py
# def get_pseudo_id(pid):
# if pid[0] != '~':
# raise ValueError("pseudo id doesn't start with ~")
# return json.loads(pid[1:])
#
# def utcnow():
# return datetime.datetime.now(datetime.timezone.utc)
#
# Path: pupa/exceptions.py
# class UnresolvedIdError(DataImportError):
# """ Attempt was made to resolve an id that has no result. """
#
# class DataImportError(PupaError):
# """ A generic error related to the import process. """
#
# Path: pupa/models.py
# class Identifier(models.Model):
# identifier = models.CharField(max_length=300)
# jurisdiction = models.ForeignKey(Jurisdiction,
# related_name='pupa_ids',
# on_delete=models.CASCADE,
# )
# content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
# object_id = models.CharField(max_length=300)
# content_object = GenericForeignKey('content_type', 'object_id')
#
# def __str__(self): # __unicode__ on Python 2
# return self.identifier
. Output only the next line. | 'start': utcnow(), |
Given the following code snippet before the placeholder: <|code_start|> raises:
ValueError if id couldn't be resolved
"""
if not json_id:
return None
if json_id.startswith('~'):
# keep caches of all the pseudo-ids to avoid doing 1000s of lookups during import
if json_id not in self.pseudo_id_cache:
spec = get_pseudo_id(json_id)
spec = self.limit_spec(spec)
if isinstance(spec, Q):
objects = self.model_class.objects.filter(spec)
else:
objects = self.model_class.objects.filter(**spec)
ids = {each.id for each in objects}
if len(ids) == 1:
self.pseudo_id_cache[json_id] = ids.pop()
errmsg = None
elif not ids:
errmsg = 'cannot resolve pseudo id to {}: {}'.format(
self.model_class.__name__, json_id)
else:
errmsg = 'multiple objects returned for {} pseudo id {}: {}'.format(
self.model_class.__name__, json_id, ids)
# either raise or log error
if errmsg:
if not allow_no_match:
<|code_end|>
, predict the next line using imports from the current file:
import os
import copy
import glob
import json
import logging
from django.db.models import Q
from django.db.models.signals import post_save
from django.contrib.contenttypes.models import ContentType
from opencivicdata.legislative.models import LegislativeSession
from pupa import settings
from pupa.exceptions import DuplicateItemError
from pupa.utils import get_pseudo_id, utcnow
from pupa.exceptions import UnresolvedIdError, DataImportError
from pupa.models import Identifier
and context including class names, function names, and sometimes code from other files:
# Path: pupa/settings.py
# DATABASE_URL = os.environ.get('DATABASE_URL', 'postgis://pupa:pupa@localhost/opencivicdata')
# SECRET_KEY = 'non-secret'
# INSTALLED_APPS = ('django.contrib.contenttypes',
# 'opencivicdata.core.apps.BaseConfig',
# 'opencivicdata.legislative.apps.BaseConfig',
# 'pupa')
# SCRAPELIB_RPM = 60
# SCRAPELIB_TIMEOUT = 60
# SCRAPELIB_RETRY_ATTEMPTS = 3
# SCRAPELIB_RETRY_WAIT_SECONDS = 10
# SCRAPELIB_VERIFY = True
# CACHE_DIR = os.path.join(os.getcwd(), '_cache')
# SCRAPED_DATA_DIR = os.path.join(os.getcwd(), '_data')
# ENABLE_PEOPLE_AND_ORGS = True
# ENABLE_BILLS = True
# ENABLE_VOTES = True
# ENABLE_EVENTS = True
# IMPORT_TRANSFORMERS = {
# 'bill': []
# }
# DEBUG = False
# TEMPLATE_DEBUG = False
# MIDDLEWARE_CLASSES = ()
# LOGGING = {
# 'version': 1,
# 'disable_existing_loggers': False,
# 'formatters': {
# 'standard': {
# 'format': "%(asctime)s %(levelname)s %(name)s: %(message)s",
# 'datefmt': '%H:%M:%S'
# }
# },
# 'handlers': {
# 'default': {'level': 'DEBUG',
# 'class': 'pupa.ext.ansistrm.ColorizingStreamHandler',
# 'formatter': 'standard'},
# },
# 'loggers': {
# '': {
# 'handlers': ['default'], 'level': 'DEBUG', 'propagate': True
# },
# 'scrapelib': {
# 'handlers': ['default'], 'level': 'INFO', 'propagate': False
# },
# 'requests': {
# 'handlers': ['default'], 'level': 'WARN', 'propagate': False
# },
# 'boto': {
# 'handlers': ['default'], 'level': 'WARN', 'propagate': False
# },
# },
# }
# DATABASES = {'default': dj_database_url.parse(DATABASE_URL)}
#
# Path: pupa/exceptions.py
# class DuplicateItemError(DataImportError):
# """ Attempt was made to import items that resolve to the same database item. """
#
# def __init__(self, data, obj, data_sources=None):
# super(DuplicateItemError, self).__init__(
# 'attempt to import data that would conflict with '
# 'data already in the import: {} '
# '(already imported as {})\n'
# 'obj1 sources: {}\nobj2 sources: {}'.format(
# data,
# obj,
# list(obj.sources.values_list('url', flat=True)
# if hasattr(obj, 'sources') else []),
# [s['url'] for s in data_sources or []]
# ))
#
# Path: pupa/utils/generic.py
# def get_pseudo_id(pid):
# if pid[0] != '~':
# raise ValueError("pseudo id doesn't start with ~")
# return json.loads(pid[1:])
#
# def utcnow():
# return datetime.datetime.now(datetime.timezone.utc)
#
# Path: pupa/exceptions.py
# class UnresolvedIdError(DataImportError):
# """ Attempt was made to resolve an id that has no result. """
#
# class DataImportError(PupaError):
# """ A generic error related to the import process. """
#
# Path: pupa/models.py
# class Identifier(models.Model):
# identifier = models.CharField(max_length=300)
# jurisdiction = models.ForeignKey(Jurisdiction,
# related_name='pupa_ids',
# on_delete=models.CASCADE,
# )
# content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
# object_id = models.CharField(max_length=300)
# content_object = GenericForeignKey('content_type', 'object_id')
#
# def __str__(self): # __unicode__ on Python 2
# return self.identifier
. Output only the next line. | raise UnresolvedIdError(errmsg) |
Next line prediction: <|code_start|> pupa_id = data.pop('pupa_id', None)
# pull related fields off
related = {}
for field in self.related_models:
related[field] = data.pop(field)
# obj existed, check if we need to do an update
if obj:
if obj.id in self.json_to_db_id.values():
raise DuplicateItemError(data, obj, related.get('sources', []))
# check base object for changes
for key, value in data.items():
if getattr(obj, key) != value and key not in obj.locked_fields:
setattr(obj, key, value)
what = 'update'
updated = self._update_related(obj, related, self.related_models)
if updated:
what = 'update'
if what == 'update':
obj.save()
# need to create the data
else:
what = 'insert'
try:
obj = self.model_class.objects.create(**data)
except Exception as e:
<|code_end|>
. Use current file imports:
(import os
import copy
import glob
import json
import logging
from django.db.models import Q
from django.db.models.signals import post_save
from django.contrib.contenttypes.models import ContentType
from opencivicdata.legislative.models import LegislativeSession
from pupa import settings
from pupa.exceptions import DuplicateItemError
from pupa.utils import get_pseudo_id, utcnow
from pupa.exceptions import UnresolvedIdError, DataImportError
from pupa.models import Identifier)
and context including class names, function names, or small code snippets from other files:
# Path: pupa/settings.py
# DATABASE_URL = os.environ.get('DATABASE_URL', 'postgis://pupa:pupa@localhost/opencivicdata')
# SECRET_KEY = 'non-secret'
# INSTALLED_APPS = ('django.contrib.contenttypes',
# 'opencivicdata.core.apps.BaseConfig',
# 'opencivicdata.legislative.apps.BaseConfig',
# 'pupa')
# SCRAPELIB_RPM = 60
# SCRAPELIB_TIMEOUT = 60
# SCRAPELIB_RETRY_ATTEMPTS = 3
# SCRAPELIB_RETRY_WAIT_SECONDS = 10
# SCRAPELIB_VERIFY = True
# CACHE_DIR = os.path.join(os.getcwd(), '_cache')
# SCRAPED_DATA_DIR = os.path.join(os.getcwd(), '_data')
# ENABLE_PEOPLE_AND_ORGS = True
# ENABLE_BILLS = True
# ENABLE_VOTES = True
# ENABLE_EVENTS = True
# IMPORT_TRANSFORMERS = {
# 'bill': []
# }
# DEBUG = False
# TEMPLATE_DEBUG = False
# MIDDLEWARE_CLASSES = ()
# LOGGING = {
# 'version': 1,
# 'disable_existing_loggers': False,
# 'formatters': {
# 'standard': {
# 'format': "%(asctime)s %(levelname)s %(name)s: %(message)s",
# 'datefmt': '%H:%M:%S'
# }
# },
# 'handlers': {
# 'default': {'level': 'DEBUG',
# 'class': 'pupa.ext.ansistrm.ColorizingStreamHandler',
# 'formatter': 'standard'},
# },
# 'loggers': {
# '': {
# 'handlers': ['default'], 'level': 'DEBUG', 'propagate': True
# },
# 'scrapelib': {
# 'handlers': ['default'], 'level': 'INFO', 'propagate': False
# },
# 'requests': {
# 'handlers': ['default'], 'level': 'WARN', 'propagate': False
# },
# 'boto': {
# 'handlers': ['default'], 'level': 'WARN', 'propagate': False
# },
# },
# }
# DATABASES = {'default': dj_database_url.parse(DATABASE_URL)}
#
# Path: pupa/exceptions.py
# class DuplicateItemError(DataImportError):
# """ Attempt was made to import items that resolve to the same database item. """
#
# def __init__(self, data, obj, data_sources=None):
# super(DuplicateItemError, self).__init__(
# 'attempt to import data that would conflict with '
# 'data already in the import: {} '
# '(already imported as {})\n'
# 'obj1 sources: {}\nobj2 sources: {}'.format(
# data,
# obj,
# list(obj.sources.values_list('url', flat=True)
# if hasattr(obj, 'sources') else []),
# [s['url'] for s in data_sources or []]
# ))
#
# Path: pupa/utils/generic.py
# def get_pseudo_id(pid):
# if pid[0] != '~':
# raise ValueError("pseudo id doesn't start with ~")
# return json.loads(pid[1:])
#
# def utcnow():
# return datetime.datetime.now(datetime.timezone.utc)
#
# Path: pupa/exceptions.py
# class UnresolvedIdError(DataImportError):
# """ Attempt was made to resolve an id that has no result. """
#
# class DataImportError(PupaError):
# """ A generic error related to the import process. """
#
# Path: pupa/models.py
# class Identifier(models.Model):
# identifier = models.CharField(max_length=300)
# jurisdiction = models.ForeignKey(Jurisdiction,
# related_name='pupa_ids',
# on_delete=models.CASCADE,
# )
# content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
# object_id = models.CharField(max_length=300)
# content_object = GenericForeignKey('content_type', 'object_id')
#
# def __str__(self): # __unicode__ on Python 2
# return self.identifier
. Output only the next line. | raise DataImportError('{} while importing {} as {}'.format(e, data, |
Using the snippet: <|code_start|> if obj.id in self.json_to_db_id.values():
raise DuplicateItemError(data, obj, related.get('sources', []))
# check base object for changes
for key, value in data.items():
if getattr(obj, key) != value and key not in obj.locked_fields:
setattr(obj, key, value)
what = 'update'
updated = self._update_related(obj, related, self.related_models)
if updated:
what = 'update'
if what == 'update':
obj.save()
# need to create the data
else:
what = 'insert'
try:
obj = self.model_class.objects.create(**data)
except Exception as e:
raise DataImportError('{} while importing {} as {}'.format(e, data,
self.model_class))
self._create_related(obj, related, self.related_models)
# Fire post-save signal after related objects are created to allow
# for handlers make use of related objects
post_save.send(sender=self.model_class, instance=obj, created=True)
if pupa_id:
<|code_end|>
, determine the next line of code. You have imports:
import os
import copy
import glob
import json
import logging
from django.db.models import Q
from django.db.models.signals import post_save
from django.contrib.contenttypes.models import ContentType
from opencivicdata.legislative.models import LegislativeSession
from pupa import settings
from pupa.exceptions import DuplicateItemError
from pupa.utils import get_pseudo_id, utcnow
from pupa.exceptions import UnresolvedIdError, DataImportError
from pupa.models import Identifier
and context (class names, function names, or code) available:
# Path: pupa/settings.py
# DATABASE_URL = os.environ.get('DATABASE_URL', 'postgis://pupa:pupa@localhost/opencivicdata')
# SECRET_KEY = 'non-secret'
# INSTALLED_APPS = ('django.contrib.contenttypes',
# 'opencivicdata.core.apps.BaseConfig',
# 'opencivicdata.legislative.apps.BaseConfig',
# 'pupa')
# SCRAPELIB_RPM = 60
# SCRAPELIB_TIMEOUT = 60
# SCRAPELIB_RETRY_ATTEMPTS = 3
# SCRAPELIB_RETRY_WAIT_SECONDS = 10
# SCRAPELIB_VERIFY = True
# CACHE_DIR = os.path.join(os.getcwd(), '_cache')
# SCRAPED_DATA_DIR = os.path.join(os.getcwd(), '_data')
# ENABLE_PEOPLE_AND_ORGS = True
# ENABLE_BILLS = True
# ENABLE_VOTES = True
# ENABLE_EVENTS = True
# IMPORT_TRANSFORMERS = {
# 'bill': []
# }
# DEBUG = False
# TEMPLATE_DEBUG = False
# MIDDLEWARE_CLASSES = ()
# LOGGING = {
# 'version': 1,
# 'disable_existing_loggers': False,
# 'formatters': {
# 'standard': {
# 'format': "%(asctime)s %(levelname)s %(name)s: %(message)s",
# 'datefmt': '%H:%M:%S'
# }
# },
# 'handlers': {
# 'default': {'level': 'DEBUG',
# 'class': 'pupa.ext.ansistrm.ColorizingStreamHandler',
# 'formatter': 'standard'},
# },
# 'loggers': {
# '': {
# 'handlers': ['default'], 'level': 'DEBUG', 'propagate': True
# },
# 'scrapelib': {
# 'handlers': ['default'], 'level': 'INFO', 'propagate': False
# },
# 'requests': {
# 'handlers': ['default'], 'level': 'WARN', 'propagate': False
# },
# 'boto': {
# 'handlers': ['default'], 'level': 'WARN', 'propagate': False
# },
# },
# }
# DATABASES = {'default': dj_database_url.parse(DATABASE_URL)}
#
# Path: pupa/exceptions.py
# class DuplicateItemError(DataImportError):
# """ Attempt was made to import items that resolve to the same database item. """
#
# def __init__(self, data, obj, data_sources=None):
# super(DuplicateItemError, self).__init__(
# 'attempt to import data that would conflict with '
# 'data already in the import: {} '
# '(already imported as {})\n'
# 'obj1 sources: {}\nobj2 sources: {}'.format(
# data,
# obj,
# list(obj.sources.values_list('url', flat=True)
# if hasattr(obj, 'sources') else []),
# [s['url'] for s in data_sources or []]
# ))
#
# Path: pupa/utils/generic.py
# def get_pseudo_id(pid):
# if pid[0] != '~':
# raise ValueError("pseudo id doesn't start with ~")
# return json.loads(pid[1:])
#
# def utcnow():
# return datetime.datetime.now(datetime.timezone.utc)
#
# Path: pupa/exceptions.py
# class UnresolvedIdError(DataImportError):
# """ Attempt was made to resolve an id that has no result. """
#
# class DataImportError(PupaError):
# """ A generic error related to the import process. """
#
# Path: pupa/models.py
# class Identifier(models.Model):
# identifier = models.CharField(max_length=300)
# jurisdiction = models.ForeignKey(Jurisdiction,
# related_name='pupa_ids',
# on_delete=models.CASCADE,
# )
# content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
# object_id = models.CharField(max_length=300)
# content_object = GenericForeignKey('content_type', 'object_id')
#
# def __str__(self): # __unicode__ on Python 2
# return self.identifier
. Output only the next line. | Identifier.objects.get_or_create(identifier=pupa_id, |
Based on the snippet: <|code_start|>
schema = {
"properties": {
"label": {"type": "string"},
"role": {"type": "string"},
"person_id": {"type": ["string", "null"]},
"person_name": {"type": ["string"], "minLength": 1},
"organization_id": {"type": "string", "minLength": 1},
"post_id": {"type": ["string", "null"]},
"on_behalf_of_id": {"type": ["string", "null"]},
"start_date": fuzzy_date_blank,
"end_date": fuzzy_date_blank,
"contact_details": contact_details,
<|code_end|>
, predict the immediate next line with the help of imports:
from .common import links, contact_details, extras, fuzzy_date_blank
and context (classes, functions, sometimes code) from other files:
# Path: pupa/scrape/schemas/common.py
. Output only the next line. | "links": links, |
Given the code snippet: <|code_start|>
schema = {
"properties": {
"label": {"type": "string"},
"role": {"type": "string"},
"person_id": {"type": ["string", "null"]},
"person_name": {"type": ["string"], "minLength": 1},
"organization_id": {"type": "string", "minLength": 1},
"post_id": {"type": ["string", "null"]},
"on_behalf_of_id": {"type": ["string", "null"]},
"start_date": fuzzy_date_blank,
"end_date": fuzzy_date_blank,
<|code_end|>
, generate the next line using the imports in this file:
from .common import links, contact_details, extras, fuzzy_date_blank
and context (functions, classes, or occasionally code) from other files:
# Path: pupa/scrape/schemas/common.py
. Output only the next line. | "contact_details": contact_details, |
Given the code snippet: <|code_start|>
schema = {
"properties": {
"label": {"type": "string"},
"role": {"type": "string"},
"person_id": {"type": ["string", "null"]},
"person_name": {"type": ["string"], "minLength": 1},
"organization_id": {"type": "string", "minLength": 1},
"post_id": {"type": ["string", "null"]},
"on_behalf_of_id": {"type": ["string", "null"]},
"start_date": fuzzy_date_blank,
"end_date": fuzzy_date_blank,
"contact_details": contact_details,
"links": links,
<|code_end|>
, generate the next line using the imports in this file:
from .common import links, contact_details, extras, fuzzy_date_blank
and context (functions, classes, or occasionally code) from other files:
# Path: pupa/scrape/schemas/common.py
. Output only the next line. | "extras": extras, |
Next line prediction: <|code_start|>
schema = {
"properties": {
"label": {"type": "string"},
"role": {"type": "string"},
"person_id": {"type": ["string", "null"]},
"person_name": {"type": ["string"], "minLength": 1},
"organization_id": {"type": "string", "minLength": 1},
"post_id": {"type": ["string", "null"]},
"on_behalf_of_id": {"type": ["string", "null"]},
<|code_end|>
. Use current file imports:
(from .common import links, contact_details, extras, fuzzy_date_blank)
and context including class names, function names, or small code snippets from other files:
# Path: pupa/scrape/schemas/common.py
. Output only the next line. | "start_date": fuzzy_date_blank, |
Predict the next line after this snippet: <|code_start|>
def create_jurisdictions():
Division.objects.create(id='ocd-division/country:us', name='USA')
Jurisdiction.objects.create(id='jid1', division_id='ocd-division/country:us')
Jurisdiction.objects.create(id='jid2', division_id='ocd-division/country:us')
def create_org():
o = Organization.objects.create(name='United Nations',
jurisdiction_id='jid1',
classification='international')
o.other_names.create(name='UN')
@pytest.mark.django_db
def test_full_organization():
create_jurisdictions()
<|code_end|>
using the current file's imports:
import pytest
from opencivicdata.core.models import Organization, Jurisdiction, Division
from pupa.scrape import Organization as ScrapeOrganization
from pupa.importers import OrganizationImporter
from pupa.exceptions import UnresolvedIdError, SameOrgNameError
and any relevant context from other files:
# Path: pupa/scrape/popolo.py
# class Organization(BaseModel, SourceMixin, ContactDetailMixin, LinkMixin, IdentifierMixin,
# OtherNameMixin):
# """
# A single popolo-style Organization
# """
#
# _type = 'organization'
# _schema = org_schema
#
# def __init__(self, name, *, classification='', parent_id=None,
# founding_date='', dissolution_date='', image='',
# chamber=None):
# """
# Constructor for the Organization object.
# """
# super(Organization, self).__init__()
# self.name = name
# self.classification = classification
# self.founding_date = founding_date
# self.dissolution_date = dissolution_date
# self.parent_id = pseudo_organization(parent_id, chamber)
# self.image = image
#
# def __str__(self):
# return self.name
#
# def validate(self):
# schema = None
# # these are implicitly declared & do not require sources
# if self.classification in ('party', 'legislature', 'upper', 'lower', 'executive'):
# schema = org_schema_no_sources
# return super(Organization, self).validate(schema=schema)
#
# def add_post(self, label, role, **kwargs):
# post = Post(label=label, role=role, organization_id=self._id, **kwargs)
# self._related.append(post)
# return post
#
# def add_member(self, name_or_person, role='member', **kwargs):
# if isinstance(name_or_person, Person):
# membership = Membership(person_id=name_or_person._id,
# person_name=name_or_person.name,
# organization_id=self._id,
# role=role, **kwargs)
# else:
# membership = Membership(person_id=_make_pseudo_id(name=name_or_person),
# person_name=name_or_person,
# organization_id=self._id, role=role, **kwargs)
# self._related.append(membership)
# return membership
#
# Path: pupa/exceptions.py
# class UnresolvedIdError(DataImportError):
# """ Attempt was made to resolve an id that has no result. """
#
# class SameOrgNameError(DataImportError):
# """ Attempt was made to import two orgs with the same name. """
#
# def __init__(self, name):
# super(SameOrgNameError, self).__init__('multiple orgs with same name "{}" in Jurisdiction '
# .format(name))
. Output only the next line. | org = ScrapeOrganization('United Nations', classification='international') |
Next line prediction: <|code_start|>
@pytest.mark.django_db
def test_deduplication_prevents_identical():
create_jurisdictions()
org1 = ScrapeOrganization('United Nations', classification='international')
org2 = ScrapeOrganization('United Nations', classification='international',
founding_date='1945')
OrganizationImporter('jid1').import_data([org1.as_dict()])
assert Organization.objects.count() == 1
OrganizationImporter('jid1').import_data([org2.as_dict()])
assert Organization.objects.count() == 1
@pytest.mark.django_db
def test_pseudo_ids():
create_jurisdictions()
wild = Organization.objects.create(id='1', name='Wild', classification='party')
senate = Organization.objects.create(id='2', name='Senate', classification='upper',
jurisdiction_id='jid1')
house = Organization.objects.create(id='3', name='House', classification='lower',
jurisdiction_id='jid1')
un = Organization.objects.create(id='4', name='United Nations', classification='international',
jurisdiction_id='jid2')
oi1 = OrganizationImporter('jid1')
assert oi1.resolve_json_id('~{"classification":"upper"}') == senate.id
assert oi1.resolve_json_id('~{"classification":"lower"}') == house.id
assert oi1.resolve_json_id('~{"classification":"party", "name":"Wild"}') == wild.id
<|code_end|>
. Use current file imports:
(import pytest
from opencivicdata.core.models import Organization, Jurisdiction, Division
from pupa.scrape import Organization as ScrapeOrganization
from pupa.importers import OrganizationImporter
from pupa.exceptions import UnresolvedIdError, SameOrgNameError)
and context including class names, function names, or small code snippets from other files:
# Path: pupa/scrape/popolo.py
# class Organization(BaseModel, SourceMixin, ContactDetailMixin, LinkMixin, IdentifierMixin,
# OtherNameMixin):
# """
# A single popolo-style Organization
# """
#
# _type = 'organization'
# _schema = org_schema
#
# def __init__(self, name, *, classification='', parent_id=None,
# founding_date='', dissolution_date='', image='',
# chamber=None):
# """
# Constructor for the Organization object.
# """
# super(Organization, self).__init__()
# self.name = name
# self.classification = classification
# self.founding_date = founding_date
# self.dissolution_date = dissolution_date
# self.parent_id = pseudo_organization(parent_id, chamber)
# self.image = image
#
# def __str__(self):
# return self.name
#
# def validate(self):
# schema = None
# # these are implicitly declared & do not require sources
# if self.classification in ('party', 'legislature', 'upper', 'lower', 'executive'):
# schema = org_schema_no_sources
# return super(Organization, self).validate(schema=schema)
#
# def add_post(self, label, role, **kwargs):
# post = Post(label=label, role=role, organization_id=self._id, **kwargs)
# self._related.append(post)
# return post
#
# def add_member(self, name_or_person, role='member', **kwargs):
# if isinstance(name_or_person, Person):
# membership = Membership(person_id=name_or_person._id,
# person_name=name_or_person.name,
# organization_id=self._id,
# role=role, **kwargs)
# else:
# membership = Membership(person_id=_make_pseudo_id(name=name_or_person),
# person_name=name_or_person,
# organization_id=self._id, role=role, **kwargs)
# self._related.append(membership)
# return membership
#
# Path: pupa/exceptions.py
# class UnresolvedIdError(DataImportError):
# """ Attempt was made to resolve an id that has no result. """
#
# class SameOrgNameError(DataImportError):
# """ Attempt was made to import two orgs with the same name. """
#
# def __init__(self, name):
# super(SameOrgNameError, self).__init__('multiple orgs with same name "{}" in Jurisdiction '
# .format(name))
. Output only the next line. | with pytest.raises(UnresolvedIdError): |
Given the code snippet: <|code_start|> OrganizationImporter('jid1').import_data([od])
assert Organization.objects.all().count() == 1
@pytest.mark.django_db
def test_deduplication_other_name_overlaps():
create_jurisdictions()
create_org()
org = ScrapeOrganization('The United Nations', classification='international')
org.add_name('United Nations')
od = org.as_dict()
OrganizationImporter('jid1').import_data([od])
assert Organization.objects.all().count() == 1
@pytest.mark.django_db
def test_deduplication_error_overlaps():
create_jurisdictions()
Organization.objects.create(name='World Wrestling Federation',
classification='international',
jurisdiction_id='jid1')
wildlife = Organization.objects.create(name='World Wildlife Fund',
classification='international',
jurisdiction_id='jid1')
wildlife.other_names.create(name='WWF')
org = ScrapeOrganization('World Wrestling Federation', classification='international')
org.add_name('WWF')
od = org.as_dict()
<|code_end|>
, generate the next line using the imports in this file:
import pytest
from opencivicdata.core.models import Organization, Jurisdiction, Division
from pupa.scrape import Organization as ScrapeOrganization
from pupa.importers import OrganizationImporter
from pupa.exceptions import UnresolvedIdError, SameOrgNameError
and context (functions, classes, or occasionally code) from other files:
# Path: pupa/scrape/popolo.py
# class Organization(BaseModel, SourceMixin, ContactDetailMixin, LinkMixin, IdentifierMixin,
# OtherNameMixin):
# """
# A single popolo-style Organization
# """
#
# _type = 'organization'
# _schema = org_schema
#
# def __init__(self, name, *, classification='', parent_id=None,
# founding_date='', dissolution_date='', image='',
# chamber=None):
# """
# Constructor for the Organization object.
# """
# super(Organization, self).__init__()
# self.name = name
# self.classification = classification
# self.founding_date = founding_date
# self.dissolution_date = dissolution_date
# self.parent_id = pseudo_organization(parent_id, chamber)
# self.image = image
#
# def __str__(self):
# return self.name
#
# def validate(self):
# schema = None
# # these are implicitly declared & do not require sources
# if self.classification in ('party', 'legislature', 'upper', 'lower', 'executive'):
# schema = org_schema_no_sources
# return super(Organization, self).validate(schema=schema)
#
# def add_post(self, label, role, **kwargs):
# post = Post(label=label, role=role, organization_id=self._id, **kwargs)
# self._related.append(post)
# return post
#
# def add_member(self, name_or_person, role='member', **kwargs):
# if isinstance(name_or_person, Person):
# membership = Membership(person_id=name_or_person._id,
# person_name=name_or_person.name,
# organization_id=self._id,
# role=role, **kwargs)
# else:
# membership = Membership(person_id=_make_pseudo_id(name=name_or_person),
# person_name=name_or_person,
# organization_id=self._id, role=role, **kwargs)
# self._related.append(membership)
# return membership
#
# Path: pupa/exceptions.py
# class UnresolvedIdError(DataImportError):
# """ Attempt was made to resolve an id that has no result. """
#
# class SameOrgNameError(DataImportError):
# """ Attempt was made to import two orgs with the same name. """
#
# def __init__(self, name):
# super(SameOrgNameError, self).__init__('multiple orgs with same name "{}" in Jurisdiction '
# .format(name))
. Output only the next line. | with pytest.raises(SameOrgNameError): |
Predict the next line after this snippet: <|code_start|> logger.error('exception "%s" prevented loading of %s module', e, mod)
# process args
args, other = parser.parse_known_args()
# set log level from command line
handler_level = getattr(logging, args.loglevel.upper(), 'INFO')
settings.LOGGING['handlers']['default']['level'] = handler_level
logging.config.dictConfig(settings.LOGGING)
# turn debug on
if args.debug:
try:
debug_module = importlib.import_module('ipdb')
except ImportError:
debug_module = importlib.import_module('pdb')
# turn on PDB-on-error mode
# stolen from http://stackoverflow.com/questions/1237379/
# if this causes problems in interactive mode check that page
def _tb_info(type, value, tb):
traceback.print_exception(type, value, tb)
debug_module.pm()
sys.excepthook = _tb_info
if not args.subcommand:
parser.print_help()
else:
try:
subcommands[args.subcommand].handle(args, other)
<|code_end|>
using the current file's imports:
import os
import sys
import logging.config
import argparse
import importlib
import traceback
from django.conf import settings
from pupa.exceptions import CommandError
and any relevant context from other files:
# Path: pupa/exceptions.py
# class CommandError(PupaError):
# """ Errors from within pupa CLI """
. Output only the next line. | except CommandError as e: |
Continue the code snippet: <|code_start|> self.set_bill(bill, chamber=bill_chamber)
if isinstance(bill, Bill) and not self.legislative_session:
self.legislative_session = bill.legislative_session
if not self.legislative_session:
raise ScrapeValueError('must set legislative_session or bill')
self.organization = pseudo_organization(organization, chamber, 'legislature')
self.votes = []
self.counts = []
def __str__(self):
return '{0} - {1} - {2}'.format(self.legislative_session, self.start_date,
self.motion_text)
def set_bill(self, bill_or_identifier, *, chamber=None):
if not bill_or_identifier:
self.bill = None
elif isinstance(bill_or_identifier, Bill):
if chamber:
raise ScrapeValueError("set_bill takes no arguments when using a `Bill` object")
self.bill = bill_or_identifier._id
else:
if chamber is None:
chamber = 'legislature'
kwargs = {'identifier': bill_or_identifier,
'from_organization__classification': chamber,
'legislative_session__identifier': self.legislative_session
}
<|code_end|>
. Use current file imports:
from ..utils import _make_pseudo_id
from .base import BaseModel, cleanup_list, SourceMixin
from .bill import Bill
from .popolo import pseudo_organization
from .schemas.vote_event import schema
from pupa.exceptions import ScrapeValueError
import re
and context (classes, functions, or code) from other files:
# Path: pupa/utils/generic.py
# def _make_pseudo_id(**kwargs):
# """ pseudo ids are just JSON """
# # ensure keys are sorted so that these are deterministic
# return '~' + json.dumps(kwargs, sort_keys=True)
#
# Path: pupa/scrape/base.py
# class BaseModel(object):
# """
# This is the base class for all the Open Civic objects. This contains
# common methods and abstractions for OCD objects.
# """
#
# # to be overridden by children. Something like "person" or "organization".
# # Used in :func:`validate`.
# _type = None
# _schema = None
#
# def __init__(self):
# super(BaseModel, self).__init__()
# self._id = str(uuid.uuid1())
# self._related = []
# self.extras = {}
#
# # validation
#
# def validate(self, schema=None):
# """
# Validate that we have a valid object.
#
# On error, this will raise a `ScrapeValueError`
#
# This also expects that the schemas assume that omitting required
# in the schema asserts the field is optional, not required. This is
# due to upstream schemas being in JSON Schema v3, and not validictory's
# modified syntax.
# ^ TODO: FIXME
# """
# if schema is None:
# schema = self._schema
#
# type_checker = Draft3Validator.TYPE_CHECKER.redefine(
# "datetime", lambda c, d: isinstance(d, (datetime.date, datetime.datetime))
# )
# type_checker = type_checker.redefine(
# "date", lambda c, d: (isinstance(d, datetime.date)
# and not isinstance(d, datetime.datetime))
# )
#
# ValidatorCls = jsonschema.validators.extend(Draft3Validator, type_checker=type_checker)
# validator = ValidatorCls(schema, format_checker=FormatChecker())
#
# errors = [str(error) for error in validator.iter_errors(self.as_dict())]
# if errors:
# raise ScrapeValueError('validation of {} {} failed: {}'.format(
# self.__class__.__name__, self._id, '\n\t'+'\n\t'.join(errors)
# ))
#
# def pre_save(self, jurisdiction_id):
# pass
#
# def as_dict(self):
# d = {}
# for attr in self._schema['properties'].keys():
# if hasattr(self, attr):
# d[attr] = getattr(self, attr)
# d['_id'] = self._id
# return d
#
# # operators
#
# def __setattr__(self, key, val):
# if key[0] != '_' and key not in self._schema['properties'].keys():
# raise ScrapeValueError('property "{}" not in {} schema'.format(key, self._type))
# super(BaseModel, self).__setattr__(key, val)
#
# def cleanup_list(obj, default):
# if not obj:
# obj = default
# elif isinstance(obj, str):
# obj = [obj]
# elif not isinstance(obj, list):
# obj = list(obj)
# return obj
#
# class SourceMixin(object):
# def __init__(self):
# super(SourceMixin, self).__init__()
# self.sources = []
#
# def add_source(self, url, *, note=''):
# """ Add a source URL from which data was collected """
# new = {'url': url, 'note': note}
# self.sources.append(new)
#
# Path: pupa/scrape/popolo.py
# def pseudo_organization(organization, classification, default=None):
# """ helper for setting an appropriate ID for organizations """
# if organization and classification:
# raise ScrapeValueError('cannot specify both classification and organization')
# elif classification:
# return _make_pseudo_id(classification=classification)
# elif organization:
# if isinstance(organization, Organization):
# return organization._id
# elif isinstance(organization, str):
# return organization
# else:
# return _make_pseudo_id(**organization)
# elif default is not None:
# return _make_pseudo_id(classification=default)
# else:
# return None
#
# Path: pupa/scrape/schemas/vote_event.py
#
# Path: pupa/exceptions.py
# class ScrapeValueError(PupaError, ValueError):
# """ An invalid value was passed to a pupa scrape object. """
. Output only the next line. | self.bill = _make_pseudo_id(**kwargs) |
Using the snippet: <|code_start|>
class VoteEvent(BaseModel, SourceMixin):
_type = 'vote_event'
_schema = schema
def __init__(self, *, motion_text, start_date, classification, result,
legislative_session=None, identifier='',
bill=None, bill_chamber=None, bill_action=None,
organization=None, chamber=None
):
super(VoteEvent, self).__init__()
self.legislative_session = legislative_session
self.motion_text = motion_text
<|code_end|>
, determine the next line of code. You have imports:
from ..utils import _make_pseudo_id
from .base import BaseModel, cleanup_list, SourceMixin
from .bill import Bill
from .popolo import pseudo_organization
from .schemas.vote_event import schema
from pupa.exceptions import ScrapeValueError
import re
and context (class names, function names, or code) available:
# Path: pupa/utils/generic.py
# def _make_pseudo_id(**kwargs):
# """ pseudo ids are just JSON """
# # ensure keys are sorted so that these are deterministic
# return '~' + json.dumps(kwargs, sort_keys=True)
#
# Path: pupa/scrape/base.py
# class BaseModel(object):
# """
# This is the base class for all the Open Civic objects. This contains
# common methods and abstractions for OCD objects.
# """
#
# # to be overridden by children. Something like "person" or "organization".
# # Used in :func:`validate`.
# _type = None
# _schema = None
#
# def __init__(self):
# super(BaseModel, self).__init__()
# self._id = str(uuid.uuid1())
# self._related = []
# self.extras = {}
#
# # validation
#
# def validate(self, schema=None):
# """
# Validate that we have a valid object.
#
# On error, this will raise a `ScrapeValueError`
#
# This also expects that the schemas assume that omitting required
# in the schema asserts the field is optional, not required. This is
# due to upstream schemas being in JSON Schema v3, and not validictory's
# modified syntax.
# ^ TODO: FIXME
# """
# if schema is None:
# schema = self._schema
#
# type_checker = Draft3Validator.TYPE_CHECKER.redefine(
# "datetime", lambda c, d: isinstance(d, (datetime.date, datetime.datetime))
# )
# type_checker = type_checker.redefine(
# "date", lambda c, d: (isinstance(d, datetime.date)
# and not isinstance(d, datetime.datetime))
# )
#
# ValidatorCls = jsonschema.validators.extend(Draft3Validator, type_checker=type_checker)
# validator = ValidatorCls(schema, format_checker=FormatChecker())
#
# errors = [str(error) for error in validator.iter_errors(self.as_dict())]
# if errors:
# raise ScrapeValueError('validation of {} {} failed: {}'.format(
# self.__class__.__name__, self._id, '\n\t'+'\n\t'.join(errors)
# ))
#
# def pre_save(self, jurisdiction_id):
# pass
#
# def as_dict(self):
# d = {}
# for attr in self._schema['properties'].keys():
# if hasattr(self, attr):
# d[attr] = getattr(self, attr)
# d['_id'] = self._id
# return d
#
# # operators
#
# def __setattr__(self, key, val):
# if key[0] != '_' and key not in self._schema['properties'].keys():
# raise ScrapeValueError('property "{}" not in {} schema'.format(key, self._type))
# super(BaseModel, self).__setattr__(key, val)
#
# def cleanup_list(obj, default):
# if not obj:
# obj = default
# elif isinstance(obj, str):
# obj = [obj]
# elif not isinstance(obj, list):
# obj = list(obj)
# return obj
#
# class SourceMixin(object):
# def __init__(self):
# super(SourceMixin, self).__init__()
# self.sources = []
#
# def add_source(self, url, *, note=''):
# """ Add a source URL from which data was collected """
# new = {'url': url, 'note': note}
# self.sources.append(new)
#
# Path: pupa/scrape/popolo.py
# def pseudo_organization(organization, classification, default=None):
# """ helper for setting an appropriate ID for organizations """
# if organization and classification:
# raise ScrapeValueError('cannot specify both classification and organization')
# elif classification:
# return _make_pseudo_id(classification=classification)
# elif organization:
# if isinstance(organization, Organization):
# return organization._id
# elif isinstance(organization, str):
# return organization
# else:
# return _make_pseudo_id(**organization)
# elif default is not None:
# return _make_pseudo_id(classification=default)
# else:
# return None
#
# Path: pupa/scrape/schemas/vote_event.py
#
# Path: pupa/exceptions.py
# class ScrapeValueError(PupaError, ValueError):
# """ An invalid value was passed to a pupa scrape object. """
. Output only the next line. | self.motion_classification = cleanup_list(classification, []) |
Predict the next line after this snippet: <|code_start|>
class VoteEvent(BaseModel, SourceMixin):
_type = 'vote_event'
_schema = schema
def __init__(self, *, motion_text, start_date, classification, result,
legislative_session=None, identifier='',
bill=None, bill_chamber=None, bill_action=None,
organization=None, chamber=None
):
super(VoteEvent, self).__init__()
self.legislative_session = legislative_session
self.motion_text = motion_text
self.motion_classification = cleanup_list(classification, [])
self.start_date = start_date
self.result = result
self.identifier = identifier
self.bill_action = bill_action
self.set_bill(bill, chamber=bill_chamber)
if isinstance(bill, Bill) and not self.legislative_session:
self.legislative_session = bill.legislative_session
if not self.legislative_session:
raise ScrapeValueError('must set legislative_session or bill')
<|code_end|>
using the current file's imports:
from ..utils import _make_pseudo_id
from .base import BaseModel, cleanup_list, SourceMixin
from .bill import Bill
from .popolo import pseudo_organization
from .schemas.vote_event import schema
from pupa.exceptions import ScrapeValueError
import re
and any relevant context from other files:
# Path: pupa/utils/generic.py
# def _make_pseudo_id(**kwargs):
# """ pseudo ids are just JSON """
# # ensure keys are sorted so that these are deterministic
# return '~' + json.dumps(kwargs, sort_keys=True)
#
# Path: pupa/scrape/base.py
# class BaseModel(object):
# """
# This is the base class for all the Open Civic objects. This contains
# common methods and abstractions for OCD objects.
# """
#
# # to be overridden by children. Something like "person" or "organization".
# # Used in :func:`validate`.
# _type = None
# _schema = None
#
# def __init__(self):
# super(BaseModel, self).__init__()
# self._id = str(uuid.uuid1())
# self._related = []
# self.extras = {}
#
# # validation
#
# def validate(self, schema=None):
# """
# Validate that we have a valid object.
#
# On error, this will raise a `ScrapeValueError`
#
# This also expects that the schemas assume that omitting required
# in the schema asserts the field is optional, not required. This is
# due to upstream schemas being in JSON Schema v3, and not validictory's
# modified syntax.
# ^ TODO: FIXME
# """
# if schema is None:
# schema = self._schema
#
# type_checker = Draft3Validator.TYPE_CHECKER.redefine(
# "datetime", lambda c, d: isinstance(d, (datetime.date, datetime.datetime))
# )
# type_checker = type_checker.redefine(
# "date", lambda c, d: (isinstance(d, datetime.date)
# and not isinstance(d, datetime.datetime))
# )
#
# ValidatorCls = jsonschema.validators.extend(Draft3Validator, type_checker=type_checker)
# validator = ValidatorCls(schema, format_checker=FormatChecker())
#
# errors = [str(error) for error in validator.iter_errors(self.as_dict())]
# if errors:
# raise ScrapeValueError('validation of {} {} failed: {}'.format(
# self.__class__.__name__, self._id, '\n\t'+'\n\t'.join(errors)
# ))
#
# def pre_save(self, jurisdiction_id):
# pass
#
# def as_dict(self):
# d = {}
# for attr in self._schema['properties'].keys():
# if hasattr(self, attr):
# d[attr] = getattr(self, attr)
# d['_id'] = self._id
# return d
#
# # operators
#
# def __setattr__(self, key, val):
# if key[0] != '_' and key not in self._schema['properties'].keys():
# raise ScrapeValueError('property "{}" not in {} schema'.format(key, self._type))
# super(BaseModel, self).__setattr__(key, val)
#
# def cleanup_list(obj, default):
# if not obj:
# obj = default
# elif isinstance(obj, str):
# obj = [obj]
# elif not isinstance(obj, list):
# obj = list(obj)
# return obj
#
# class SourceMixin(object):
# def __init__(self):
# super(SourceMixin, self).__init__()
# self.sources = []
#
# def add_source(self, url, *, note=''):
# """ Add a source URL from which data was collected """
# new = {'url': url, 'note': note}
# self.sources.append(new)
#
# Path: pupa/scrape/popolo.py
# def pseudo_organization(organization, classification, default=None):
# """ helper for setting an appropriate ID for organizations """
# if organization and classification:
# raise ScrapeValueError('cannot specify both classification and organization')
# elif classification:
# return _make_pseudo_id(classification=classification)
# elif organization:
# if isinstance(organization, Organization):
# return organization._id
# elif isinstance(organization, str):
# return organization
# else:
# return _make_pseudo_id(**organization)
# elif default is not None:
# return _make_pseudo_id(classification=default)
# else:
# return None
#
# Path: pupa/scrape/schemas/vote_event.py
#
# Path: pupa/exceptions.py
# class ScrapeValueError(PupaError, ValueError):
# """ An invalid value was passed to a pupa scrape object. """
. Output only the next line. | self.organization = pseudo_organization(organization, chamber, 'legislature') |
Given the following code snippet before the placeholder: <|code_start|>
class VoteEvent(BaseModel, SourceMixin):
_type = 'vote_event'
_schema = schema
def __init__(self, *, motion_text, start_date, classification, result,
legislative_session=None, identifier='',
bill=None, bill_chamber=None, bill_action=None,
organization=None, chamber=None
):
super(VoteEvent, self).__init__()
self.legislative_session = legislative_session
self.motion_text = motion_text
self.motion_classification = cleanup_list(classification, [])
self.start_date = start_date
self.result = result
self.identifier = identifier
self.bill_action = bill_action
self.set_bill(bill, chamber=bill_chamber)
if isinstance(bill, Bill) and not self.legislative_session:
self.legislative_session = bill.legislative_session
if not self.legislative_session:
<|code_end|>
, predict the next line using imports from the current file:
from ..utils import _make_pseudo_id
from .base import BaseModel, cleanup_list, SourceMixin
from .bill import Bill
from .popolo import pseudo_organization
from .schemas.vote_event import schema
from pupa.exceptions import ScrapeValueError
import re
and context including class names, function names, and sometimes code from other files:
# Path: pupa/utils/generic.py
# def _make_pseudo_id(**kwargs):
# """ pseudo ids are just JSON """
# # ensure keys are sorted so that these are deterministic
# return '~' + json.dumps(kwargs, sort_keys=True)
#
# Path: pupa/scrape/base.py
# class BaseModel(object):
# """
# This is the base class for all the Open Civic objects. This contains
# common methods and abstractions for OCD objects.
# """
#
# # to be overridden by children. Something like "person" or "organization".
# # Used in :func:`validate`.
# _type = None
# _schema = None
#
# def __init__(self):
# super(BaseModel, self).__init__()
# self._id = str(uuid.uuid1())
# self._related = []
# self.extras = {}
#
# # validation
#
# def validate(self, schema=None):
# """
# Validate that we have a valid object.
#
# On error, this will raise a `ScrapeValueError`
#
# This also expects that the schemas assume that omitting required
# in the schema asserts the field is optional, not required. This is
# due to upstream schemas being in JSON Schema v3, and not validictory's
# modified syntax.
# ^ TODO: FIXME
# """
# if schema is None:
# schema = self._schema
#
# type_checker = Draft3Validator.TYPE_CHECKER.redefine(
# "datetime", lambda c, d: isinstance(d, (datetime.date, datetime.datetime))
# )
# type_checker = type_checker.redefine(
# "date", lambda c, d: (isinstance(d, datetime.date)
# and not isinstance(d, datetime.datetime))
# )
#
# ValidatorCls = jsonschema.validators.extend(Draft3Validator, type_checker=type_checker)
# validator = ValidatorCls(schema, format_checker=FormatChecker())
#
# errors = [str(error) for error in validator.iter_errors(self.as_dict())]
# if errors:
# raise ScrapeValueError('validation of {} {} failed: {}'.format(
# self.__class__.__name__, self._id, '\n\t'+'\n\t'.join(errors)
# ))
#
# def pre_save(self, jurisdiction_id):
# pass
#
# def as_dict(self):
# d = {}
# for attr in self._schema['properties'].keys():
# if hasattr(self, attr):
# d[attr] = getattr(self, attr)
# d['_id'] = self._id
# return d
#
# # operators
#
# def __setattr__(self, key, val):
# if key[0] != '_' and key not in self._schema['properties'].keys():
# raise ScrapeValueError('property "{}" not in {} schema'.format(key, self._type))
# super(BaseModel, self).__setattr__(key, val)
#
# def cleanup_list(obj, default):
# if not obj:
# obj = default
# elif isinstance(obj, str):
# obj = [obj]
# elif not isinstance(obj, list):
# obj = list(obj)
# return obj
#
# class SourceMixin(object):
# def __init__(self):
# super(SourceMixin, self).__init__()
# self.sources = []
#
# def add_source(self, url, *, note=''):
# """ Add a source URL from which data was collected """
# new = {'url': url, 'note': note}
# self.sources.append(new)
#
# Path: pupa/scrape/popolo.py
# def pseudo_organization(organization, classification, default=None):
# """ helper for setting an appropriate ID for organizations """
# if organization and classification:
# raise ScrapeValueError('cannot specify both classification and organization')
# elif classification:
# return _make_pseudo_id(classification=classification)
# elif organization:
# if isinstance(organization, Organization):
# return organization._id
# elif isinstance(organization, str):
# return organization
# else:
# return _make_pseudo_id(**organization)
# elif default is not None:
# return _make_pseudo_id(classification=default)
# else:
# return None
#
# Path: pupa/scrape/schemas/vote_event.py
#
# Path: pupa/exceptions.py
# class ScrapeValueError(PupaError, ValueError):
# """ An invalid value was passed to a pupa scrape object. """
. Output only the next line. | raise ScrapeValueError('must set legislative_session or bill') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.